> 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.3_sessionprompt_entry_point.md). Agents can also search and read this documentation through its [MCP server](https://www.opencodebook.xyz/~gitbook/mcp).

# 4.3 SessionPrompt: The Entry Point of a Session

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

***

`SessionPrompt` (`session/prompt.ts`) is the gateway through which user messages enter OpenCode's core engine. It is responsible for receiving user input, preparing context, and then launching the Agentic Loop.

## 4.3.1 The Complete Execution Flow of the `prompt()` Method

```typescript
export const prompt = fn(PromptInput, async (input) => {
  // 1. Retrieve the session
  const session = await Session.get(input.sessionID)

  // 2. Clean up incomplete reverts
  await SessionRevert.cleanup(session)

  // 3. Create the user message
  const message = await createUserMessage(input)

  // 4. Update the session timestamp
  await Session.touch(input.sessionID)

  // 5. Handle runtime permission overrides (backward compatible)
  const permissions: PermissionNext.Ruleset = []
  for (const [tool, enabled] of Object.entries(input.tools ?? {})) {
    permissions.push({
      permission: tool,
      action: enabled ? "allow" : "deny",
      pattern: "*",
    })
  }

  // 6. If noReply is set, return immediately (do not trigger AI response)
  if (input.noReply === true) return message

  // 7. Enter the Agentic Loop
  return loop({ sessionID: input.sessionID })
})
```

**The `PromptInput` Structure**:

```typescript
export const PromptInput = z.object({
  sessionID: Identifier.schema("session"),
  messageID: Identifier.schema("message").optional(),
  model: z.object({
    providerID: z.string(),
    modelID: z.string(),
  }).optional(),
  agent: z.string().optional(),
  noReply: z.boolean().optional(),   // Store message only, do not trigger a reply
  system: z.string().optional(),     // Additional system instructions
  variant: z.string().optional(),
  parts: z.array(z.discriminatedUnion("type", [
    // TextPart, FilePart, AgentPart, SubtaskPart
  ])),
})
```

The `parts` array of a message supports multiple types -- the user can send not only text but also attach files, specify an Agent, or create subtasks.

## 4.3.2 The System Instruction Injection Mechanism

When the `loop()` function prepares the LLM call context, it loads system instructions via `InstructionPrompt` (`session/instruction.ts`).

**Instruction File Scanning**:

```typescript
const FILES = [
  "AGENTS.md",
  "CLAUDE.md",
  "CONTEXT.md", // deprecated
]
```

OpenCode searches for instruction files in the following locations:

1. **Global Locations**:

   ```
   ~/.config/opencode/AGENTS.md
   ~/.claude/CLAUDE.md          // Compatible with Claude Code's format
   ```
2. **Project Directory**: Searches upward level by level from the current working directory to the project root

   ```
   ./AGENTS.md
   ./CLAUDE.md
   ../AGENTS.md     (searching upward)
   ../../AGENTS.md   (continuing upward)
   ```

**Upward Search Logic** (`Filesystem.globUp`):

This is a key design decision -- it allows instruction files from the project root to be discovered even when working in a subdirectory. For example:

```
project/
+-- AGENTS.md              <-- Project-level instructions
+-- src/
|   +-- AGENTS.md          <-- src directory-level instructions
|   +-- auth/
|       +-- (current working directory)  <-- Will find src/AGENTS.md and project/AGENTS.md
```

**The Claim Mechanism** -- Preventing Duplicate Injection:

```typescript
function isClaimed(messageID: string, filepath: string) {
  const claimed = state().claims.get(messageID)
  if (!claimed) return false
  return claimed.has(filepath)
}
```

During the processing of a single message, each instruction file is injected only once. This prevents the same instructions from being loaded repeatedly across multiple conversation turns.

## 4.3.3 Message Preprocessing and Formatting

When creating user messages, `SessionPrompt` also handles some special syntax:

**`resolvePromptParts()`** -- Resolving References in Templates:

```typescript
export async function resolvePromptParts(template: string) {
  const parts: PromptInput["parts"] = [{ type: "text", text: template }]
  const files = ConfigMarkdown.files(template)

  for (const match of files) {
    const name = match[1]
    const filepath = name.startsWith("~/")
      ? path.join(os.homedir(), name.slice(2))
      : path.resolve(Instance.worktree, name)

    // Try as a file attachment
    const stats = await fs.stat(filepath).catch(() => undefined)
    if (stats) {
      parts.push({ type: "file", mime: "...", url: "...", filename: name })
    } else {
      // Try as an Agent reference
      const agent = await Agent.get(name)
      if (agent) {
        parts.push({ type: "agent", name: name })
      }
    }
  }
  return parts
}
```

This means users can reference file paths or Agent names within their messages, and the system will automatically resolve them into the corresponding Parts.
