subagent: implement structured output for in-process backends

The seam vocabulary (SubagentStartRequest.outputSchema, SubagentResult
.structured) existed but no in-process backend honored it — spawn/fork
advertised outputSchema: false. This lands the missing half:

- dsh-tools gains a structured-output JSON Schema subset (json-schema.ts):
  StructuredOutputSchema, assertSupportedOutputSchema (rejects loud outside
  the enforced subset, every violation listed), validateStructuredValue
  (path-qualified issues, total). outputSchema's seam type becomes this raw
  JSON-Schema subset instead of the author-facing SchemaSpec DSL — the schema
  travels verbatim to the model as a forced tool's parameters.
- dsh-subagent-inprocess gains the shared structured runtime: one global
  structured_output capture tool (placeholder parameters) + a prepend:true
  agent/request listener doing FINAL-REQUEST enforcement (strip for plain
  agents, per-run schema for structured children — survives downstream
  request-replacing listeners) + an agent/turn-continuation veto that stops
  a child's turn once captured (no wasted extra model step). Lifetime is
  refcounted by backends (plugin lifetime) AND live runs (start→settle).
- startInProcessRun drives the capture: subset asserted before the child
  exists, instruction appended to the child's system prompt, clean-finish
  nudge loop (structuredNudgeRetries, backend Config, default 1), captured
  value on result.structured; a clean finish without a capture settles
  'error' (never a silent success with a missing field).
- spawn + fork flip outputSchema: true and inject 'tools'.
This commit is contained in:
Tianyi Cui
2026-07-05 11:35:39 +08:00
parent 2bad139ece
commit dafb81be7b
26 changed files with 1402 additions and 65 deletions

View File

@@ -12,12 +12,13 @@ The seam this rides on: `CreateAgentOptions.seed` (added on `dsh-agent`, threade
## Capabilities
`{ outputSchema: false, depthLimit: true, toolFilter: false }` — identical to spawn (the depth/model/output behavior is the shared driver's).
`{ outputSchema: true, depthLimit: true, toolFilter: false }` — identical to spawn (the depth/model/structured-output behavior is the shared driver's).
## Config
| Key | Meaning |
|---|---|
| `providerName` | Registry name on `ctx.subagents` (default `fork`). |
| `structuredNudgeRetries` | How many times a structured run re-prompts a child that finished cleanly without calling `structured_output` (default 1). |
See [`dsh-subagent-spawn`](../subagent-spawn/README.md) for the run lifecycle, model inheritance, and depth tracking — all shared.

View File

@@ -25,19 +25,25 @@ import z from 'schemastery'
import type { SessionEvent } from '@deepseek-ai/dsh-session'
import type { Agent } from '@deepseek-ai/dsh-agent'
import type { SubagentCapabilities, SubagentProvider, SubagentStartRequest } from '@deepseek-ai/dsh-subagent'
import { startInProcessRun } from '@deepseek-ai/dsh-subagent-inprocess'
import { acquireStructuredRuntime, startInProcessRun } from '@deepseek-ai/dsh-subagent-inprocess'
export const name = 'subagent-fork'
export const inject = ['subagents', 'agents']
export const inject = ['subagents', 'agents', 'tools']
/** Config: the registry name to register the provider under. */
/** Config: the registry name to register the provider under, plus structured-run tuning. */
export interface Config {
/** Provider name on `ctx.subagents` (default `fork`). */
providerName: string
/**
* How many times a structured run re-prompts a child that finished cleanly
* without calling `structured_output` before giving up (default 1).
*/
structuredNudgeRetries: number
}
export const Config: z<Config> = z.object({
providerName: z.string().default('fork'),
structuredNudgeRetries: z.natural().default(1),
})
/**
@@ -57,18 +63,24 @@ export function completedTurnPrefix(parent: Agent): SessionEvent[] {
}
/**
* The fork provider. Supports `depthLimit`; NOT `outputSchema`/`toolFilter` this
* cut (the service rejects a request needing either before `start` runs).
* The fork provider. Supports `depthLimit` and `outputSchema` (via the shared
* in-process structured runtime); NOT `toolFilter` this cut (the service
* rejects a request needing it before `start` runs).
*/
class ForkProvider implements SubagentProvider {
readonly capabilities: SubagentCapabilities = { outputSchema: false, depthLimit: true, toolFilter: false }
readonly capabilities: SubagentCapabilities = { outputSchema: true, depthLimit: true, toolFilter: false }
constructor(readonly name: string, private readonly ctx: Context) {}
constructor(
readonly name: string,
private readonly ctx: Context,
private readonly structuredNudgeRetries: number,
) {}
start(request: SubagentStartRequest) {
const seed = completedTurnPrefix(request.parent)
return startInProcessRun(this.ctx, request, {
providerName: this.name,
structuredNudgeRetries: this.structuredNudgeRetries,
// Only pass a seed when there's a completed turn to inherit; an empty seed
// is equivalent to a fresh child, so omit it to keep the session unseeded.
...seed.length > 0 ? { seed } : {},
@@ -77,5 +89,12 @@ class ForkProvider implements SubagentProvider {
}
export function apply(ctx: Context, config: Config): void {
ctx.subagents.registerProvider(new ForkProvider(config.providerName, ctx))
// Hold the structured runtime for the plugin's lifetime (see the spawn
// backend — same two-level lifetime: backends for availability, runs for
// mid-run survival across a backend unload).
ctx.effect(() => {
const acquisition = acquireStructuredRuntime(ctx)
return () => { acquisition.release() }
}, 'subagent-fork structured runtime')
ctx.subagents.registerProvider(new ForkProvider(config.providerName, ctx, config.structuredNudgeRetries))
}

View File

@@ -30,8 +30,8 @@ async function setup(script: Script) {
await ctx.plugin(Invariants)
await ctx.plugin(AgentLoop, { agents: [] })
await ctx.plugin(SubagentService)
await ctx.plugin(Spawn, { providerName: 'spawn' })
await ctx.plugin(fork, { providerName: 'fork' })
await ctx.plugin(Spawn, { providerName: 'spawn', structuredNudgeRetries: 1 })
await ctx.plugin(fork, { providerName: 'fork', structuredNudgeRetries: 1 })
ctx.llm.registerAdapter(['mock'], new MockAdapter(script))
const parent = ctx.agentLoop.create(AgentId('parent'), { model: 'mock' })
return { ctx, parent }

View File

@@ -37,7 +37,7 @@ async function setup(script: Script) {
await ctx.plugin(Invariants)
await ctx.plugin(AgentLoop, { agents: [] })
await ctx.plugin(SubagentService)
await ctx.plugin(fork, { providerName: 'fork' })
await ctx.plugin(fork, { providerName: 'fork', structuredNudgeRetries: 1 })
ctx.llm.registerAdapter(['mock'], new MockAdapter(script))
const parent = ctx.agentLoop.create(AgentId('parent'), { model: 'mock' })
return { ctx, parent }
@@ -161,16 +161,20 @@ describe('dsh-subagent-fork', () => {
await run.dispose()
})
it('advertises depthLimit but not outputSchema/toolFilter', async () => {
it('advertises depthLimit and outputSchema but not toolFilter', async () => {
const { ctx } = await setup([])
expect(ctx.subagents.getProvider('fork')!.capabilities).toEqual({ outputSchema: false, depthLimit: true, toolFilter: false })
expect(ctx.subagents.getProvider('fork')!.capabilities).toEqual({ outputSchema: true, depthLimit: true, toolFilter: false })
})
it('unregisters the provider when its fiber is disposed (HMR safety)', async () => {
const ctx = new Context()
await ctx.plugin(SubagentService)
await ctx.plugin(AgentRegistry)
const fiber = await ctx.plugin(fork, { providerName: 'fork' })
// The backend injects 'tools' for the structured runtime, so the registry
// (and its systemPrompt dependency) must be live for the fiber to activate.
await ctx.plugin(SystemPrompt)
await ctx.plugin(ToolRegistry)
const fiber = await ctx.plugin(fork, { providerName: 'fork', structuredNudgeRetries: 1 })
expect(ctx.subagents.list()).toEqual(['fork'])
await fiber.dispose()
expect(ctx.subagents.list()).toEqual([])
@@ -179,12 +183,12 @@ describe('dsh-subagent-fork', () => {
it('has the namespace-plugin export shape (no stray default)', () => {
expect('default' in fork).toBe(false)
expect(fork.name).toBe('subagent-fork')
expect(fork.inject).toEqual(['subagents', 'agents'])
expect(fork.inject).toEqual(['subagents', 'agents', 'tools'])
const loader = Object.create(Loader.prototype) as Loader
const unwrapped = loader.unwrapExports(fork) as Record<string, unknown>
expect(unwrapped).toBe(fork)
expect(unwrapped.name).toBe('subagent-fork')
expect(unwrapped.inject).toEqual(['subagents', 'agents'])
expect(unwrapped.inject).toEqual(['subagents', 'agents', 'tools'])
expect(typeof unwrapped.apply).toBe('function')
})
})