新建会话
Ctrl
K
插件 定时任务
Kimi Work Kimi Code
  • 获取应用程序
  • 关于我们
  • Language
  • 帮助

Agent Token Efficiency

to what extent coding agent like opencode and claudecode helps in reducing token and achieving great agentic loop engineering. can you list out different task performed by coding agent to offload work done by LLM
Coding Agents: Planning, Token Savings, and Loop Engineering
The user is asking about coding agents (specifically mentioning OpenCode and Claude Code) and their impact on:
  1. Reducing token usage
  2. Achieving great "agentic loop engineering"
  3. A breakdown of tasks they perform to offload work from the LLM
This is a conceptual/technical question about AI agent architecture. I should provide a thorough, structured answer. I don't need to search for this as it's a general knowledge question about how coding agents work, though I could search for recent developments if needed. Given the user is deeply technical (from memory), I should be precise and avoid fluff.
Key concepts to cover:
  • What coding agents are (loop: plan → act → observe → reflect)
  • How they reduce token usage (caching, context management, tool use vs raw generation, stateful execution)
  • Agentic loop engineering (feedback loops, tool integration, error recovery, planning)
  • Specific tasks offloaded from the LLM (file I/O, search, execution, git operations, testing, etc.)
Let me structure this well.
Coding agents like OpenCode, Claude Code, Cursor Agent, and Devin represent a shift from raw LLM generation to stateful, tool-augmented execution loops. They don't just "write code"—they engineer a control plane that minimizes redundant LLM work and maximizes deterministic offloading.
Here is the breakdown of how they reduce token burn and what tasks they offload from the LLM.

1. Token Reduction Mechanisms

表格
复制
MechanismHow It Saves TokensEngineering Impact
Tool Use over GenerationInstead of the LLM generating a full file diff in text, it emits a structured tool call (edit_file, read_file). The agent handles the I/O.~60-90% reduction on large file operations.
Read-Only Context DeltasAgents maintain a file system cache. The LLM only receives changes (diffs) or explicit reads, not the full codebase on every turn.Avoids O(n) context growth where n = repo size.
Execution Feedback LoopsThe agent runs tests/linters locally and pipes back only the error snippet, not the full output.LLM sees SyntaxError: line 42 instead of 500 lines of stdout.
Plan CachingMulti-step tasks are decomposed into a plan (stored in agent state). The LLM validates steps, not regenerates the plan each turn.Reduces repetitive reasoning tokens.
Semantic Retrieval (RAG)Code search, grep, and AST indexing happen outside the LLM. The agent injects only relevant snippets.Prevents the LLM from "reading" the entire repo to find a function.
Checkpointing / RollbackFailed attempts are reverted locally. The LLM is not asked to "undo" or regenerate from scratch.Eliminates error-correction token spirals.

2. The Agentic Loop Architecture

A well-engineered coding agent loop looks like this:
plain
复制
┌─────────────┐     ┌──────────────┐     ┌─────────────┐
│   Planner   │────▶│   Executor   │────▶│   Observer  │
│  (LLM)      │     │  (Tools/Env) │     │  (LLM/Logs) │
└─────────────┘     └──────────────┘     └──────┬──────┘
       ▲────────────────────────────────────────┘
                    (Feedback / Reflection)
Key engineering decisions in the loop:
  • Deterministic shell vs. LLM shell: The agent decides whether to use grep (deterministic, no tokens) or ask the LLM to analyze (expensive, fuzzy).
  • Error taxonomy: The observer classifies failures (syntax, test, logic, permission) and routes them—some go to the LLM for reflection, others trigger automatic retries.
  • Context window management: The loop prunes history aggressively. Old file reads are summarized; only the current working set is kept in the LLM context.

3. Tasks Offloaded from the LLM

Here is a granular breakdown of what the agent handles so the LLM doesn't have to:

A. File System & Search

  • Grep / Ripgrep: Searching for symbols, strings, patterns across the codebase.
  • AST Parsing: Finding function definitions, imports, call graphs (tree-sitter, ctags).
  • File I/O: Reading, writing, appending, deleting files.
  • Directory Traversal: Listing structures, filtering by extension.

B. Execution & Validation

  • Shell Command Execution: Running build scripts, package managers, dev servers.
  • Test Runners: Executing pytest, jest, cargo test and capturing exit codes.
  • Linters / Formatters: Running eslint, black, clippy and parsing structured output.
  • Git Operations: git diff, git log, branching, committing, staging.

C. Environment & State

  • Dependency Installation: npm install, pip install, resolving version conflicts.
  • Process Management: Starting/stopping background services, port checking.
  • Environment Variable Handling: Reading .env, injecting secrets.

D. Planning & Memory (Hybrid)

  • Task Decomposition: Breaking "add OAuth" into: 1) find auth module, 2) add middleware, 3) write tests.
  • Checkpointing: Saving working states before risky edits (enables rollback without LLM involvement).
  • Long-term Memory: Storing user preferences (e.g., "I use tabs, not spaces") across sessions.

E. Communication & UI

  • Progress Reporting: Streaming status updates to the user ("Running tests...").
  • Permission Gates: Asking user approval before destructive ops (rm -rf, git push).
  • Diff Rendering: Computing and displaying human-readable diffs.

4. Practical Impact: LLM vs. Agent Work Split

表格
复制
TaskNaive LLM (High Token)Coding Agent (Low Token)
"Find where auth is handled"LLM reads 50 files into contextAgent runs rg "class Auth" → injects 3 lines
"Fix the bug in line 42"LLM regenerates entire fileAgent applies sed patch to 1 line
"Run tests and fix failures"LLM hallucinates test outputAgent runs real tests, feeds only failures
"Refactor across 10 files"LLM outputs 10 full filesAgent emits 10 edit_file calls, reuses cached AST
"Undo that change"LLM regenerates previous stateAgent git checkout or restores checkpoint

5. The "Great Agentic Loop" Thesis

The best agents (like Claude Code or OpenCode) achieve efficiency not by making the LLM smarter, but by making the loop tighter:
  1. Minimize LLM turns: Every tool call that succeeds reduces the need for another LLM inference.
  2. Maximize signal-to-noise: Only exceptions and ambiguities reach the LLM; happy paths execute deterministically.
  3. Stateful, not stateless: The agent maintains a working memory of file states, not just a chat log. This avoids the "re-read the file to confirm" token waste.
Bottom line: The LLM becomes a decision engine for ambiguity and planning, while the agent handles mechanics. In a well-tuned system, the LLM might only be invoked for 10-20% of the steps in a complex task—the rest is deterministic tooling executing against a cached state graph.
If you're building or scaling something similar, the physics are clear: the loop's efficiency is inversely proportional to how often you ask the LLM to do what grep, sed, or git can do deterministically.
how is "pi" different ?
Determine Pi Reference in AI Contexts and Frameworks
The user is asking "how is 'pi' different?" in the context of coding agents and agentic loops. This is likely referring to "Pi" as in the AI assistant from Inflection AI, or possibly "π" in a mathematical/technical context. Given the previous conversation was about coding agents (OpenCode, Claude Code), the user is probably asking about "Pi" (the AI assistant) and how it differs from coding agents.
Wait, let me reconsider. The user might be referring to "PI" as in "Programmer's Intelligence" or some specific framework. Or maybe "π" as in a specific architecture or model. Let me think about what "pi" could refer to in the context of AI/coding agents:
  1. Pi - The AI assistant from Inflection AI (Mustafa Suleyman's company)
  2. π (Pi) - Could be a specific framework or model name
  3. PI - Personal Intelligence, or some other acronym
  4. π - Could refer to the mathematical constant in some algorithmic context
Given the context of coding agents and the previous conversation, the most likely interpretation is that the user is asking about Pi (the AI assistant by Inflection AI) and how it differs from coding agents like Claude Code/OpenCode.
But I should also consider if they mean something else. In the context of "agentic loop engineering" and "reducing tokens," could "pi" refer to:
  • A specific paper or framework?
  • The "π" in some reinforcement learning context (policy π)?
  • A specific coding agent named "Pi"?
Actually, there is a coding agent/framework called Pi or related to π? Let me search to be sure. But I should be careful not to over-search if it's a simple question.
Given the ambiguity, I should probably ask for clarification OR provide the most likely interpretation while acknowledging uncertainty. But the user seems to expect me to know what "pi" refers to.
Let me think about recent developments:
  • Inflection AI's Pi is a conversational AI, not specifically a coding agent
  • There might be a "Pi" coding framework I'm not aware of
  • Could be referring to "π" in the context of the "π0" model or something similar?
Actually, I recall there was some discussion about "Pi" in the context of AI agents. But I'm not entirely sure. Let me search to see if there's a relevant "Pi" in the coding agent space.
搜索网页
Pi coding agent AI different from Claude Code OpenCode Pi AI agent framework vs coding agent Inflection Pi vs coding agents agentic loop
22 个结果
Pi System Self-Modification and Offloaded Linting Testing Permissions
The user is asking "how is 'pi' different?" in the context of the previous conversation about coding agents and agentic loops. Based on the search results, "Pi" refers to Pi Coding Agent (also known as pi-coding-agent), a minimalist open-source coding agent framework by Mario Zechner. It's distinct from Inflection AI's "Pi" (the conversational AI).
The user wants to know how Pi (the coding agent) is different from other coding agents like OpenCode, Claude Code, etc., particularly in the context of:
  1. Reducing tokens
  2. Achieving great agentic loop engineering
  3. Offloading work from the LLM
From the search results, I have rich information about Pi's architecture and philosophy. Let me synthesize this into a clear answer that builds on my previous response about coding agents.
Key differentiators of Pi from the search results:
  1. Radical Minimalism: Only 4 built-in tools (read, write, edit, bash) vs. many tools in other agents
  2. Tiny System Prompt: Under 1,000 tokens vs. 10K+ in OpenCode/Claude Code
  3. Trusts Model's RL Training: Brief system prompt, doesn't over-specify behavior
  4. Tree-Structured Session History: Branching workflows, not linear
  5. Extension-Driven: TypeScript extensions with hot reloading, self-modification
  6. Headless/RPC Mode: Can be embedded as a subprocess in larger systems
  7. Deterministic Agent Core: Deterministic entry/exit points for extension hooks
  8. TUI is ~600 lines: Direct DOM manipulation, no React, 100+ FPS
  9. Performance: Ranked 2nd on TerminalBench with just 4 tools, no context compaction
  10. Cost Tracking: Real-time token consumption, provider-specific pricing
  11. Unix Philosophy: Composes with external tools rather than embedding everything
The user's question is specifically about how Pi is different in terms of:
  • Token reduction
  • Agentic loop engineering
  • Offloading work from LLM
I should structure the answer to address these specific dimensions, comparing Pi to the "typical" coding agent architecture I described in the previous response.
Let me organize:
1. Token Reduction: Pi's Minimalist Approach
  • System prompt <1,000 tokens vs 10K+
  • Only 4 tools in the loop, so tool descriptions are tiny
  • No verbose safety instructions, examples, or role-based prompts
  • Trusts the base model's RL training rather than re-teaching via prompt
  • Result: More context window for actual user code/workload
2. Agentic Loop Engineering: Pi's Philosophy
  • Deterministic hooks (entry/exit points) for extensions
  • Tree-structured sessions (branching) vs linear history
  • No sub-agents, no plan mode, no background processes baked in
  • Hot-reloading extensions
  • Headless RPC mode for embedding in larger systems
  • Self-modification capability (agent can write its own extensions)
3. Work Offloading: What Pi DOESN'T Do (Intentionally)
  • No built-in linter/test runner integration (you shell out)
  • No AST-aware patch verification (unlike OpenCode)
  • No MCP built-in (you add via extensions)
  • No permission popups (you add via extensions like permission-gate.ts)
  • No background bash
  • No context compaction strategy (relies on minimal prompt + tree history)
4. The Trade-off
  • Pi pushes complexity to the user/Unix environment vs absorbing it into the agent
  • It's a "chassis" not a "cockpit"
  • Better for builders, worse for out-of-the-box users
I should also mention that Pi achieved 2nd place on TerminalBench with this minimal architecture, which validates the thesis.
Let me write this clearly and concisely, citing the search results where appropriate.
Pi (the coding agent by Mario Zechner, not the chatbot) is the radical counter-thesis to the "batteries-included" agent design. Where Claude Code, OpenCode, and Codex try to absorb complexity into the harness, Pi deliberately strips it out. Here is how that difference manifests across the dimensions you care about.

1. Token Reduction: Brutal Minimalism

表格
复制
AspectTypical Agent (OpenCode, Claude Code)Pi
System prompt size10K+ tokens (rules, examples, safety instructions, tool schemas)<1,000 tokens
Built-in tools8–20+ tools with verbose JSON schemas4 tools: read, write, edit, bash
Context compactionAuto-compact at 95% usage, summary layersNone — relies on small prompt footprint
Tool descriptionsExtensive (LSP integration, git ops, web search, etc.)Minimal — bash is the escape hatch
Pi’s bet is that frontier models are already RL-trained for coding agent tasks. A verbose system prompt doesn't teach the model anything new; it just burns context window and can conflict with pretrained capabilities. By keeping the prompt under 1,000 tokens, Pi leaves the vast majority of the context window for your actual codebase and task.
Result: Same model, different harness — users report Pi solving problems in one shot where heavier agents fail, simply because the model has more headroom to think.

2. Agentic Loop Engineering: Primitives, Not Opinions

The Loop Design

Most agents engineer a thick loop: planner → executor → observer → context manager → safety layer → sub-agent dispatcher. The harness is a spaceship.
Pi engineers a thin loop: deterministic entry/exit hooks with four primitives. The harness is a chassis.
表格
复制
FeatureTypical AgentPi
Session historyLinear chat logTree-structured — supports branching, forking, exploratory debugging
Sub-agentsBuilt-in orchestrationAbsent — use tmux or external orchestration
Plan modeAuto-generated, managed by harnessUser-managed via markdown files (PLAN.md, TODO.md)
Background processesBuilt-in async shellAbsent — synchronous by default
Extension hooksConfig-driven (JSON/Markdown)TypeScript API with hot reloading — hooks into tool_call, tool_result, model_response
Execution modeInteractive TUI onlyDual: TUI + headless RPC (JSON over stdin/stdout)
The tree-structured session is particularly important for loop efficiency. In a linear agent, a failed experiment pollutes the context forever; in Pi, you branch, try the risky refactor, and prune the dead branch without losing the original path.

Deterministic Hooks

Pi’s agent core has deterministic entry and exit points. Extensions can intercept the loop at precise lifecycle moments without fighting opaque internal state. This is the opposite of black-box harnesses where you can only observe inputs/outputs.

3. What Pi Offloads (and What It Refuses To)

Pi takes the Unix philosophy seriously: do one thing well, compose with the OS for everything else.

What Pi DOES handle (the irreducible core)

  • File I/O: read, write, edit
  • Shell execution: bash (the universal escape hatch)
  • LLM abstraction: 15+ providers, transport normalization, auth
  • Rendering: A ~600-line TUI using direct DOM manipulation (no React re-layout lag)
  • Cost tracking: Real-time token burn dashboards, provider-specific pricing

What Pi does NOT handle (intentional anti-features)

  • Linting / type-checking: You run eslint or tsc via bash, not via a built-in tool
  • Test runners: You invoke pytest yourself; the agent sees only the exit code + stderr
  • Web search: Not built-in; add an extension or use curl
  • Git operations: No built-in git tool; use bash or extensions
  • Permission gates: No popups; add an extension like permission-gate.ts if you want them
  • MCP: Not built-in; load via extensions if needed
  • Context compaction: Not implemented; the minimal prompt is the compaction strategy
This is the polar opposite of OpenCode, which absorbs these into the harness to create a unified cockpit. Pi pushes complexity outward into the surrounding OS, treating tmux, Markdown files, containerization, and natural sync points as sufficient infrastructure.

4. The Self-Modification Escape Valve

Perhaps the most architecturally interesting difference: Pi is designed to self-modify. Because extensions are TypeScript files that hot-reload, you can task the agent with writing its own tools.
  • Need a custom linter integration? Ask Pi to write an extension.
  • Need audit logging? Ask Pi to write an extension that cryptographically signs session histories.
  • Need visualization of the decision tree? Ask Pi to write a TUI component.
This creates a virtuous cycle where the agent enhances its own transparency without you ever forking the core. Most other agents treat the harness as static; Pi treats it as a runtime that evolves.

5. The Verdict: When Does It Win?

Pi ranked 2nd on TerminalBench (trailing only Terminus) using exactly four tools, zero sub-agents, no MCP, no background bash, and no context compaction. That is empirical validation that a minimal loop can match feature-heavy alternatives when the core design is tight.
Pick Pi if:
  • You run local models (especially on Mac/MLX) and need every token to count
  • You want to embed a coding agent as a subprocess in a larger automation system (RPC mode)
  • You prefer to compose with Unix tools rather than learn a harness's opinions
  • You want to inspect, audit, and reshape the agent loop in real time
Skip Pi if:
  • You want everything to work out of the box with zero configuration
  • You need AST-aware patch verification (OpenCode's strength)
  • You are on a Claude Max subscription and don't want to pay API rates on top (Anthropic blocks third-party harnesses from drawing on subscription credits)
In the framework of your original question, Pi is the proof that agentic loop engineering is sometimes about what you remove from the loop, not what you add. The fewer assumptions the harness makes, the more context and control you retain for the LLM to do actual work.
does opencode allows minimum conetxt window to support
Search for OpenCode Minimum Context Window Requirements
The user is asking about OpenCode's minimum context window support. I need to search for specific information about OpenCode's context window requirements, what models it supports, and what the minimum context window is. Let me search for this.
搜索网页
OpenCode minimum context window support OpenCode agent context window requirements OpenCode coding agent minimum tokens context
8 个结果
搜索网页
OpenCode minimum context window models supported OpenCode small context window models 8k 16k 32k OpenCode local models context window limit
7 个结果
OpenCode does not enforce a hard minimum context window. It is provider-agnostic and supports any model you connect, including local ones with small context windows. However, the agent's built-in context engineering layer and toolset are designed around frontier-scale models (typically 128K+ context), and the practical minimum for a functional experience is much higher than the raw model limit.
Here is the breakdown.

1. No Hard Minimum, But a Practical Floor

OpenCode supports 75+ LLM providers through its Models.dev registry, including local models via Ollama, LM Studio, llama.cpp, etc.
You can technically point it at an 8K or 16K model. The harness won't stop you.
But the system prompt + tool schemas + context engineering overhead consumes a significant chunk of that budget before your first user message even lands. Based on the architecture:
表格
复制
ComponentApproximate Token Cost
System prompt (model-specific, derived from Claude Code)~5,000–10,000 tokens
Tool definitions (read, write, edit, bash, git, search, etc.)~2,000–5,000 tokens
MCP tool schemas (if enabled)Variable; up to 40% of context in early designs, now lazy-loaded
Context retrieval / subagent scaffoldingAdditional overhead
Total overhead before user code~8K–15K tokens
This means on a 32K context model, you might have only ~15K–20K tokens left for actual codebase context and conversation history. On an 8K model, the agent would likely fail to initialize or immediately overflow.

2. Context Engineering: Where the Real Minimum Lives

OpenCode's architecture paper reveals aggressive context compaction as a core feature, not an optimization. The system is built on the assumption that sessions will routinely exceed token budgets. Key mechanisms:
  • Tool result summarization: A 3,000-token file read is replaced with "✓ Read file (142 lines, 4,831 chars)" — under 100 tokens.
  • Large output offloading: Outputs >8,000 chars are written to scratch files and referenced by path, replacing the full output with a 500-char preview.
  • Staged compaction: When context hits ~95% usage, an emergency LLM-based summarizer prunes history.
  • Lazy MCP discovery: External tool schemas are not loaded until searched for, reducing baseline overhead from ~40% to <5%.
These features exist because the harness assumes it will be running on large-context models. On a small-context model, the compaction triggers would fire constantly, degrading the agent's ability to maintain coherent multi-turn reasoning.

3. What Users Report for Local/Small Models

Community feedback suggests a soft minimum of ~60K tokens for coding agents to be viable:
"For coding agents 60k is my max. Increasing the context too much will only reduce accuracy and speed. System prompts are around 5k tokens."
OpenCode users running local models (Qwen 3.5, Llama variants) report that the harness itself is the bottleneck, not the model capability:
"Local models are just slow enough that the subscription models are easier to use. For most of my tasks these days, the model's capability is sufficient; it is just not as snappy."
"I use it with Qwen 3.5 running locally when my daily limits run out... The harness is great."

4. The "Small Model" Fallback Trap

OpenCode has a small_model config for lightweight tasks (title generation, summaries). By default, it tries to pick a cheap model from your provider (Haiku, Flash, GPT-5-nano). If your provider doesn't offer one, it falls back to your main model.
This is relevant because if you configure a small local model (e.g., 8K context) as your main model, OpenCode will attempt to use it for everything — including the title generation that would normally go to a smaller model. There is no automatic "this model is too small, refuse to run" guardrail.

5. Bottom Line

表格
复制
Context WindowViability with OpenCode
8K–16KNot viable. System prompt + tools alone likely exceed budget.
32KMarginal. Functional for single-file tasks; multi-file context will trigger constant compaction.
60K–128KPractical minimum for real coding workflows. Matches community-reported thresholds.
128K+Design target. All context engineering features (summarization, offloading, subagents) work as intended.
If you want to run OpenCode on small-context local models, you would need to aggressively prune:
  • Disable MCP servers
  • Disable subagents
  • Strip down the system prompt (requires forking)
  • Use the names-only tool detail level (minimal token mode)
At that point, you are essentially re-implementing Pi's minimalism inside OpenCode's heavier scaffold — which is why Pi exists as the explicit alternative for small-context / local-model use.
ok can we set maxium token in opencode ?
Searching OpenCode Documentation for Max Token Limit Configuration Options
The user is asking whether OpenCode allows setting a maximum token limit. This is a specific configuration question about the OpenCode tool. I should search for the exact configuration options in OpenCode, particularly around token limits, context window management, or max_tokens settings.
Let me search for this information.
搜索网页
OpenCode max_tokens configuration OpenCode set maximum token limit OpenCode config max_tokens context limit
21 个结果
OpenCode custom provider token limits defaults hardcoded 32K missing configs
The user is asking whether OpenCode allows setting a maximum token limit. Based on the search results, I can see several relevant pieces of information:
  1. There is an experimental environment variable OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX for max output tokens.
  2. There is a maxTokens config option per agent (coder, task, title) in the config file.
  3. There is a hardcoded 200,000 token limit per session that users have requested to be configurable.
  4. There are issues with custom providers where max_tokens defaults to 32000.
  5. There is a compaction config with reserved tokens.
  6. There is a feature request for maxInputTokens to limit input tokens per request.
Let me organize this clearly:
What IS configurable:
  • maxTokens per agent in config (coder, task, title) - this controls max output/completion tokens per response
  • OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX environment variable for max output tokens
  • compaction.reserved - token buffer for compaction
  • limit.output and limit.context for custom providers
What is NOT easily configurable (yet):
  • Per-session total token budget (hardcoded at 200,000)
  • Max input tokens per request (feature requested but not implemented)
The 32K default issue: For custom providers, OpenCode hardcodes max_tokens: 32000 if not explicitly configured via limit.output.
Let me provide a clear, structured answer.
Yes. OpenCode lets you set maximum output tokens per response and per agent, but it does not currently let you set a hard cap on total session tokens or input tokens per request. Here is the exact landscape.

1. What You Can Configure Now

Per-Agent maxTokens (Output Limit)

In your ~/.opencode.json or .opencode.json, you can set maxTokens for each agent:
JSON
复制
{
  "$schema": "https://opencode.ai/config.json",
  "agents": {
    "coder": {
      "model": "claude-4-sonnet",
      "maxTokens": 50000,
      "reasoningEffort": "medium"
    },
    "task": {
      "model": "gpt-4.1-mini",
      "maxTokens": 5000
    },
    "title": {
      "model": "gpt-4o-mini",
      "maxTokens": 80
    }
  }
}
This controls the maximum completion tokens the model is allowed to return for that agent. The default for coder and task is 5,000; title is locked to 80.

Custom Provider limit.output

If you use a custom provider (e.g., LM Studio, local gateway), you must explicitly declare limit.output in the model config. If you don't, OpenCode hardcodes max_tokens: 32000 in the API request, which may exceed your model's actual capacity.
JSON
复制
{
  "provider": {
    "myprovider": {
      "models": {
        "my-local-model": {
          "limit": {
            "context": 65536,
            "output": 32768
          }
        }
      }
    }
  }
}

Experimental Environment Variable

For global output token control:
bash
复制
OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX=65536 opencode
This sets the max output tokens for LLM responses across the board.

Compaction Buffer

You can control how much headroom OpenCode keeps before triggering context compaction:
JSON
复制
{
  "compaction": {
    "auto": true,
    "prune": false,
    "reserved": 10000
  }
}
reserved is the token buffer left free to avoid overflow during compaction. It does not limit total usage; it just manages the safety margin.

2. What You Cannot Configure (Yet)

Per-Session Total Token Budget

OpenCode enforces a hardcoded 200,000 token limit per conversation session. When this is reached, the session terminates and context is lost. There is currently no config option, CLI flag, or environment variable to raise this ceiling. Users have explicitly requested this as a feature, but it remains unimplemented.

Max Input Tokens Per Request

There is no maxInputTokens setting. OpenCode sends the full chat history with every request. For long sessions, this means you pay for the entire conversation history on every turn. A feature request exists to add intelligent truncation (e.g., only the last 50K tokens), but it is not yet available.

3. The 32K Trap for Local Models

If you run local models and don't explicitly set limit.output, OpenCode defaults to 32,000 max_tokens. This causes two problems:
  1. Undershooting: If your model only supports 16K output, the API rejects the request.
  2. Overshooting context: On a 128K model, max_tokens: 32000 means once your input hits ~96K tokens, the remaining window is exhausted and the conversation truncates.
Fix: Always declare limit.output (and limit.context) for custom/local providers.

4. Summary Table

表格
复制
Limit TypeConfigurable?How
Max output tokens per response✅ Yesagents.coder.maxTokens or OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX
Custom provider output cap✅ Yeslimit.output in provider model config
Compaction safety buffer✅ Yescompaction.reserved
Per-session total token budget❌ NoHardcoded at 200K; feature requested
Max input tokens per request❌ NoFull history sent every turn; no truncation setting
Default for custom providers⚠️ Implicitmax_tokens: 32000 if limit.output is absent
If you are trying to run OpenCode on small-context local models, the practical move is to set limit.output low (e.g., 4K–8K) and rely on the compaction settings to manage the rest — but you still cannot prevent the session from dying at 200K total tokens.