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

feat(core): agent(), llm() and structured JSON Schema output in Code Mode #66278

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
hearnadam merged 8 commits into anomalyco:dev from hearnadam:codemode-agents
Nov 26, 2026
+1,502 −90
Merged

feat(core): agent(), llm() and structured JSON Schema output in Code Mode #66278

Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
8 commits
Select commit Hold shift + click to select a range
f47608b
feat(core): agent(), llm() and z for Code Mode scripts
hearnadam Nov 24, 2026
5120c27
feat(core): zod-style refinements in Code Mode z; ignore unenforceabl…
hearnadam Nov 24, 2026
3f0444e
fix(core): end child turn on structured_output, persist schema in met…
hearnadam Nov 25, 2026
f753c20
perf(core): skip context.select on history-less llm(), add effort/low…
hearnadam Nov 25, 2026
1a72457
refactor(core): accept plain JSON Schema in Code Mode agent()/llm() a…
Nov 25, 2026
bf97f6c
fix(core): scope endsTurn to flagged structured_output, fallback tool…
hearnadam Nov 26, 2026
f6f1588
chore(client): regenerate types for codemode_agents flag
hearnadam Nov 26, 2026
13eef99
chore(protocol): regenerate OpenAPI document for codemode_agents flag
hearnadam Nov 26, 2026
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

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

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

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

Diff view
Diff view
Prev Previous commit
Next Next commit
refactor(core): accept plain JSON Schema in Code Mode agent()/llm() a…
…nd drop builder
  • Loading branch information

Uh oh!

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

Adam Hearn @hearnadam
Adam Hearn authored and hearnadam committed Nov 26, 2026
commit 1a72457f93f374b9989dc9f0d988454e44175201

There are no files selected for viewing

128 changes: 9 additions & 119 deletions 128 packages/core/src/codemode/agents.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -122,15 +122,12 @@ export const LIMITS = {
llmTotal: 500,
}

const OPTIONAL = "~optional"

// prettier-ignore
const guide = `## agent(), llm() and z in Code Mode
const guide = `## agent() and llm() in Code Mode

Scripts you run with \`execute\` also have these globals:
- \`await agent(prompt, { schema?, agent?, model?, effort?, label?, retries? })\` starts a subagent (default \`"general"\`, use \`"explore"\` for read-only work) in its own child session, waits for it, and returns its final text — or a checked value when \`schema\` is given.
- \`await agent(prompt, { schema?, agent?, model?, effort?, label?, retries? })\` starts a subagent (default \`"general"\`, use \`"explore"\` for read-only work) in its own child session, waits for it, and returns its final text — or a value checked against \`schema\` (a JSON Schema object).
- \`await llm(prompt, { schema?, system?, model?, effort?, label?, retries? })\` makes one fast model call with no tools and no history (defaults to low reasoning effort). Use it whenever the script already has the text to classify, extract, summarize or verify.
- \`z\` builds JSON Schema like zod: \`z.object({ file: z.string(), line: z.integer().optional(), severity: z.enum(["low", "high"]) })\`. Plain JSON Schema works too.

For speed, put scouting, per-item pipelining (\`Promise.all(items.map(async (item) => { const a = await ...; const b = a.flagged ? await ... : null; return ... }))\`), and writing final files (\`Bun.write\`) in ONE \`execute\` call instead of bouncing intermediate results back to the main session between turns. Read small shared files once in the script and include them in prompts instead of having every worker re-read them. Pass \`effort: "low"\` to \`agent()\` for mechanical stages; omit or pass \`"high"\` for harder reasoning. Up to ${LIMITS.agentConcurrency} agents and ${LIMITS.llmConcurrency} \`llm()\` calls run at once (caps: ${LIMITS.agentTotal} agents, ${LIMITS.llmTotal} \`llm()\`); after any usage/rate limit, no more calls start.

Expand All @@ -139,7 +136,7 @@ Each \`agent()\` is a full subagent run. Start agents only when the user asks fo
const instructionsKey = Instructions.Key.make("core/codemode-agents")
const instructionsCodec = Schema.toCodecJson(Schema.String)

/** The short guide to agent(), llm() and z, sent while the session's Code Mode has them. */
/** The short guide to agent() and llm(), sent while the session's Code Mode has them. */
export const instructions = (enabled: boolean): Instructions.List =>
Instructions.make({
key: instructionsKey,
Expand All @@ -148,14 +145,11 @@ export const instructions = (enabled: boolean): Instructions.List =>
render: {
initial: (text) => text,
changed: (previous, current) => (previous === current ? undefined : current),
removed: () => "agent(), llm() and z are no longer available in Code Mode scripts.",
removed: () => "agent() and llm() are no longer available in Code Mode scripts.",
},
})

/**
* The script's `agent`, `llm` and `z` globals. `z` builds JSON Schema the way zod does, as plain objects whose methods
* (`optional`, `nullable`, `describe`, ...) are host functions; agent() and llm() drop those methods again.
*/
/** The script's `agent` and `llm` globals. Both accept a plain JSON Schema in `options.schema`. */
export const extension = Extension.make({
name: "agents",
globals: {
Expand Down Expand Up @@ -200,23 +194,6 @@ export const extension = Extension.make({
return yield* limited(run, "llm", input.options?.retries ?? 0, call)
}),
),
z: {
string: (options?: unknown) => build({ type: "string", ...keywords(options) }),
number: (options?: unknown) => build({ type: "number", ...keywords(options) }),
integer: (options?: unknown) => build({ type: "integer", ...keywords(options) }),
boolean: () => build({ type: "boolean" }),
null: () => build({ type: "null" }),
unknown: () => build({}),
any: () => build({}),
literal: (value: unknown) => build({ const: value }),
enum: (values: unknown) => build({ enum: Array.isArray(values) ? values : [] }),
array: (items: unknown, options?: unknown) => build({ type: "array", items: clean(items), ...keywords(options) }),
object: (shape: unknown) => object(shape),
union: (members: unknown) => build({ anyOf: Array.isArray(members) ? members.map(clean) : [] }),
optional: (inner: unknown) => build({ ...(isRecord(inner) ? strip(inner) : {}), [OPTIONAL]: true }),
nullable: (inner: unknown) => build({ anyOf: [clean(inner), { type: "null" }] }),
record: (values: unknown) => build({ type: "object", additionalProperties: clean(values) }),
},
},
})

Expand All @@ -235,8 +212,8 @@ export const display = (name: string, args: ReadonlyArray<unknown>) => {
}

/**
* Normalizes a schema from a script: drops `z` methods and markers, wraps a non-object root as `{ value }`, and checks
* that it is JSON Schema we can validate against. Fails with a message for the script otherwise.
* Normalizes a JSON Schema from a script: wraps a non-object root as `{ value }` and checks that it is a JSON Schema
* this runtime can validate against. Fails with a message for the script otherwise.
*/
export function compile(json: JsonSchema.JsonSchema, wrapped: boolean): Result.Result<Output, string> {
// Patterns guide the model but are not enforced: a regex written by one model and run on another's output could
Expand All @@ -252,10 +229,9 @@ export function compile(json: JsonSchema.JsonSchema, wrapped: boolean): Result.R
}

export function output(schema: unknown): Result.Result<Output, string> {
const cleaned = clean(schema)
if (!isRecord(cleaned)) return Result.fail("schema must be an object: a z schema or a JSON Schema.")
if (!isRecord(schema)) return Result.fail("schema must be a JSON Schema object.")
// A script's JSON Schema is a boundary value: the codec below is what checks that it is usable.
const json = cleaned as JsonSchema.JsonSchema
const json = schema as JsonSchema.JsonSchema
const wrapped = json.type !== "object"
const root: JsonSchema.JsonSchema = wrapped
? { type: "object", properties: { value: json }, required: ["value"], additionalProperties: false }
Expand Down Expand Up @@ -389,89 +365,3 @@ const parseOutput = (name: string, schema: unknown) => {
if (Result.isSuccess(result)) return Effect.succeed(result.success)
return Effect.fail(new TypeError(`${name}(): ${result.failure}`))
}

// zod's common refinements, mapped onto the JSON Schema keyword for the node's type.
const build = (json: Record<string, unknown>): Record<string, unknown> => {
const bounds = (kind: "min" | "max", value: unknown) => {
const n = Number(value)
if (json.type === "string") return build({ ...json, [kind === "min" ? "minLength" : "maxLength"]: n })
if (json.type === "array") return build({ ...json, [kind === "min" ? "minItems" : "maxItems"]: n })
return build({ ...json, [kind === "min" ? "minimum" : "maximum"]: n })
}
const format = (name: string) => () => build({ ...json, format: name })
return {
...json,
optional: () => build({ ...json, [OPTIONAL]: true }),
nullable: () => build({ anyOf: [strip(json), { type: "null" }], ...marker(json) }),
nullish: () => build({ anyOf: [strip(json), { type: "null" }], [OPTIONAL]: true }),
describe: (description: unknown) => build({ ...json, description: String(description) }),
default: (value: unknown) => build({ ...json, default: value }),
min: (value: unknown) => bounds("min", value),
max: (value: unknown) => bounds("max", value),
length: (value: unknown) =>
json.type === "array"
? build({ ...json, minItems: Number(value), maxItems: Number(value) })
: build({ ...json, minLength: Number(value), maxLength: Number(value) }),
nonempty: () => bounds("min", 1),
int: () => build({ ...json, type: "integer" }),
positive: () => build({ ...json, exclusiveMinimum: 0 }),
nonnegative: () => build({ ...json, minimum: 0 }),
regex: (pattern: unknown) =>
build({
...json,
pattern: isRecord(pattern) && typeof pattern.source === "string" ? pattern.source : String(pattern),
}),
email: format("email"),
url: format("uri"),
uuid: format("uuid"),
datetime: format("date-time"),
}
}

const object = (shape: unknown) => {
const entries = isRecord(shape) ? Object.entries(shape) : []
return build({
type: "object",
properties: Object.fromEntries(entries.map(([key, value]) => [key, clean(value)])),
required: entries.filter(([, value]) => !(isRecord(value) && value[OPTIONAL] === true)).map(([key]) => key),
additionalProperties: false,
})
}

const strip = (json: Record<string, unknown>) =>
Object.fromEntries(Object.entries(json).filter(([key, value]) => key !== OPTIONAL && typeof value !== "function"))

const marker = (json: Record<string, unknown>) => (json[OPTIONAL] === true ? { [OPTIONAL]: true } : {})

const KEYWORDS = new Set([
"description",
"minimum",
"maximum",
"minLength",
"maxLength",
"minItems",
"maxItems",
"pattern",
"format",
])

// Only the keywords that narrow a value; anything else in options is ignored.
const keywords = (options: unknown) =>
isRecord(options)
? Object.fromEntries(
Object.entries(options).filter(
([key, value]) => KEYWORDS.has(key) && (typeof value === "string" || typeof value === "number"),
),
)
: {}

/** Drops `z` methods and markers at any depth, leaving plain JSON Schema. */
function clean(value: unknown): unknown {
if (Array.isArray(value)) return value.map(clean)
if (!isRecord(value)) return value
return Object.fromEntries(
Object.entries(value)
.filter(([key, item]) => key !== OPTIONAL && typeof item !== "function")
.map(([key, item]) => [key, clean(item)]),
)
}
52 changes: 35 additions & 17 deletions 52 packages/core/src/tool/plugin/codemode-agents.md
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
# Code Mode agents

Inside `execute`, three globals let one script run many model calls:
Inside `execute`, two globals let one script run many model calls:

| Global | What it does | Cost |
| ------------------------- | -------------------------------------------------------------------------------- | ------------------- |
| `agent(prompt, options?)` | Starts a subagent in its own child session, with tools, and waits for its result | A full subagent run |
| `llm(prompt, options?)` | One model call: no tools, no conversation history | One request |
| `z` | Builds schemas the way zod does | Free |

Start agents only when the user asked for parallel agents, multi-agent work or a workflow. For anything else, describe what a script would do and roughly how many agents it would start, and ask. `llm()` is cheap enough to use whenever a script needs a model.

Expand Down Expand Up @@ -34,7 +33,15 @@ Each child is a normal session the user can open. agent() rejects when the child

```js
const label = await llm(`Is this a bug report or a feature request?\n\n${issue.body}`, {
schema: z.object({ kind: z.enum(["bug", "feature"]), confidence: z.number() }),
schema: {
type: "object",
properties: {
kind: { enum: ["bug", "feature"] },
confidence: { type: "number" },
},
required: ["kind", "confidence"],
additionalProperties: false,
},
})
```

Expand All @@ -45,21 +52,32 @@ Options: `schema`, `system`, `model`, `effort`, `label`, `retries`. Defaults to
With `schema`, the model must return a value that matches; agent() and llm() check it and give the model the exact problems to fix until it does, so the script gets a value it can use without parsing.

```js
const Finding = z.object({
file: z.string(),
line: z.integer({ minimum: 1 }).optional(),
severity: z.enum(["low", "medium", "high"]),
summary: z.string().describe("One sentence"),
})
const Findings = z.object({ findings: z.array(Finding) })
const Findings = {
type: "object",
properties: {
findings: {
type: "array",
items: {
type: "object",
properties: {
file: { type: "string" },
line: { type: "integer", minimum: 1 },
severity: { enum: ["low", "medium", "high"] },
summary: { type: "string", description: "One sentence" },
},
required: ["file", "severity", "summary"],
additionalProperties: false,
},
},
},
required: ["findings"],
additionalProperties: false,
}
```

- Types: `z.string()`, `z.number()`, `z.integer()`, `z.boolean()`, `z.null()`, `z.unknown()`, `z.literal(v)`, `z.enum([...])`, `z.array(item)`, `z.object({...})`, `z.union([...])`, `z.record(value)`.
- Methods: `.optional()`, `.nullable()`, `.nullish()`, `.describe(text)`, `.default(value)`, `.min(n)`, `.max(n)`, `.length(n)`, `.nonempty()`, `.int()`, `.positive()`, `.nonnegative()`, `.email()`, `.url()`, `.uuid()`, `.datetime()`, `.regex(re)`. Nothing else from zod exists: no `.refine()`, `.transform()` or `.parse()`.
- `.regex()` and JSON Schema `pattern` are shown to the model but not enforced; check those values in the script if they matter.
- Object keys are required unless `.optional()`; extra keys are not allowed.
- A root that is not an object works: `schema: z.array(Finding)` returns an array.
- Plain JSON Schema works anywhere a `z` schema does.
- Pass standard JSON Schema (Draft 2020-12).
- `pattern` is shown to the model as guidance but is not enforced during validation; check regexes in the script if they matter.
- A root that is not an object works: `{ type: "array", items: { type: "string" } }` returns an array directly.

Describe fields whose meaning is not obvious from the name: the model reads the descriptions.

Expand Down Expand Up @@ -108,7 +126,7 @@ Wait for every result first only when the next step needs all of them, such as d

## Rules of thumb

- Scout first in the main conversation (list files, check the diff) to learn the work list, then fan out over it.
- Put scouting, per-item pipelining, and writing final files (`Bun.write`) in one `execute` call instead of bouncing intermediate results back to the main session between turns.
- Keep each agent's task small and specific, with a clear result. One agent per file or per finding beats one agent for everything.
- Agents that edit files at the same time can overwrite each other. Give them separate files, or have them return changes and apply them yourself.
- Return the summary the user needs from the script, not every raw result: the script's return value is what you read next.
Expand Down
2 changes: 1 addition & 1 deletion 2 packages/core/src/tool/plugin/codemode-agents.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const DEFAULT_AGENT = "general"
const LLM_ATTEMPTS = 3

export const SkillDescription =
"Read before writing a Code Mode script that calls agent() or llm(): the full API, schemas with z, limits, and patterns for fanning work out, verifying it and combining the results."
"Read before writing a Code Mode script that calls agent() or llm(): the full API, schemas, limits, and patterns for fanning work out, verifying it and combining the results."

export const Plugin = {
id: "opencode.tool.codemode-agents",
Expand Down
6 changes: 3 additions & 3 deletions 6 packages/core/test/codemode-agents-e2e.test.ts
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ describe("agent()", () => {
Effect.gen(function* () {
const h = yield* harness()
const result = yield* h.run(
`return await agent("Find bugs in src", { agent: "reviewer", label: "bug hunt", schema: z.object({ bugs: z.array(z.string()) }) })`,
`return await agent("Find bugs in src", { agent: "reviewer", label: "bug hunt", schema: { type: "object", properties: { bugs: { type: "array", items: { type: "string" } } }, required: ["bugs"], additionalProperties: false } })`,
{
reviewer: [
TestLLM.toolCall("call-bad", "structured_output", { bugs: "off by one" }),
Expand Down Expand Up @@ -234,7 +234,7 @@ describe("agent()", () => {
Effect.gen(function* () {
const h = yield* harness()
const result = yield* h.run(
`return await agent("Check auth", { agent: "readonly", schema: z.object({ ok: z.boolean() }) })`,
`return await agent("Check auth", { agent: "readonly", schema: { type: "object", properties: { ok: { type: "boolean" } }, required: ["ok"], additionalProperties: false } })`,
{
readonly: [
TestLLM.toolCall("call-ok", "structured_output", { ok: true }),
Expand Down Expand Up @@ -287,7 +287,7 @@ describe("llm()", () => {
Effect.gen(function* () {
const h = yield* harness()
const result = yield* h.run(
`return await llm("Classify: the app crashes on save", { schema: z.object({ kind: z.enum(["bug", "feature"]) }) })`,
`return await llm("Classify: the app crashes on save", { schema: { type: "object", properties: { kind: { enum: ["bug", "feature"] } }, required: ["kind"], additionalProperties: false } })`,
{
build: [
TestLLM.toolCall("call-1", "respond", { kind: "crash" }),
Expand Down
Loading
Oops, something went wrong.

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.
You are visitor 01402792 — 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.