Merge branch 'structured-output-subagent-seam' into worktree-dynamic-workflows

Restack on the carved-out foundation (#192), per review feedback on #170.
The seam files resolve to the carve-out's revision — its prompt-order
neutrality fix (backends no longer inject 'tools'; the structured runtime
gates its own capture-tool registration) restores the subagent tools to
master's front position, so every recorded fixture is re-recorded on the
stacked tree and the authored error-finish/cancel headers re-patched to the
stacked tool list ([subagent, subagent_fork, workflow, todo_write, ...]).
This commit is contained in:
Tianyi Cui
2026-07-06 23:43:13 +08:00
71 changed files with 6160 additions and 5306 deletions

View File

@@ -28,7 +28,11 @@ import type { SubagentCapabilities, SubagentProvider, SubagentStartRequest } fro
import { acquireStructuredRuntime, startInProcessRun } from '@deepseek-ai/dsh-subagent-inprocess'
export const name = 'subagent-fork'
export const inject = ['subagents', 'agents', 'tools']
// `tools` is deliberately NOT injected — same rationale as subagent-spawn: the
// structured runtime gates its capture-tool registration on `tools` itself, so
// this backend's apply timing (and the delegation tool's position in the
// model-visible tool list) is unchanged by structured output.
export const inject = ['subagents', 'agents']
/** Config: the registry name to register the provider under, plus structured-run tuning. */
export interface Config {

View File

@@ -170,8 +170,10 @@ describe('dsh-subagent-fork', () => {
const ctx = new Context()
await ctx.plugin(SubagentService)
await ctx.plugin(AgentRegistry)
// The backend injects 'tools' for the structured runtime, so the registry
// (and its systemPrompt dependency) must be live for the fiber to activate.
// The backend does NOT inject 'tools' (the structured runtime gates its
// capture-tool registration on tools availability itself, keeping backend
// apply timing — and the delegation tool's prompt position — unchanged);
// the registries are loaded here so the runtime registers eagerly anyway.
await ctx.plugin(SystemPrompt)
await ctx.plugin(ToolRegistry)
const fiber = await ctx.plugin(fork, { providerName: 'fork', structuredNudgeRetries: 1 })
@@ -183,12 +185,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', 'tools'])
expect(fork.inject).toEqual(['subagents', 'agents'])
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', 'tools'])
expect(unwrapped.inject).toEqual(['subagents', 'agents'])
expect(typeof unwrapped.apply).toBe('function')
})
})

View File

@@ -142,28 +142,51 @@ function registerRuntime(root: Context, runtime: StructuredRuntime): void {
// The registered parameters are a PLACEHOLDER: the request listener below
// swaps in the run's real schema per child, and strips the tool entirely for
// every agent without a structured run — so this shape is never model-visible.
runtime.disposers.push(root.tools.register({
name: STRUCTURED_OUTPUT_TOOL,
description:
'Report your final structured result. Call this exactly once, when your answer is complete; '
+ 'the arguments must match this tool\'s parameter schema exactly.',
parameters: { type: 'object', properties: {} },
execute(args: unknown, exec: ToolExecution): Promise<ContentBlock[]> {
const state = exec.agent ? runtime.states.get(exec.agent) : undefined
if (!state) {
// Reachable only if a non-structured agent somehow calls the tool (the
// request listener strips it, so the model never sees it) — fail loud
// rather than capture into nowhere.
throw new Error(`${STRUCTURED_OUTPUT_TOOL} is only available to subagents started with an output schema`)
}
const violations = validateStructuredValue(state.schema, args)
// ToolArgsError → isError result with INVALID_ARGS: the model retries
// within the same turn, exactly like a schema-validated defineTool call.
if (violations.length > 0) throw new ToolArgsError(violations)
state.captured = { value: args }
return Promise.resolve([{ type: 'text', text: 'Structured output recorded.' }])
},
}))
//
// Registration does NOT ride on the acquiring backend's plugin-level
// `inject`: a backend that waited on `tools` would apply later than it did
// before this module existed, shifting when its PROVIDER registers — and the
// delegation tool mirrors provider lifecycle, so that shift would reorder
// the model-visible tool list of every existing prompt. Instead the capture
// tool registers synchronously when `tools` is already live (the common
// case), and through a scoped inject fiber when the Loader happens to start
// the backend first. Either way the registration lands on root and is
// disposed by the runtime's refcount; disposing the fiber also covers the
// never-activated case.
let disposeTool: (() => void) | undefined
const registerCapture = (tools: Context['tools']): void => {
disposeTool = tools.register({
name: STRUCTURED_OUTPUT_TOOL,
description:
'Report your final structured result. Call this exactly once, when your answer is complete; '
+ 'the arguments must match this tool\'s parameter schema exactly.',
parameters: { type: 'object', properties: {} },
execute(args: unknown, exec: ToolExecution): Promise<ContentBlock[]> {
const state = exec.agent ? runtime.states.get(exec.agent) : undefined
if (!state) {
// Reachable only if a non-structured agent somehow calls the tool (the
// request listener strips it, so the model never sees it) — fail loud
// rather than capture into nowhere.
throw new Error(`${STRUCTURED_OUTPUT_TOOL} is only available to subagents started with an output schema`)
}
const violations = validateStructuredValue(state.schema, args)
// ToolArgsError → isError result with INVALID_ARGS: the model retries
// within the same turn, exactly like a schema-validated defineTool call.
if (violations.length > 0) throw new ToolArgsError(violations)
state.captured = { value: args }
return Promise.resolve([{ type: 'text', text: 'Structured output recorded.' }])
},
})
}
const liveTools = root.get('tools')
const toolsFiber = liveTools ? undefined : root.inject(['tools'], (childCtx: Context) => {
registerCapture(childCtx.root.tools)
})
if (liveTools) registerCapture(liveTools)
runtime.disposers.push(() => {
disposeTool?.()
void toolsFiber?.dispose()
})
// FINAL-ASSEMBLY enforcement (prepend: true = first registered = OUTERMOST
// wrapper): post-process whatever the downstream listeners and the registry

View File

@@ -420,6 +420,33 @@ describe('in-process structured output', () => {
expect(ctx.tools.get(STRUCTURED_OUTPUT_TOOL)).toBeUndefined()
})
it('registers the capture tool through the scoped fiber when tools loads after the acquisition', async () => {
// The Loader starts sibling plugins concurrently, so a backend can
// acquire the runtime before dsh-tools has applied. The capture tool
// must then register as soon as `tools` exists — via the inject fiber,
// not by deferring the backend (which would reorder the prompt's tools).
const ctx = new Context()
const acquisition = acquireStructuredRuntime(ctx)
await ctx.plugin(SystemPrompt)
await ctx.plugin(ToolRegistry)
// Fiber activation completes asynchronously after the service appears.
await new Promise(resolve => setImmediate(resolve))
expect(ctx.tools.get(STRUCTURED_OUTPUT_TOOL)).toBeDefined()
acquisition.release()
expect(ctx.tools.get(STRUCTURED_OUTPUT_TOOL)).toBeUndefined()
})
it('releasing before tools ever loads disposes the pending fiber without registering', async () => {
const ctx = new Context()
const acquisition = acquireStructuredRuntime(ctx)
acquisition.release()
await ctx.plugin(SystemPrompt)
await ctx.plugin(ToolRegistry)
await new Promise(resolve => setImmediate(resolve))
// The disposed fiber never fires: nothing registers after the fact.
expect(ctx.tools.get(STRUCTURED_OUTPUT_TOOL)).toBeUndefined()
})
it('attach/captured/detach manage per-agent state through the acquisition surface', async () => {
const { ctx, parent } = await setup([])
const acquisition = acquireStructuredRuntime(ctx)

View File

@@ -25,7 +25,12 @@ import type { SubagentCapabilities, SubagentProvider, SubagentStartRequest } fro
import { acquireStructuredRuntime, startInProcessRun } from '@deepseek-ai/dsh-subagent-inprocess'
export const name = 'subagent-spawn'
export const inject = ['subagents', 'agents', 'tools']
// `tools` is deliberately NOT injected: the structured runtime gates its own
// capture-tool registration on `tools` availability internally, so this
// backend's apply timing — and with it the provider-mirroring delegation
// tool's position in the model-visible tool list — stays what it was before
// structured output existed.
export const inject = ['subagents', 'agents']
/** Config: the registry name to register the provider under, plus structured-run tuning. */
export interface Config {

View File

@@ -251,8 +251,10 @@ describe('dsh-subagent-spawn', () => {
const ctx = new Context()
await ctx.plugin(SubagentService)
await ctx.plugin(AgentRegistry)
// The backend injects 'tools' for the structured runtime, so the registry
// (and its systemPrompt dependency) must be live for the fiber to activate.
// The backend does NOT inject 'tools' (the structured runtime gates its
// capture-tool registration on tools availability itself, keeping backend
// apply timing — and the delegation tool's prompt position — unchanged);
// the registries are loaded here so the runtime registers eagerly anyway.
await ctx.plugin(SystemPrompt)
await ctx.plugin(ToolRegistry)
const fiber = await ctx.plugin(spawn, { providerName: 'spawn', structuredNudgeRetries: 1 })
@@ -264,12 +266,12 @@ describe('dsh-subagent-spawn', () => {
it('has the namespace-plugin export shape (no stray default)', () => {
expect('default' in spawn).toBe(false)
expect(spawn.name).toBe('subagent-spawn')
expect(spawn.inject).toEqual(['subagents', 'agents', 'tools'])
expect(spawn.inject).toEqual(['subagents', 'agents'])
const loader = Object.create(Loader.prototype) as Loader
const unwrapped = loader.unwrapExports(spawn) as Record<string, unknown>
expect(unwrapped).toBe(spawn)
expect(unwrapped.name).toBe('subagent-spawn')
expect(unwrapped.inject).toEqual(['subagents', 'agents', 'tools'])
expect(unwrapped.inject).toEqual(['subagents', 'agents'])
expect(typeof unwrapped.apply).toBe('function')
})
})