qwen-code/docs/design/structured-output/structured-output.md
Shaojin Wen ad23c7ab34
docs: user + design docs for --json-schema structured output (#4051)
* docs: add user + design docs for --json-schema structured output

Follows up #3598 (cli/core feature shipped to main, no docs).

**User doc** `docs/users/features/structured-output.md` — covers
quick-start, schema input forms (inline + `@path`), output shapes per
`--output-format`, parse-time restrictions, retry/failure modes,
privacy redaction, permission gating, MCP shadow-tool handling, and a
worked `jq`-piped pipeline example. Registered under the existing
`features/_meta.ts` so it shows up in the docs sidebar between
"Headless Mode" and "Dual Output".

**Design doc** `docs/design/structured-output/structured-output.md` —
why the synthetic-tool-whose-param-schema-is-the-user-schema approach,
the four-stage parse-time validation pipeline,
`schemaRootAcceptsObject`'s decided-vs-deferred boundaries, main-turn
vs drain-turn parity via `processToolCallBatch`, the structured-
success terminal block, the cross-surface privacy redaction sharing
`STRUCTURED_OUTPUT_REDACTED_ARGS`, subagent context handling
(`forSubAgent`), MCP shadow-tool guard, the compatibility surface,
alternatives considered (and why rejected), and a file-by-file index.

Both docs are English-only — repo convention is English-only for
both `docs/users/features/` (zero zh-CN siblings) and `docs/design/`
(only `customize-banner-area/` has a zh-CN twin). Open to adding
zh-CN translations as a separate PR if there's demand.

* docs(structured-output): address PR review feedback

User doc:
- explicit stdout-vs-stderr contract and `{}`-schema behavior.
- 500 ms shutdown-holdback latency note.
- ReDoS warning for user-supplied `pattern` keywords.
- root `$ref` rejection + `allOf` workaround.
- per-retry token cost note.
- sibling-suppression success vs retry paths split out.
- numeric exit codes (1 / 53 / 130) for every failure mode.
- new "Session resumption" section for --continue / --resume.

Design doc:
- gloss the ToolSearch on-demand-loading reference.
- `not` row: drop the array-indexing-lookalike `[…]`.
- 500 ms holdback is best-effort, not guaranteed.
- redaction rationale extends to validation-failure retries.
- `CORE_TOOLS` phrasing: structured_output is excluded FROM the set;
  skill is in a separate dynamically-discovered category.
- subagent suppression maintainer note (single brittle call path).
- `--bare` parenthetical lists the three retained core tools.
- PR #4001 status (closed 2026-05-11, superseded).

* docs(structured-output): correct empty-schema / holdback / SIGINT claims

Three doc claims were stronger than the actual code behaviour:

- **Empty schema produces `{}`, not `null`.** `turn.ts` normalises
  the tool args via `(fnCall.args || {})` before they land in
  `structuredSubmission`, so a zero-arg call against `{}` is emitted
  as `{}` on stdout. The `?? null` in the adapter is defence-in-depth
  for the strictly-undefined case, which the upstream path doesn't
  produce.

- **Holdback is a cap, not a fixed wait.** The loop guard is
  `Date.now() < deadline && registry.hasUnfinalizedTasks()`, so it
  exits immediately when nothing is in flight. Reword as "capped at
  ~500 ms" with an early-exit note.

- **SIGINT can still flush a captured result.** The holdback loop
  does not poll the abort signal, so a SIGINT after the structured
  call is captured but before `adapter.emitResult` finishes may
  still land on stdout. Treat exit code 130 as the source of truth.

Also addresses the new auto-review summary suggestion about per-turn
schema cost: pull the cost callout up out of the bullet list (so it
covers both retry cost and schema-embedded-every-turn cost), since
the schema-embedding cost isn't retry-specific.

* docs(structured-output): correct stdout/stderr + json-mode envelope claims

Two doc claims didn't match `JsonOutputAdapter.emitResult`:

- **Model prose doesn't go to stderr in text mode.** Only error
  messages and log lines do. Successful runs emit just the
  JSON-stringified payload on stdout; accumulated assistant prose
  is discarded entirely (not mirrored to stderr). Point users at
  `--output-format json` / `stream-json` when they need the prose.

- **`--output-format json` emits a JSON array, not a single
  document with top-level fields.** The adapter calls
  `JSON.stringify(this.messages)` where `messages` is an array of
  message objects. `structured_result` lives on the final
  `type: "result"` element of that array, not at the document
  root, so consumers must read `.[-1].structured_result` rather
  than `.structured_result`.

* docs(structured-output): note schema-itself reaches the provider

The Privacy section so far only described `structured_output` *args*
being redacted from local on-device surfaces (telemetry + chat
recording). The schema body is a separate exposure surface — it
ships as the function declaration's `parameters` block on every
model request, so `enum`, `const`, `default`, `examples`,
`description`, `$comment`, etc. travel to the provider in
cleartext. Users defaulting to "redaction covers everything"
could legitimately leak secrets via schema-literal fields.

Add a callout in the user doc, plus a parallel paragraph in the
design doc explaining why the redaction stops at on-device
surfaces (the model needs the schema to satisfy the tool-call
contract, so provider-side redaction isn't possible).

* docs(structured-output): correct stdout-on-failure / ReDoS example / hooks / --bare deny / typo

Five issues from the latest /qreview pass:

- **stdout-vs-stderr is text-mode only.** In `--output-format json`
  and `stream-json`, the failure result message is emitted on
  stdout (final element of the JSON array, or the terminating
  `result` line on the JSONL stream). Wrappers in those modes must
  switch on `is_error`, not on whether stdout is empty.

- **ReDoS example didn't actually demonstrate the threat.** JSON
  Schema `pattern` only fires on string instances, and tool args
  are always objects, so the bare `{"pattern": "(a+)+b"}` schema
  doesn't constrain anything the model can supply. Move the
  pattern inside a string-typed property.

- **Hooks see raw `tool_input`.** `PreToolUse` / `PostToolUse` /
  `PostToolUseFailure` receive the unredacted args — including
  HTTP hooks that can forward off-device. Call this out
  explicitly so users with audit-style catch-all hooks know to
  filter or add hook-side redaction.

- **`--bare` drops settings-level deny.** Bare mode builds
  `mergedDeny` as `[...(bareMode ? [] : settings.permissions.deny), …]`
  — settings-level denies are skipped while the synthetic tool
  stays registered. Argv-level `--exclude-tools` still applies.
  Document this exception in the user doc and the design doc.

- **`maxSessionTurns` hint typo.** The hint points at "schema is
  unsatisfiable" — the original text inverted the polarity.

* feat(core): PR-2.5 — post-promote stream redirect + natural-exit registry settle

Closes the two limitations PR-2 (#3894) deferred for the Phase D part
(b) Ctrl+B promote flow (#3831):

1. **Post-promote stream redirect**: today the `bg_xxx.output` file
   is frozen at promote time because `ShellExecutionService` detaches
   its data listener as part of PR-1's ownership-transfer contract.
   PR-2.5 wires a caller-side `onPostPromoteData` callback so bytes
   from the still-running child append to the file via an
   `fs.createWriteStream` opened in `handlePromotedForeground`.
2. **Natural-exit registry settle**: today the registry entry stays
   `'running'` until `task_stop` / session-end `abortAll` fires its
   abort listener. PR-2.5 wires `onPostPromoteSettle` so natural
   child exit transitions the entry to `'completed'` / `'failed'`
   with the right exitCode / signal / error message.

## Service (`shellExecutionService.ts`)

- New exported types: `ShellExecuteOptions`, `ShellPostPromoteHandlers`,
  `ShellPostPromoteSettleInfo`.
- `execute()` options bag now accepts `postPromote?: { onData, onSettle }`.
  Threaded through to both `executeWithPty` and `childProcessFallback`.
- PTY's `performBackgroundPromote` (line ~1159): after disposing
  the foreground data + exit + error listeners, RE-ATTACH minimal
  forwarders that call `postPromote.onData` / `postPromote.onSettle`
  when the caller opted in. Backwards compat: when `postPromote` is
  unset the PR-2 detach-everything contract is preserved (the
  re-attach is gated on each callback being defined).
- `childProcessFallback`'s `performBackgroundPromote` (line ~706):
  same pattern — re-attach `stdout.on('data', ...)`, `stderr.on('data',
  ...)`, `child.once('exit', ...)`, `child.once('error', ...)` when
  the caller opted in. `error` listener routes through `onSettle`
  with `error` populated, so spawn-side errors after the foreground
  errorHandler detached don't crash the daemon via the default
  unhandled `'error'` event.
- Both paths wrap caller callbacks in try/catch so a thrown handler
  doesn't crash the child's data loop / unhandled-rejection the
  service.

## Shell tool (`shell.ts`)

- New `PromoteArtifacts` type — slots shared between the foreground
  `execute()` postPromote handlers (which fire on the service side
  as soon as promote happens) and the post-resolve
  `handlePromotedForeground` finalizer (which runs after
  `await resultPromise` returns). The two race; the buffer +
  settle-queue absorb that race so neither chunks nor the eventual
  exit info are lost.
- `executeForeground` wires `postPromote` handlers that route data
  to either `promoteArtifacts.stream` (if open) or
  `promoteArtifacts.buffer` (drained when the stream opens), and
  queue settle info if the wired handler isn't yet installed.
- `handlePromotedForeground` opens `fs.createWriteStream(outputPath,
  { flags: 'w' })`, writes the initial snapshot first, drains the
  buffer, then registers the entry and wires `onSettleWired` with
  the full registry decision table:
    - `error` set → `registry.fail(shellId, error.message, endTime)`
    - `exitCode === 0` → `registry.complete(shellId, 0, endTime)`
    - non-zero exitCode → `registry.fail(shellId, "Exited with code N", endTime)`
    - signal !== null → `registry.fail(shellId, "Terminated by signal N", endTime)`
    - all-null fallback → `registry.fail(shellId, "Exited with unknown status", endTime)`
- Fires queued settle synchronously after wiring so a fast command
  that exits between promote and finalizer doesn't get lost.
- Self-audit catch: closes the output stream on the
  `registry.register` throw path so the FD doesn't leak past the
  orphan-child kill.

## Tests

- 3 new in `shellExecutionService.test.ts`:
  - `post-promote bytes route to postPromote.onData when callback provided`
  - `postPromote.onSettle fires on natural child exit after promote`
  - `backwards compat: without postPromote, listeners stay fully detached`
- 3 new in `shell.test.ts` under a `foreground → background promote
  PR-2.5` describe block:
  - `post-promote bytes APPEND to bg_xxx.output via write stream`
  - `natural child exit transitions registry entry to "completed"`
  - `non-zero exit / signal / error → "failed" with descriptive message`
- Bulk-replaced 50 prior `{},` (empty 6th-arg shellExecutionConfig)
  with `expect.objectContaining({}),` + added `expect.objectContaining({
  postPromote: expect.any(Object) }),` as the 7th-arg expectation for
  the foreground execute call.
- Updated the existing `registers a bg_xxx entry on result.promoted`
  test to assert on `fs.createWriteStream` + `stream.write` instead
  of the now-removed `fs.writeFileSync` snapshot path.

182/182 shell.test.ts pass + 73/73 shellExecutionService.test.ts pass
+ 111/111 coreToolScheduler.test.ts pass + 60/60 AppContainer.test.tsx
pass; tsc + ESLint clean.

Self-audit: 3 rounds (positive / reverse / cross-file) found one
issue — output stream FD leak on `registry.register` throw — and
fixed it before flagging complete. All flagged edge cases (stream
errors, child-exits-before-wire-up race, task_stop during natural-
exit window, promote-never-happens cleanup, backwards compat
without callbacks) have explicit handling and / or test pinning.

* fix(core): #4102 review wave — 3 Critical + UTF-8 + tests

3 Critical race/correctness issues + 1 multibyte-corruption suggestion
+ 3 test coverage gaps addressed:

**Critical 1 — child_process late-chunk drop (service)**
Settle was fired on 'exit', but stdout/stderr can emit buffered data
between 'exit' and 'close'. Late chunks landed in
`promoteArtifacts.buffer` after shell.ts had already closed the
stream + transitioned the registry → silently dropped → truncated
`bg_xxx.output`. Switched to listening on 'close' which guarantees
all stdio is fully drained. (code, signal) payload is identical to
'exit', just with proper ordering.

**Critical 2 — stream-flush wait before registry transition (shell)**
`stream.end()` is asynchronous; pending writes can still be in the
libuv queue when it returns. The old code transitioned the registry
immediately after `.end()`, so a /tasks consumer could observe a
`completed` entry and read the output file BEFORE the trailing
bytes were on disk. Fixed: wired settle now `stream.once('finish',
...)` BEFORE calling `registry.complete/fail`. `error` event also
short-circuits to the transition so a late ENOSPC doesn't hang the
settle path forever.

**Critical 3 — stream-open-fail buffer leak (shell)**
If `fs.createWriteStream` threw, the catch path set `stream = null`
but the foreground `onData` handler would still take the
`stream === null` branch and push chunks into `promoteArtifacts.buffer`
— unbounded growth under a sustained child whose output file
couldn't be opened. Added a `streamFailed: boolean` latch on
`PromoteArtifacts`. When set, `onData` drops chunks (with a debug
log) instead of buffering. The catch branch sets the latch.

**Suggestion — shared TextDecoder corrupts multibyte UTF-8 (service)**
child_process post-promote used ONE TextDecoder for both stdout AND
stderr. The decoder's continuation-byte state machine assumes one
byte source; interleaved multibyte chunks corrupted. Now uses
separate decoders + flushes both with `decode()` (no `stream: true`)
on settle so trailing bytes surface as their final characters.

**Suggestion — llmContent reflects already-settled status (shell)**
When the queued-settle drain transitions the registry synchronously
(fast-exit race), the model-facing copy was still saying "Status:
running. … task_stop({...})". Updated to branch on
`postPromoteAlreadySettled` / `postPromoteFinalStatus` — when the
process is already gone, the copy says "Status: completed/failed"
and replaces the `task_stop` suggestion with "Process has already
exited; no `task_stop` needed".

**Suggestion — test coverage gaps**
Added: (a) `queued-settle race: onSettle BEFORE
handlePromotedForeground completes` — custom service impl fires
onSettle synchronously before resolving the promote promise, pins
the drain path. (b) child_process post-promote tests for stdout/stderr
forwarding + 'close'-not-'exit' settle + spawn-error settle.

**Self-audit**: Round 1 + reverse audit. Stream.once mock added to
fire 'finish' synchronously so existing tests don't hang on the new
flush wait. 76/76 shellExecutionService.test.ts (+3) + 183/183
shell.test.ts (+1) pass; tsc + ESLint clean.

* fix(core): #4102 review wave-2 — 3 more from gpt-5.5

C1 (shell.ts:2227): the WriteStream `'error'` event handler only
logged. `fs.createWriteStream` reports common open failures
(ENOENT / EACCES / ENOSPC) asynchronously via that event rather
than throwing. Result: `promoteArtifacts.stream` kept pointing at
the failed stream; `onSettleWired` attached a `.once('finish')`
listener that would never fire → registry stuck on `running`
forever. Latch the failure (null the shared `stream` slot,
set `streamFailed`); `onSettleWired`'s existing `if (!stream)`
branch then transitions the registry immediately.

C2 (shellExecutionService.ts:1468): the promote handoff removes the
foreground `ptyErrorHandler` and only re-attaches data + exit
listeners. A subsequent PTY `error` event had no listener — Node
treats an unhandled `error` from an EventEmitter as a fatal
exception that takes the whole CLI down. Attach a post-promote
forwarder that ignores expected PTY read-exit codes (EIO / EAGAIN,
same filter the foreground handler uses) and routes unexpected
errors through `postPromote.onSettle` with `error` populated.
Single-fire latch shared with `onExit` so settle never fires twice.

C3 (shell.ts:2503): `onSettleWired` waits for the stream's
asynchronous `'finish'` event before flipping
`postPromoteAlreadySettled`, but the model-facing `statusLine` was
built immediately after invoking `onSettleWired` on the queued
settle. A fast-exited promoted command could therefore land
"Status: running" + a `task_stop` instruction in production even
though settle was already observed. Split into two flags:
`postPromoteSettleObserved` (set synchronously when settle is
classified) drives the model copy; the registry transition stays
behind the stream flush.

Tests: +1 PR-2.5 wave-2 PTY error-routing test; +2 shell.ts tests
(stream open async error → registry still transitions; async
`'finish'` after queued-settle drain → llmContent says 'completed'
before registry transition fires).

* fix(core): #4102 review wave-3 — 4 actionable from deepseek-v4-pro

T2 (shell.ts:2456) — Critical buffer-leak race
`onSettleWired` previously set `promoteArtifacts.stream = null`
BEFORE calling `stream.end()`. Any `postPromote.onData` chunk that
landed between that null assignment and the actual flush completing
saw `stream === null && streamFailed === false` and pushed into
`promoteArtifacts.buffer` — a buffer that has no further drain path
(the foreground finalizer has already returned). Result: chunks
stranded indefinitely; PTY mode in particular hits this because
`onExit` can fire while kernel buffers still hold data. Fix drains
the pre-settle buffer to the stream BEFORE nulling AND latches
`streamFailed = true` so any subsequent chunk drops via the
existing `else if (streamFailed)` arm in `onData` instead of
leaking. Updates the `streamFailed` doc to cover both setters
(open-fail and settle-done) so the dual semantic is explicit.

T3 (shell.ts:2262) — silent chunk-drop in catch path
When `fs.createWriteStream` throws synchronously (rare: ENOENT on
a vanished tmpdir), chunks already in `promoteArtifacts.buffer`
were silently lost with no observability — oncall reading a
truncated `bg_xxx.output` had no way to distinguish "stream open
failed" from "child produced nothing." Logs the dropped chunk
count and empties the buffer.

T5 (shell.ts:2443) — opaque all-null fallback
The "Exited with unknown status" fallback fired the registry to
'failed' without any context about which fields were null. This
branch is meant to be unreachable; hitting it indicates the
service emitted a defective settle info object. Includes the
field values in both the fail message and a warn log so the
oncall engineer can tell this path apart from the other "failed"
branches.

T6 (shellExecutionService.ts:1452) — leaked PTY post-promote listeners
`ptyProcess.onData(...)` returns an `IDisposable` that was being
discarded; same for `onExit`. The `'error'` listener function was
also not captured (no way to `removeListener` it). EventEmitter
holds refs to listener closures, which transitively hold refs to
`onPostData` / `onPostSettle` / the caller's `promoteArtifacts`.
While bounded by the PTY's lifetime, the closures keep the
caller's state pinned for the post-settle delay window. Captures
all three handles into `postPromoteDataDisposable` /
`postPromoteExitDisposable` / `postPromoteErrorListener`, then
releases them via a shared `disposePostPromoteListeners()` call
from `firePostSettle` (idempotent — each slot null-checked and
nulled after disposal).

Tests: +1 service test for IDisposable + error-listener cleanup;
+2 shell.ts tests for buffer drain race and catch-path snapshot
fallback. Existing tests stay green (262 → 265 in the touched
suites; 7819 → 7822 across the core package).

* fix(core/test): drop unused 'registry' in wave-3 T2 test (TS6133)

CI build failed across all platforms with src/tools/shell.test.ts(4395,15): error TS6133. The variable was a leftover from copying the queued-settle test pattern; the wave-3 T2 test inspects writeStreamMock.write call history directly and never reads the registry, so the assignment is dead code. Drop it.

* fix(core): #4102 review wave-4 — 6 actionable from gpt-5.5 + deepseek-v4-pro

T1 (Critical, shellExecutionService.ts:860 child_process onSettle
exactly-once)
The PTY path used a `firePostSettle` latch but child_process wired
`close` and `error` independently to `onPostSettle`. A spawn-side
error followed by Node's auto-emitted `'close'` would call the
caller's settle TWICE, racing the registry transition. Added the
same single-fire latch on the child_process path.

T2 (Critical, shell.ts:2264 handoff race reorder)
Original order was `write(snapshot) -> drain buffer -> assign stream`.
Synchronous today (no race in current code), but assign-after-drain
leaves a hazard for any future refactor that adds an `await` inside
the drain loop — a chunk arriving in that window would land in
`promoteArtifacts.buffer`, then post-assign chunks would write to
the stream first, producing out-of-order bytes until the settle
drain. Reordered to `write(snapshot) -> assign stream -> drain
buffer`, which closes the hazard regardless of future async
additions.

T3 (Suggestion, shellExecutionService.ts:816 decoder flush gated
on onSettle)
The trailing-multibyte flush ran inside the `child.once('close', ...)`
handler, which was only installed when `onSettle` was set. An
`onData`-only caller (no onSettle) lost trailing continuation
bytes silently. Hoisted flush into `flushPostPromoteDecoders`
called from `firePostSettle`, and made `firePostSettle` available
on the `'close'` path independent of onSettle (T6 install).

T4 (Suggestion, shell.ts:1700 promoted ANSI passthrough)
The regular `executeBackground` path strips ANSI before writing to
`bg_xxx.output`; the promoted-foreground onData path appended raw
chunks. Reading `bg_xxx.output` after Ctrl+B showed plain text up
to the snapshot then raw `\x1b[31m` / cursor-move / clear-screen
sequences for the post-promote tail — unreadable. Apply
`stripAnsi(rawChunk)` before write/buffer, matching the
executeBackground contract.

T5 (Suggestion, shellExecutionService.ts:786 UTF-8 hardcoded)
The post-promote child_process decoders were hard-coded to
`new TextDecoder('utf-8')`, but the foreground decoder runs
encoding detection via `getCachedEncodingForBuffer`. On a non-UTF-8
child (e.g. GBK on a Chinese Windows shell), the snapshot decoded
correctly but the post-promote tail was mojibake. Capture the
foreground decoder's `.encoding` property and reuse it for
post-promote (with utf-8 fallback if foreground hadn't seen any
bytes yet, and a try/catch around `new TextDecoder` for the rare
unsupported-encoding case).

T6 (Suggestion, shellExecutionService.ts:1540 `error` listener
gated on onSettle)
The post-promote `error` listener was attached only when `onSettle`
was set. An `onData`-only caller still had the foreground
errorHandler detached; a post-promote spawn error would then crash
the CLI via Node's unhandled-error default. Hoisted the close +
error listeners into `if (postPromote)` so any caller opting into
post-promote gets crash protection; if `onSettle` is absent the
listeners log + drop instead of routing.

T7 (Suggestion, shellExecutionService.ts:791 onSettle-only
pipe-block deadlock)
Same root cause as T6: when only `onSettle` is set, the foreground
`stdout`/`stderr` 'data' listeners are detached and no post-promote
listener replaces them. The Readables stay paused, the OS pipe
buffer fills (~64KB on Linux), the child blocks on `stdout.write`,
'close' never fires, onSettle never fires. Added `child.stdout?.resume()`
and `child.stderr?.resume()` in the no-onData branch so the child
can drain its pipes and reach exit.

T8 (Suggestion, shell.ts:2614 dead inspectLine ternary)
`inspectLine`'s ternary returned the same string on both sides —
copy-paste leftover from when the other two adjacent ternaries
(statusLine / stopLine) were correctly varied. Collapsed to a
single string assignment.

Tests: +5 regression tests (4 child_process: T1 double-fire latch,
T3 onData-only flush, T6 onData-only error survives, T7 onSettle-
only resume; +1 shell.ts: T4 ANSI strip).

265 -> 270 in the touched suites; 7822 -> 7827 across the core
package; full suite green.

* fix(core/test): use ShellOutputEvent type in wave-4 onData callbacks (TS2345)

CI lint failed on the wave-4 (T3 / T6) tests with TS2345: pushing
ShellOutputEvent into Array<{type:string;chunk:unknown}> narrows
incompatibly. Switch to ShellOutputEvent[] (matches earlier helpers
at lines 758/966) and discriminate the union via .type === 'data'
when reading .chunk so the narrowed multibyte assertion still
type-checks.

* docs(structured-output): address doudouOUC's four review findings

- Tighten JSON/stream-json paragraph: not all failures emit a result
  to stdout (exit 53 / exit 130 are stderr-only); check exit code first
- Fix suppressed-sibling retry guidance: re-issue in a separate turn
  that does not include structured_output (avoids re-suppression)
- Distinguish settings-deny (exit 53) from --exclude-tools (exit 1)
  in Permission gating section
- Replace <projectDir> placeholder with actual path
  ~/.qwen/projects/<sanitized-cwd>/chats/<sessionId>.jsonl in both docs

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs(structured-output): fix Permission gating — both deny paths strip registration

Forward audit against source code found that the Permission gating
section incorrectly distinguished settings.permissions.deny (claiming
tool stays visible, exit 53) from --exclude-tools (claiming
declaration stripped, exit 1). Both go through the same mergedDeny →
isToolEnabled path and both prevent registration — the model never
sees the tool. Corrected both docs to reflect the actual mechanism:
typical outcome is plain text (exit 1), with maxSessionTurns (exit 53)
as the fallback if the model loops through other tools.

* docs(structured-output): address doudouOUC's May 17 review (5 items)

- Clarify validation is client-side Ajv, not provider-side
- Qualify "same way" with DeclarativeTool abstraction parenthetical
- Match symptom→cause structure for maxSessionTurns hint
- Expand $ref workaround with concrete $defs example
- Clarify Dual Output See Also doesn't require --json-schema

* docs(structured-output): address 2 unresolved design-doc suggestions

1. Privacy/redaction section: note hooks as intentionally non-redacted
   surface (matches user-doc "Hooks see raw args" callout).
2. Dual call-site section: clarify differing post-helper termination
   flow between main-turn (direct return) and drain-turn (sentinel hop).

* docs(structured-output): address doudouOUC's May 17 review (2 nits)

1. Failure-paths table: align "three common causes" cell with the
   symptom→cause framing already used at parse-time validation pipeline
   section ("common stuck-run symptom and its two likely causes").
2. Dual call-site section: fix factual inaccuracy from prior commit —
   `drainOneItem` is `async (): Promise<void>` and returns nothing.
   The two-hop termination is via closure-mutated `structuredSubmission`
   (set by `processToolCallBatch`, checked by `drainLocalQueue` and the
   holdback loop), not a return-value sentinel.

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-17 23:10:34 +08:00

27 KiB

Structured Output (--json-schema) — Design

This document captures the implementation decisions behind the --json-schema headless feature. User-facing usage lives in docs/users/features/structured-output.md.

Goal

In headless runs (qwen -p, piped stdin, or positional prompt), let the caller constrain the model's final answer to a user-supplied JSON Schema and surface the validated payload as machine-readable output that scripts and downstream tooling can consume directly. The model's incidental prose during planning is allowed, but the run must terminate with a payload that conforms to the schema, not with free-form text.

Approach: synthetic tool whose parameter schema IS the user schema

When --json-schema is set, Config.createToolRegistry registers a synthetic structured_output tool (syntheticOutput.ts). Its parametersJsonSchema is exactly the schema the user passed; its execute() returns a stop-message llmContent. The tool-call infrastructure already validates args against parametersJsonSchema client-side (via Ajv in BaseDeclarativeTool.build()), so "the model returned an answer conforming to the schema" reduces to "the model successfully called structured_output."

Three properties fall out of this for free:

  1. No bespoke validator path. Ajv-backed validateToolParams already runs inside BaseDeclarativeTool.build() and rejects non-conforming args before execute() ever fires.
  2. Standard retry behavior. A validation failure surfaces to the model as a tool-call error the same way any other tool's args error does. The model sees the Ajv message and can correct in the next turn.
  3. Provider-agnostic. Gemini, OpenAI, and Anthropic all serialize tool param schemas the same way (via the DeclarativeTool abstraction); the synthetic tool plugs into all three.

The tool is registered with alwaysLoad: true so the ToolSearch on-demand-loading infrastructure (introduced in #3589 — keeps the exposed tool surface small by deferring rarely-used tools behind a search call, only mounting their full schemas when the model asks) never hides it from the model. Without that flag, the model wouldn't know the terminal contract exists.

Parse-time validation pipeline

resolveJsonSchemaArg(raw) in packages/cli/src/config/config.ts runs four checks before the schema reaches Config.createToolRegistry:

  1. Source resolution. Accept either an inline JSON literal or @path/to/file. The @path form stats the resolved path first, refuses non-regular files (FIFOs, character devices, directories), caps size at 4 MiB, and on JSON parse failure emits a generic error (no file-content prefix in stderr).
  2. JSON shape. Parsed result must be a non-array object — primitives, booleans, and arrays are rejected with a clear message.
  3. Root accepts objectsschemaRootAcceptsObject. Function-calling APIs always pass objects as tool args; a root schema like {type: "array"} would register an unusable tool. The walk handles type, const, enum, anyOf, oneOf, allOf, not, if / then / else, and root $ref.
  4. Strict Ajv compileSchemaValidator.compileStrict. A dedicated Ajv instance with strictSchema: true surfaces typos like propertees that the lenient runtime validator would silently swallow.

schemaRootAcceptsObject boundaries

The walk is intentionally best-effort. It catches the unambiguous "this can never accept an object" cases, and defers anything that needs whole-schema satisfiability analysis to Ajv at runtime.

Decided at parse time:

Pattern Outcome
type present, doesn't include "object" reject
type: ["object", "null"] etc. accept
const: non-object value reject
enum: no object members (incl. empty) reject
anyOf/oneOf: empty array reject
anyOf/oneOf: no branch admits object reject
allOf: any branch is false or rejects object reject
Root $ref (with or without sibling type) reject
not: bare {type: "object"} (no narrowing keywords) reject
not: {type: "object", required: […], …} etc. accept (narrowing keywords leave some objects satisfiable; defer)
if: true + then rejects object reject
if: false + else rejects object reject

Deferred to Ajv at runtime:

  • $ref inside anyOf / oneOf / allOf branches (opaque — local $ref resolution would need cycle detection, JSON Pointer escapes, and $defs vs definitions handling; the cost outweighs the benefit for a parse-time best-effort check).
  • if whose value is an object schema (decidable only against a candidate value).
  • Negated anyOf / oneOf / const patterns more complex than not.type.
  • Arbitrary pattern ReDoS exposure (user-supplied; the threat model is narrow because the flag is a CLI argument, not a network input).

The maxSessionTurns exit path appends a --json-schema-specific hint pointing users at the common stuck-run symptom (model never called structured_output) and its two likely causes (tool denied via permissions / schema unsatisfiable) so the runtime fallthrough has user-visible diagnostics.

Runtime: turn dispatch

packages/cli/src/nonInteractiveCli.ts handles the runtime dispatch. The structured-output specifics:

Pre-scan + sibling suppression

When the model emits structured_output alongside other tools in the same assistant turn, the synthetic call is the terminal contract. The pre-scan in processToolCallBatch filters requestsToExecute to only structured_output calls, so side-effecting siblings (write_file, run_shell_command, edit, …) never run.

Example batches (when --json-schema is active):

Model emits Behavior
[write_file(…), structured_output(…)] write_file is skipped. structured_output validates, run ends.
[structured_output(bad-args), structured_output(good)] First fails Ajv validation; second succeeds. Run ends with the second call's args.
[structured_output(bad-args), write_file(…)] structured_output(bad) fails. write_file is also skipped (it was suppressed up front). The model sees both: Ajv's error message for the structured call, and a synthesised "Skipped: …" tool_result for the side-effect call. Next turn, the model may re-issue both or correct the structured call alone.
[other_tool_a, other_tool_b] (no structured_output) Pre-scan is inert. Both tools run normally; the run does NOT terminate.

The synthesised "Skipped:" body has two variants:

  • Success path (a structured call captured the contract this turn): "Skipped: this turn's structured_output contract took precedence as the terminal output." — short, because the session terminates immediately and no consumer (model or SDK) acts on it.
  • Retry path (no structured call captured, the model gets another turn): adds "Re-issue this call in a separate turn if needed." — this is the only model-actionable case.

Main-turn / drain-turn parity

processToolCallBatch(batchRequests, setModelOverride) is defined inside runNonInteractive and called from both:

  • The main-turn loop (top of the function).
  • drainOneItem (cron-prompt / background-task notification reply loop).

The drain turn matters because structured_output is registered for the whole session, so a cron job or a notification reply MIGHT also fire the tool. The helper handles both call sites identically at invocation time; the only call-site-specific binding is which modelOverride variable to write to — passed in as a setter.

The post-helper termination flow differs between the two sites: the main-turn path directly calls return emitStructuredSuccess(), while the drain-turn path requires a two-hop termination (processToolCallBatch captures the result into the closure-scoped structuredSubmission; drainLocalQueue checks it to stop the drain loop, then the holdback loop checks it to break out and call emitStructuredSuccess). Both converge on the same terminal block, but the extra indirection in the drain path is load-bearing — without it the drain loop would continue processing queued items after the structured result was captured.

Structured success terminal block

emitStructuredSuccess() (also defined inside runNonInteractive) is the shared "we got a valid call, shut down" path:

  1. registry.abortAll() aborts in-flight background agents — the structured-output contract is single-shot and shouldn't race task_notifications into the terminal emit.
  2. Bounded holdback (STRUCTURED_SHUTDOWN_HOLDBACK_MS = 500 ms) so the natural cancel handlers of just-aborted agents have a chance to emit their terminal task_notification and land it in localQueue. The loop guard is Date.now() < deadline && registry.hasUnfinalizedTasks(), so the wait exits immediately when nothing is in flight (typical path) and never blocks longer than the cap. The 500 ms ceiling is best-effort — orphaned task_started events remain possible under load if a particular agent's abort handler exceeds the budget. The loop does not poll the abort signal: a SIGINT received during holdback or during the emit path that follows will not short-circuit the result that was already captured. Without the holdback, stream-json consumers would routinely see task_started events without matching task_notification.
  3. flushQueuedNotificationsToSdk(localQueue) drains everything still queued.
  4. finalizeOneShotMonitors() (idempotent — safe to call twice; the drain-turn path already invoked it).
  5. adapter.emitResult({ structuredResult: …, isError: false, … }).

Failure paths

Cause Exit code Surface
Model emits plain text only 1 Error with turn count + truncated Output preview.
Model never calls structured_output for maxSessionTurns turns 53 Reached max session turns + --json-schema hint pointing at the common stuck-run symptom and its two likely causes.
Validation fails repeatedly (eventually 53 via max-turns) Each failure surfaces to the model on the next turn with the Ajv message.
Abort / SIGINT 130 Cancellation path. A structured result is normally not emitted, but emitStructuredSuccess()'s holdback loop does not poll the abort signal — a SIGINT that arrives after capture but before/during the stdout emit may still flush the result. Exit code is the reliable signal.

Output envelope

The adapter pipeline in BaseJsonOutputAdapter.buildResultMessage treats the presence of structuredResult (tracked via 'structuredResult' in options, not !== undefined, so the contract is preserved even when the model called structured_output with no args under an empty schema):

  • result is forced to JSON.stringify(payload) — overriding any free-text summary the adapter accumulated.
  • A top-level structured_result field carries the raw object for consumers that don't want to re-parse the stringified form.
  • undefined payloads normalize to null (rendered as the literal JSON null in both fields) so the field can't silently disappear. In practice this fallback is rarely reached: upstream, turn.ts applies (fnCall.args || {}) before storing the submission, so a zero-arg call against an empty schema lands as {} and renders as {} on stdout, not null. The ?? null step is defence-in-depth for the strictly-undefined case.

TEXT mode writes just the result field + newline to stdout (any incidental assistant prose accumulated during the run is discarded — not mirrored to stderr). JSON mode emits the full event log as a JSON array; structured_result lives on the final type: "result" element of that array, not at the document root. Stream-json mode emits each message on its own line as JSONL; the terminating result line carries structured_result.

Privacy: cross-surface redaction

The args submitted via structured_output ARE the structured payload. On the success path they're already on stdout; on validation-failure retries they may never reach stdout at all. Either way, persisting them on durable on-device surfaces (or exporting them off-device through telemetry) is duplication that leaks the payload into longer-lived storage than the user asked for. The redaction rule is therefore "never persist any args from this synthetic tool, regardless of outcome," not just "dedup what's already on stdout."

Two surfaces have to redact, and both share the same placeholder constant STRUCTURED_OUTPUT_REDACTED_ARGS:

  • ToolCallEvent.function_args (telemetry) — covers OTLP exports, QwenLogger, ui-telemetry, and the chat-recording UI event mirror.
  • redactStructuredOutputArgsForRecording (used by recordAssistantTurn in geminiChat.ts) — covers the on-disk chat-recording JSONL at ~/.qwen/projects/<sanitized-cwd>/chats/<sessionId>.jsonl. Validation-failure retries land here too — each retry's args also get the same placeholder.

The shared constant prevents drift between the two surfaces. Tool-call metrics (duration, success, decision) are preserved.

Hooks (PreToolUse, PostToolUse, PostToolUseFailure) are intentionally not redacted — they receive the raw tool_input because the hook contract is "see what the tool sees." This is documented in the user-doc Privacy section as a "Hooks see raw args" callout so operators can filter on tool_name or add hook-side redaction before running --json-schema against sensitive data.

The redaction is intentionally scoped to on-device persistence surfaces (telemetry exports + chat-recording JSONL). The schema itself still travels to the model provider on every request as the structured_output function declaration's parameters block — no provider-side redaction is possible, since the model needs the schema to satisfy the tool-call contract. The user-doc Privacy section warns users to keep enum / const / default / examples / description payloads free of secrets for the same reason.

Permission gating

structured_output is deliberately excluded from PermissionManager.CORE_TOOLS (the set of tools subject to the --core-tools allowlist check) — alongside the other synthetic tools (agent, exit_plan_mode, ask_user_question, task_stop, send_message). Dynamically discovered tools (skill, MCP) are a separate exclusion category that also bypasses the allowlist for unrelated reasons. The synthetic tool only exists when --json-schema is set; adding it to the allowlist machinery would mean --core-tools read_file --json-schema X silently drops the terminal contract.

Explicit permissions.deny rules and --exclude-tools settings still apply via PermissionManager.evaluateisToolEnabled. Both use the same deny mechanism and both prevent registration — the tool declaration is stripped from the registry, so the model never sees the tool. The typical outcome is that the model answers in plain text (exit 1). If the model loops through other tools without producing text, it eventually hits maxSessionTurns (exit 53) and the --json-schema hint in handleMaxTurnsExceededError tells the user where to look.

--bare interaction. Bare mode short-circuits the settings → CLI config bridge: packages/cli/src/config/config.ts builds mergedDeny as [...(bareMode ? [] : settings.permissions.deny), ...], so settings-level denies (and tools.exclude) are dropped under --bare. Argv-level --exclude-tools is unconditionally appended into mergedDeny, so it still applies. The synthetic tool is registered independently of all this (driven by jsonSchema, not by the deny list), so a settings-only deny of structured_output silently no-ops under --bare while the tool remains callable.

Subagent contexts

Config.createToolRegistry accepts a forSubAgent: true option that suppresses the synthetic registration. Subagent overrides reuse the parent Config via prototype delegation (createApprovalModeOverride / buildSubagentContextOverrideObject.create(base)), and this.jsonSchema propagates through the prototype chain. Without the flag, the synthetic tool would register in the subagent's registry too, and a subagent calling it would receive the "session ends now" llmContent — but only runNonInteractive's main / drain loops detect that as terminal, so the subagent would keep running and burn tokens on a tool whose contract its loop can't honor.

Maintainer note. This suppression hangs on the single call path through createToolRegistry(forSubAgent: true). Any future subagent spawn mechanism that bypasses this path will leak the synthetic tool into the subagent's registry and reintroduce the burn-tokens-forever failure mode. The fail-safe complement would be a runtime guard inside syntheticOutput.execute() that returns a fatalError (or no-op) when invoked from a subagent context. Land one if a second leak path appears.

MCP shadow-tool guard

tool-registry.ts:registerTool checks the lazy factories map for name collisions, not just the eager tools map. If an MCP server discovers a tool literally named structured_output, the auto-qualification path that exists for eager-tool collisions fires for factory collisions too: the MCP tool gets renamed to mcp__<server>__structured_output and the synthetic factory keeps the bare name. Without this guard, an MCP server could silently hijack the structured-output contract.

Compatibility surface

Combination Status Rationale
--json-schema + -p (or stdin, or positional) Supported Primary headless path.
--json-schema + --output-format text (default) Supported JSON.stringify(payload) + newline.
--json-schema + --output-format json / stream-json Supported structured_result field carries the raw object.
--json-schema + --bare Supported --bare restricts the registry to read_file, edit, run_shell_command; the synthetic tool is registered alongside that minimal set.
--json-schema + -i Rejected at parse time TUI has no terminal contract for the synthetic tool.
--json-schema + --input-format stream-json Rejected at parse time Single-shot contract vs. long-lived protocol.
--json-schema + --acp / --experimental-acp Rejected at parse time ACP loop is independent.
--json-schema + --prompt-interactive Rejected at parse time Same as -i.
--json-schema + no prompt + no piped stdin Rejected at parse time Headless requires a prompt.

Alternatives considered

Schema-aware response prompting (no synthetic tool). Asking the model to "respond with JSON matching this schema" via the system prompt and parsing the final assistant message instead. Rejected because the model has no syntactic guarantee — the output might be fenced, prefixed with chatter, or hallucinate fields. Tool-call validation is enforced by the function-calling layer before execute(), which gives us a hard syntactic + semantic guard.

OpenAI's response_format: {type: "json_schema", …}. Provider- specific; would require parallel implementations for Gemini and Anthropic. The synthetic-tool approach is provider-agnostic.

Reorder structured_output to the front of the batch instead of filtering. Lets side-effecting siblings run if the structured call fails validation. Rejected because the contract for --json-schema is "produce structured output" — if the model is in this mode, sibling side-effects are probably a mistake. Suppressing them entirely is safer; the model sees a "Skipped:" tool_result and can re-issue them in a separate turn.

Local $ref resolution inside schemaRootAcceptsObject. Would catch schemas like {anyOf: [{$ref: "#/$defs/String"}], $defs: {…}} at parse time. Rejected for now because the cost (cycle detection, JSON Pointer syntax, $defs vs definitions, partial pointers, remote refs) outweighs the benefit; the maxSessionTurns hint already points users at "schema is unsatisfiable" as a likely cause.

Open work

  • Schema-aware response validation could grow a pattern-based ReDoS guard if real users hit catastrophic-backtracking patterns in --json-schema arguments.
  • SDK protocol additions (Python / TypeScript / Java SDKs exposing a typed structured_result field) — track separately; PR #4001 (closed unmerged on 2026-05-11) covered that scope before the cli/core work landed and was superseded.

File index

  • packages/cli/src/config/config.tsresolveJsonSchemaArg, schemaRootAcceptsObject, yargs .check mutex rules.
  • packages/cli/src/gemini.tsx — TUI guard, exit-code plumbing.
  • packages/cli/src/nonInteractiveCli.tsprocessToolCallBatch, emitStructuredSuccess, suppressedOutputBody, plain-text failure path.
  • packages/cli/src/nonInteractive/io/BaseJsonOutputAdapter.tsstructuredResultresult + structured_result envelope.
  • packages/core/src/config/config.ts — registration with registerStructuredOutputIfRequested, forSubAgent skip.
  • packages/core/src/tools/syntheticOutput.ts — synthetic tool + STRUCTURED_OUTPUT_REDACTED_ARGS placeholder.
  • packages/core/src/tools/tool-registry.ts — factory-collision rename for MCP shadow tools.
  • packages/core/src/telemetry/types.tsfunction_args redaction.
  • packages/core/src/core/geminiChat.tsredactStructuredOutputArgsForRecording.
  • packages/core/src/utils/schemaValidator.tscompileStrict with strict Ajv instance.
  • packages/cli/src/utils/errors.tshandleMaxTurnsExceededError's --json-schema hint.