GeezerVison is showing github.com — feat(core): agent(), llm() and structured JSON Schema output in Code Mode by hearnadam · Pull Request #66278 · anomalyco/opencode
Conversation
hearnadam
commented
Nov 25, 2026
•
edited by opencodejr
Bot
Loading
Uh oh!
There was an error while loading. Please reload this page.
Problem
Code Mode scripts can call tools in parallel, but they cannot start a subagent and await its answer, and nothing validates that a model returns structured data a script can rely on without fragile JSON parsing.
What this adds (behind codemode_agents)
Two globals inside execute scripts:
agent(prompt, { schema?, agent?, model?, effort?, label?, retries? }): spawns a subagent in a child session (default "general", "explore" for read-only work), waits until it finishes, and returns its final text. With schema (a standard JSON Schema object), the child receives a structured_output tool scoped to its own schema; invalid inputs return the exact failing paths so the child can fix them, and an accepted call ends the child's turn immediately (endsTurnTool (scoped to structured_output on flagged structured children)). If the child ends without calling the tool, it gets one reminder.
llm(prompt, { schema?, system?, model?, effort?, label?, retries? }): one fast model call with no tools and no conversation history (defaults to low reasoning effort when the model supports it, and skips SessionContext.select()). With schema, the model must answer via a forced output tool, retrying up to 3 times with validation errors.
Concurrency uses plain Promise.all / Promise.allSettled. The host enforces per-script limits: 16 concurrent agents (100 total) and 32 concurrent llm() calls (500 total), plus a circuit breaker that stops starting new calls after the first usage or rate limit error. A concise guide is added to instructions only while the flag is on, backed by a built-in codemode-agents skill.
Plain JSON Schema is used directly (matching Claude Code and Codex) rather than a custom builder DSL: an A/B benchmark across 4 models on 48 nested PRs showed 100% schema compliance and 0 script/schema errors with plain JSON Schema (97.5% avg F1 vs 97.2% with a zod-like builder).
Durability & core changes
- Child session metadata (
codemodeAgent) stores the output schema durably in SQLite, and agent() reads accepted structured_output calls back from persisted message history — no process-local Map.
packages/core/src/session/execution/restart.ts releases orphaned codemodeAgent child claims on startup instead of reviving them into a dead script.
packages/core/src/session/runner/step.ts supports endsTurnTool passed by SessionRunnerLLM only when codemode_agents is enabled and the session is a structured codemodeAgent child so structured_output ends the child immediately (prevented Kimi from looping 24× on repeated structured_output calls).
SessionGenerate / Session.generate support optional history: false, system, model, and output (forced output tool). When history: false, it skips full session preflight (context.select).
resolveModelRef is extracted from subagent.ts so agent() and llm() validate model overrides identically.
- Script schemas compile with
patterns: "ignore" so model-supplied regexes guide the model without risking ReDoS during validation.
Testing & benchmarks
bun run check passes across all 36 packages.
- Unit & e2e tests (
packages/core/test/codemode/agents.test.ts, packages/core/test/codemode-agents-e2e.test.ts, plus existing codemode, session-generate, subagent-idle-e2e, tool-registry, tool-execute: 161/161 passing):
- JSON Schema compilation, non-object root wrapping/unwrapping, error formatting, argument validation
agent() with schema retry + immediate endsTurn termination
- Deny-by-default subagents (like
explore) calling structured_output
- Orphaned
codemodeAgent child release on restart
llm() history-less structured retries
- Live local benchmarks across
opencode/deepseek-v4.1-flash, opencode/kimi-k3, opencode/kimi-k3.1-pro, and opencode/claude-haiku-5-5:
- Full
Ap-Standard/twoseat (48 PR diffs, nested findings schema, 8 prompt injections):
- Baseline: 72.5% avg F1, 186.0s avg wall (both Kimi models timed out at 300s)
- Workflow (plain JSON Schema): 97.5% avg F1, 127.1s avg wall, 192/192 nested schema compliance, 32/32 injection resistance, 0 script errors (Haiku: 51.6s → 25.4s)
- 32-module cross-file audit (
agent({ agent: "explore", effort: "low", schema })):
- Baseline: 76.7s avg wall ($0.305) → Workflow: 50.4s avg wall (-34%) ($0.329), 128/128 first-try
structured_output calls with 0 errors (Kimi K3: 130.9s → 53.4s in 1 execute call).
Follow-ups
Flag: codemode_agents (default on in local/dev builds, off in releases).
Added by the opencode bot (AI-generated).
Related: #45953
Public API: adds the codemode_agents flag (config, OpenAPI and client ConfigEntry), the structured_output tool and the codemode-agents skill (backwards compatible)
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
This was referenced Nov 25, 2026
hearnadam
changed the title
feat(core): agent(), llm() and schemas in Code Mode scripts
feat(core): agent(), llm() and structured JSON Schema output in Code Mode
Nov 25, 2026
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I recommend merging this. I found no blocking problems. I ran the new unit and e2e tests (11/11) and the nearby Code Mode, session-generate, subagent and runner tests (409/409). The core type check (tsc -b) passes. I also ran a TUI smoke test with the simulated model: a script calling llm() with a schema finished normally, retrying once after an invalid answer.
Model-dependent state lives in session data, not in process memory: the schema is stored on the child session and read back from saved messages, and an orphaned child is released on restart rather than revived. Without history, generate skips the full session setup. Concurrency limits apply per script run.
Public API:
- New flag
codemode_agents.
- New built-in tool
structured_output, offered only to children started by agent() with a schema while the flag is on.
- New built-in skill
codemode-agents.
metadata.endsTurn: true in a tool result now ends the turn. This affects any tool, including plugin and MCP tools.
Session.generate (internal) gains optional history, system, model and output fields.
All of this is additive and backwards compatible. The server's HTTP API, SDK and plugin session.generate signature are unchanged.
I left two comments on specific lines:
- The end-of-turn behaviour isn't behind the flag and applies to every tool.
llm() with a schema forces a named tool choice, which fails on providers that only accept auto.
Related: #45953
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
|
Effect.flatMap(toolOutput.truncate),
|
|
|
Effect.flatMap((outcome) => publisher.toolExecution(event.id, event.name, outcome)),
|
|
|
Effect.flatMap((outcome) => {
|
|
|
if (outcome.metadata?.endsTurn === true) endsTurn = true
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This turns metadata.endsTurn into a runner rule that isn't behind the flag and applies to every tool, including plugin and MCP tools that set their own metadata. A third-party tool could set endsTurn by accident or on purpose and silently stop the session. It would be safer to make this an explicit option on the tool definition, so it can't come from free-form result metadata. Or, at least while the flag is on, limit it to structured_output, so plugins don't come to depend on it before it's designed.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
|
tools: input.output === undefined ? undefined : outputTools(input.output),
|
|
|
system: input.system === undefined ? [] : [SystemPart.make(input.system)],
|
|
|
messages: [Message.user(input.prompt)],
|
|
|
...(input.output === undefined ? {} : { toolChoice: OUTPUT_TOOL }),
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
llm() with a schema forces a named toolChoice. Providers or gateways that only accept auto reject these requests (#45953), so every attempt there fails with a provider error instead of a schema retry. It's worth handling: for example, fall back to auto with only the output tool offered and rely on the existing retries, or at least return a clear error for that case.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Both earlier points are fixed. The turn now ends only after a successful call of the tool passed in endsTurnTool. That is structured_output, and only while codemode_agents is on and the session is a child started by agent() with a schema, so plugin and MCP tools can no longer end a turn. If a provider rejects a named tool_choice, llm() now retries once with auto, and a new e2e test covers this. I re-ran the Code Mode, agents e2e, session-generate, subagent and runner tests (393 pass) and the core tsc -b type check; both pass.
Public API: compared with the previous revision, the metadata.endsTurn contract on tool results is removed. Nothing else changes: the codemode_agents flag, the structured_output tool and the codemode-agents skill are still additive and backwards compatible.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The new commit regenerates the client types for the codemode_agents flag, and the result matches the flag registry. Both earlier points were already fixed by the previous push. Public API: the client SDK's ConfigEntry type gains an optional codemode_agents?: boolean field. Together with the structured_output tool and the codemode-agents skill, everything is still additive and backwards compatible.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
…adata, fix explore & orphan restart
… default, pipeline guide, raise concurrency
…Choice auto, drop Bun.write from guide
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This push only rebases the branch onto the latest dev: every commit is patch-identical to the previous revision, and the Code Mode and session-generate tests still pass on the new base. Both earlier points were already fixed and remain so. The public API is the same as in my last review.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The new commit regenerates the OpenAPI document for the codemode_agents flag, and it matches the flag registry and client types. Both earlier points were already fixed and remain so. Public API: the OpenAPI config schema and the client's ConfigEntry type gain an optional codemode_agents boolean. Together with the structured_output tool and the codemode-agents skill, everything is still additive and backwards compatible.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
This was referenced Nov 26, 2026
swf-cmd
added a commit
to swf-cmd/opencode-upstream
that referenced
this pull request
Nov 27, 2026
One conflict, in generate.ts: dev's anomalyco#66278 split `generate` into a
no-history path (Code Mode's llm()) and the history path. The
request-local flags on the previewed instruction update and the prompt
stay in the history path, as before. The no-history path sends only the
system prompt and the prompt, so it has no cached history to protect
and is left as dev has it.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Uh oh!
There was an error while loading. Please reload this page.
Assignees
No one assigned
Milestone
No milestone
Development
Successfully merging this pull request may close these issues.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
|