GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

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

@hearnadam hearnadam commented Nov 25, 2026 •
edited by opencodejr Bot
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor

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

  • feat(codemode): durable Code Mode execution (suspend on shutdown, resume on boot) #66478 — Durable Code Mode execution (suspend on shutdown, resume on boot, durable/idempotent extensions)
  • feat(codemode): reusable saved Code Mode scripts with typed args #66479 — Reusable saved Code Mode scripts with typed args
  • Mirror the new direct structured_output built-in tool on the anomalyco/abattoir model-tools page before removing the flag.

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.

All reactions
@github-actions github-actions Bot added the contributor label Nov 25, 2026
@hearnadam
hearnadam force-pushed the codemode-agents branch from 72e7196 to 6e31f79 Compare November 25, 2026 23:48
This was referenced Nov 25, 2026
feat(codemode): durable Code Mode execution (suspend on shutdown, resume on boot) #66478
Open
feat(codemode): reusable saved Code Mode scripts with typed args #66479
Open
@hearnadam 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
@hearnadam
hearnadam marked this pull request as ready for review November 25, 2026 23:49
opencodejr[bot]
opencodejr Bot reviewed Nov 25, 2026
View reviewed changes

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

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.

All reactions
Comment thread packages/core/src/session/runner/step.ts Outdated
Effect.flatMap(toolOutput.truncate),
Effect.flatMap((outcome) => publisher.toolExecution(event.id, event.name, outcome)),
Effect.flatMap((outcome) => {
if (outcome.metadata?.endsTurn === true) endsTurn = true

@opencodejr opencodejr Bot Nov 25, 2026

Copy link
Copy Markdown
Contributor

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.

All reactions
Comment thread packages/core/src/session/generate.ts
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 }),

@opencodejr opencodejr Bot Nov 25, 2026

Copy link
Copy Markdown
Contributor

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.

All reactions
opencodejr[bot]
opencodejr Bot reviewed Nov 26, 2026
View reviewed changes

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

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.

All reactions
@hearnadam
hearnadam enabled auto-merge (squash) November 26, 2026 00:12
@hearnadam
hearnadam disabled auto-merge November 26, 2026 00:12
@hearnadam
hearnadam enabled auto-merge (squash) November 26, 2026 00:12
opencodejr[bot]
opencodejr Bot reviewed Nov 26, 2026
View reviewed changes

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

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.

All reactions
hearnadam and others added 7 commits November 25, 2026 16:19
@hearnadam
feat(core): agent(), llm() and z for Code Mode scripts
f47608b
@hearnadam
feat(core): zod-style refinements in Code Mode z; ignore unenforceabl…
5120c27
…e patterns
@hearnadam
fix(core): end child turn on structured_output, persist schema in met…
3f0444e
…adata, fix explore & orphan restart
@hearnadam
perf(core): skip context.select on history-less llm(), add effort/low…
f753c20
… default, pipeline guide, raise concurrency
Adam Hearn @hearnadam
refactor(core): accept plain JSON Schema in Code Mode agent()/llm() a…
1a72457
…nd drop builder
@hearnadam
fix(core): scope endsTurn to flagged structured_output, fallback tool…
bf97f6c
…Choice auto, drop Bun.write from guide
@hearnadam
chore(client): regenerate types for codemode_agents flag
f6f1588
@hearnadam
hearnadam force-pushed the codemode-agents branch from 4e5c029 to f6f1588 Compare November 26, 2026 00:20
opencodejr[bot]
opencodejr Bot reviewed Nov 26, 2026
View reviewed changes

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

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.

All reactions
@hearnadam
chore(protocol): regenerate OpenAPI document for codemode_agents flag
13eef99
opencodejr[bot]
opencodejr Bot reviewed Nov 26, 2026
View reviewed changes

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

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.

All reactions
@hearnadam
hearnadam merged commit d09b189 into anomalyco:dev Nov 26, 2026
13 checks passed

Uh oh!

There was an error while loading. Please reload this page.

@hearnadam hearnadam mentioned this pull request Nov 26, 2026
feat(core): reusable saved Code Mode scripts as custom tools #66525
Draft
@simonklee simonklee mentioned this pull request Nov 26, 2026
fix(cli-rs): port selection colours and ACP fixes, and regenerate bindings #66652
Merged
This was referenced Nov 26, 2026
feat(codemode): agent() children should not notify the parent or leave background jobs running #66691
Open
fix(core): keep Code Mode agent() children from notifying the parent or leaving jobs running #66696
Closed
@Edo771977 Edo771977 mentioned this pull request Nov 27, 2026
chore: merge upstream/dev into the fork Edo771977/opencode#102
Merged
swf-cmd added a commit to swf-cmd/opencode-upstream that referenced this pull request Nov 27, 2026
@swf-cmd @claude
Merge dev into request-local-cache
14c4dae
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

@opencodejr opencodejr[bot] opencodejr[bot] left review comments

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

contributor

Projects

None yet

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.

1 participant

@hearnadam
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.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.