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

# 12.4 Non-Interactive Mode

> **Model**: claude-opus-4-6 (anthropic/claude-opus-4-6) **Generated on**: 2026-02-17

***

OpenCode is not just an interactive tool—it can also run in non-interactive mode, making it suitable for CI/CD pipelines, automation scripts, and code generation scenarios.

## 12.4.1 The run Subcommand: Pipeline / CI Scenarios

`opencode run` is the core command for non-interactive mode. It accepts a prompt (via arguments or standard input), executes the Agentic Loop, streams the output, and then exits.

```bash
# Pass the prompt directly
opencode run "Fix the TypeScript errors in src/utils.ts"

# Pipe input
cat bug_report.md | opencode run

# Combined usage
echo "Add unit tests for the auth module" | opencode run --model anthropic/claude-sonnet-4

# Continue the previous session
opencode run -c "Now fix the remaining two test failures"

# Specify the output format
opencode run --format json "What files were modified?"
```

### Implementation Analysis

The handler function in `run.ts` demonstrates the complete non-interactive mode flow:

```typescript
// cli/cmd/run.ts (simplified)
export const RunCommand = cmd({
  command: "run [prompt]",
  builder: (yargs) => yargs
    .positional("prompt", { type: "string" })
    .option("continue", { alias: "c", type: "boolean" })
    .option("session", { alias: "s", type: "string" })
    .option("fork", { type: "boolean" })
    .option("model", { alias: "m", type: "string" })
    .option("agent", { type: "string" })
    .option("file", { alias: "f", type: "array" })
    .option("format", { type: "string", choices: ["json"] })
    .option("thinking", { type: "boolean" }),
  handler: async (args) => {
    await bootstrap(cwd, async () => {
      // 1. Create or continue a session
      const session = await resolveSession(args)

      // 2. Build the prompt (supports piped input + file attachments)
      const prompt = buildPrompt(args)

      // 3. Send the message and get the event stream
      const events = await sdk.session.chat({
        sessionID: session.id,
        content: prompt,
      })

      // 4. Process events in a streaming fashion
      for await (const event of events.stream) {
        switch (event.type) {
          case "message.part.updated":
            handlePartUpdate(event)  // Output text, tool calls, etc.
            break
          case "session.status":
            if (event.status === "idle") return  // Completed
            break
          case "permission.asked":
            handlePermission(event)  // Handled automatically in non-interactive mode
            break
        }
      }
    })
  },
})
```

### Formatted Output for Tool Calls

The `run` command provides concise formatted output for each tool type, letting users see what the Agent is doing in the terminal:

```typescript
function tool(part: ToolPart) {
  if (part.tool === "bash") return bash(props<typeof BashTool>(part))
  if (part.tool === "glob") return glob(props<typeof GlobTool>(part))
  if (part.tool === "read") return read(props<typeof ReadTool>(part))
  if (part.tool === "grep") return grep(props<typeof GrepTool>(part))
  if (part.tool === "edit") return edit(props<typeof EditTool>(part))
  if (part.tool === "write") return write(props<typeof WriteTool>(part))
  if (part.tool === "task") return task(props<typeof TaskTool>(part))
  // ... other tools
  return fallback(part)  // Unknown tools use a generic format
}
```

The output format for each tool is carefully designed to provide clear, compact information in the terminal:

```
✱ Glob "**/*.test.ts" in src/ · 12 matches
→ Read src/auth/auth.test.ts [offset=1, limit=50]
⎔ Edit src/auth/auth.ts (3 changes)
⚙ Bash npm test
  ✓ 47 passed, 0 failed
✱ Grep "TODO" in src/ · 3 matches
⌁ Task "Fix remaining TODOs" → session_abc123
```

### JSON Output Format

When using `--format json`, the `run` command outputs structured JSON that is easy to parse in scripts:

```bash
opencode run --format json "What files were modified?" | jq '.messages[-1].content'
```

### Piped Input Support

The `run` command supports receiving prompts via standard input (stdin):

```typescript
const prompt = await iife(async () => {
  const piped = !process.stdin.isTTY ? await Bun.stdin.text() : undefined
  if (!args.prompt) return piped
  return piped ? piped + "\n" + args.prompt : args.prompt
})
```

When standard input is not a TTY (e.g., when coming from a pipe or redirection), the content from stdin is read as a prefix to the prompt. This enables the following usage patterns:

```bash
# Use file contents as context
cat error_log.txt | opencode run "Analyze this error and suggest a fix"

# Combine with other tools in a pipeline
git diff | opencode run "Review this diff and suggest improvements"
```

## 12.4.2 The generate Subcommand: Code Generation Mode

`opencode generate` is another non-interactive command, used to generate OpenAPI specifications and code samples:

```typescript
// cli/cmd/generate.ts
export const GenerateCommand = cmd({
  command: "generate",
  describe: "generate openapi spec with code samples",
  handler: async (args) => {
    await bootstrap(cwd, async () => {
      // Generate the OpenAPI JSON
      const spec = generateOpenAPISpec()

      // Output to stdout or a file
      console.log(JSON.stringify(spec, null, 2))
    })
  },
})
```

This command is primarily intended for developer toolchains—the generated OpenAPI specification can be used to automatically generate SDKs, API documentation, or test clients.

## 12.4.3 The serve Subcommand: Headless Server

`opencode serve` starts an HTTP Server without a TUI, suitable for running in server environments:

```typescript
// cli/cmd/serve.ts
export const ServeCommand = cmd({
  command: "serve",
  describe: "starts a headless opencode server",
  handler: async (args) => {
    if (!Flag.OPENCODE_SERVER_PASSWORD) {
      console.log("Warning: OPENCODE_SERVER_PASSWORD is not set; server is unsecured.")
    }
    const opts = await resolveNetworkOptions(args)
    const server = Server.listen(opts)
    console.log(`opencode server listening on http://${server.hostname}:${server.port}`)
    // Keep the process running indefinitely
    await new Promise(() => {})
  },
})
```

Typical use cases for the `serve` command:

* **Remote development**: Run `opencode serve` on a remote server and access it from your local machine via the Web UI or SDK.
* **IDE integration**: IDE extensions connect to a running OpenCode Server.
* **Automation platforms**: Interact with OpenCode via its API to implement automated code reviews, refactoring, and more.

## 12.4.4 Other Non-Interactive Commands

OpenCode also provides a series of management commands, all operating in non-interactive mode:

```bash
# List available models
opencode models

# Manage authentication
opencode auth login
opencode auth status

# Manage MCP Servers
opencode mcp list
opencode mcp add <name> --command <cmd>

# Session management
opencode session list
opencode session export <id>

# Statistics
opencode stats

# Version management
opencode upgrade
opencode uninstall
```

## 12.4.5 Summary

OpenCode's non-interactive mode embodies the "Unix Philosophy"—each command does one thing well, and they can be combined through pipes and scripts to accomplish complex tasks:

1. **`run`**: Single execution with piped input support, suitable for CI/CD and automation scripts.
2. **`serve`**: Headless Server, suitable for remote and integration scenarios.
3. **`generate`**: Toolchain support, outputting structured data.
4. **Management commands**: Configuration and state management, supporting scripted operations.

This dual support for interactive and non-interactive modes allows OpenCode to serve both as a daily development interactive assistant and as a component integrated into automated workflows.
