> For the complete documentation index, see [llms.txt](https://www.opencodebook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.opencodebook.xyz/en/chapter_04_session_system/4.4_sessionprocessor_core_loop.md). Agents can also search and read this documentation through its [MCP server](https://www.opencodebook.xyz/~gitbook/mcp).

# 4.4 SessionProcessor: The Core of the Agentic Loop

> **Model**: claude-opus-4-6 (anthropic/claude-opus-4-6) **Generation Date**: 2025-02-17

***

`SessionProcessor` (`session/processor.ts`) is the most critical module in OpenCode -- it implements the complete logic of the Agentic Loop. Understanding it means understanding how an AI Agent "thinks" and "acts."

## 4.4.1 The Streaming State Machine

`SessionProcessor.create()` returns a processor object whose core is the `process()` method. Inside this method is a `while(true)` loop -- each iteration represents one generation step (Step) by the LLM.

The complete event handling of the state machine (simplified source):

```typescript
async process(streamInput: LLM.StreamInput) {
  while (true) {
    const stream = await LLM.stream(streamInput)

    for await (const value of stream.fullStream) {
      input.abort.throwIfAborted()  // Check if aborted by the user

      switch (value.type) {
        // === Chain-of-Thought Processing ===
        case "reasoning-start":
          // Create a new ReasoningPart
          reasoningMap[value.id] = {
            type: "reasoning", text: "",
            time: { start: Date.now() },
          }
          break

        case "reasoning-delta":
          // Append chain-of-thought text delta
          reasoningMap[value.id].text += value.text
          await Session.updatePart({ part, delta: value.text })
          break

        case "reasoning-end":
          // Complete the chain of thought, record end time
          part.time.end = Date.now()
          await Session.updatePart(part)
          break

        // === Text Generation Processing ===
        case "text-start":
          currentText = { type: "text", text: "", time: { start: Date.now() } }
          break

        case "text-delta":
          currentText.text += value.text
          await Session.updatePart({ part: currentText, delta: value.text })
          break

        // === Tool Call Processing ===
        case "tool-input-start":
          // Create a ToolPart, state = pending
          toolcalls[value.id] = await Session.updatePart({
            type: "tool", tool: value.toolName,
            state: { status: "pending", input: {}, raw: "" },
          })
          break

        case "tool-call":
          // Arguments complete, state -> running
          // * Doom Loop detection happens here *
          break

        case "tool-result":
          // Execution succeeded, state -> completed
          break

        case "tool-error":
          // Execution failed, state -> error
          break

        // === Step Boundaries ===
        case "start-step":
          snapshot = await Snapshot.track()  // Create a file snapshot
          break

        case "finish-step":
          // Tally tokens and cost
          // Check if Compaction is needed
          break
      }
    }

    // Post-iteration decision logic...
  }
}
```

## 4.4.2 The Tool Execution Loop

The full lifecycle of a tool invocation manifests in the Processor as four events:

```
tool-input-start  -> Create ToolPart (pending)
       |
tool-call         -> Update state (running), trigger Doom Loop detection
       |
     /    \
tool-result   tool-error
(completed)   (error)
```

**Doom Loop Detection** (source code):

```typescript
case "tool-call": {
  const match = toolcalls[value.toolCallId]
  if (match) {
    // Update to running state
    await Session.updatePart({ ...match, state: { status: "running", ... } })

    // * Doom Loop Detection *
    const parts = await MessageV2.parts(input.assistantMessage.id)
    const lastThree = parts.slice(-DOOM_LOOP_THRESHOLD) // Last 3 Parts

    if (
      lastThree.length === DOOM_LOOP_THRESHOLD &&
      lastThree.every(p =>
        p.type === "tool" &&
        p.tool === value.toolName &&                              // Same tool
        p.state.status !== "pending" &&
        JSON.stringify(p.state.input) === JSON.stringify(value.input) // Identical arguments
      )
    ) {
      // Trigger doom_loop permission check -- pause and ask the user
      await PermissionNext.ask({
        permission: "doom_loop",
        patterns: [value.toolName],
        metadata: { tool: value.toolName, input: value.input },
      })
    }
  }
  break
}
```

> **Extended Explanation: What Is a Doom Loop?**
>
> In AI Agent systems, a Doom Loop refers to the Agent repeatedly performing the same operation while expecting different results. For example:
>
> 1. AI reads a file -> finds an error -> modifies the file -> modification fails -> reads the file -> finds the same error -> modifies the file -> modification fails again -> ...
> 2. AI runs tests -> tests fail -> modifies code -> modified code is identical -> runs tests -> tests fail again -> ...
>
> OpenCode's detection strategy is straightforward: if the last 3 tool calls invoke the **same tool** with **identical arguments**, it is classified as a Doom Loop. At that point, a `doom_loop` permission check is triggered, and the default configuration is `"ask"` -- execution is paused, and the user decides whether to continue.

## 4.4.3 Snapshot Trigger Timing

At the start and end of each Step, the Processor interacts with the Snapshot system:

```typescript
case "start-step":
  snapshot = await Snapshot.track()  // Record the current file state
  break

case "finish-step":
  // ... token statistics ...
  if (snapshot) {
    const patch = await Snapshot.patch(snapshot) // Compute the diff
    if (patch.files.length) {
      await Session.updatePart({
        type: "patch", hash: patch.hash, files: patch.files,
      })
    }
  }
  break
```

This means **file changes in every Step are recorded as a Patch**. Users can inspect which files were modified in each step and can also use the Revert feature to roll back to any step.

## 4.4.4 The Retry Mechanism

`session/retry.ts` implements automatic retries for failed LLM API calls:

Retry trigger conditions:

* The API returns a retryable error (e.g., rate limit 429, server error 500)
* Output length exceeded (`OutputLengthError`)
* Network errors

Retry strategy:

* Uses Exponential Backoff
* Each retry creates a `RetryPart` record so the user can see the retry history
* A maximum retry count is enforced

## 4.4.5 Error Recovery Strategies

Error handling in the Processor is organized into several layers:

```typescript
// 1. Stream-level errors
case "error":
  throw value.error  // Propagate upward

// 2. Tool-level errors
case "tool-error":
  // Record the error but do not break the loop
  // Permission denials and question rejections set blocked = true
  if (value.error instanceof PermissionNext.RejectedError) {
    blocked = shouldBreak
  }
  break
```

```
// 3. API-level errors (handled inside LLM.stream)
try { await LLM.stream(...) }
catch (error) {
  if (isRetryable(error))  -> Auto-retry
  if (isAuthError(error))  -> Publish authentication error event
  if (isContextOverflow)   -> Trigger Compaction then retry
  else                     -> Record the error, end the loop
}
```

A key design decision: **tool execution failures do not break the Agentic Loop**. Error information is returned to the LLM as a tool result, letting the AI decide how to handle it -- this is the essence of being "Agentic": the AI has the ability to recover from errors on its own.
