Merge remote-tracking branch 'origin/master' into codex/pr335-merge-master-20260719

This commit is contained in:
Tianyi Cui
2026-07-19 12:45:35 +08:00
57 changed files with 1379 additions and 811 deletions

View File

@@ -12,6 +12,6 @@ The subagent seam: an agent delegating work to a child agent. Like the [bash](..
| `subagent-acp/` | Out-of-process backend: a child agent in a spawned subprocess, driven over ACP | (registers on `ctx.subagents`) |
| `tool-subagent/` | Model-facing `subagent` delegation tool over `ctx.subagents` | (registers on `ctx.tools`) |
The interface lives at `subagent/subagent/`. The in-process `subagent-spawn` / `subagent-fork` backends share the `subagent-inprocess` driver (a library with no provider of its own — both depend on it, neither on the other), the out-of-process `subagent-acp` backend builds on the `subagent-subprocess` library (the credential env scrub, the dispose ladder, isolated config dirs) and ships alongside them here; the test-only `dsh-subagent-mock` (in [support](../support/README.md)) is separate. All **product** packages except the mock.
The interface lives at `subagent/subagent/`. The in-process `subagent-spawn` / `subagent-fork` backends share the `subagent-inprocess` driver (a library with no provider of its own — both depend on it, neither on the other), and the out-of-process `subagent-acp` backend builds on the `subagent-subprocess` library (the credential env scrub, the dispose ladder, isolated config dirs). Tests replace only the child boundary with package-local fixtures.
The proposal and design rationale: [docs/rfc/implemented/feature/2026-06-21-subagent-capability-seam.md](../../docs/rfc/implemented/feature/2026-06-21-subagent-capability-seam.md).

View File

@@ -37,7 +37,6 @@
"@deepseek-ai/dsh-agent": "workspace:^",
"@deepseek-ai/dsh-llm": "workspace:^",
"@deepseek-ai/dsh-subagent": "workspace:^",
"@deepseek-ai/dsh-subagent-mock": "workspace:^",
"@deepseek-ai/dsh-system-prompt": "workspace:^",
"@deepseek-ai/dsh-tasks": "workspace:^",
"@deepseek-ai/dsh-tool-tasks": "workspace:^",

View File

@@ -0,0 +1,98 @@
import { describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import { type Agent } from '@deepseek-ai/dsh-agent'
import SubagentService, { type SubagentStartRequest } from '@deepseek-ai/dsh-subagent'
import { SessionId } from '@deepseek-ai/dsh-session'
import * as scripted from './scripted-provider.ts'
/** A minimal parent; the scripted provider only reads its id. */
function fakeParent(id = 'parent-1'): Agent {
return { id: SessionId(id) } as unknown as Agent
}
function baseRequest(over: Partial<SubagentStartRequest> = {}): SubagentStartRequest {
return {
prompt: [{ type: 'text', text: 'task' }],
parent: fakeParent(),
signal: new AbortController().signal,
...over,
}
}
async function mount(config: Partial<scripted.Config> = {}): Promise<Context> {
const ctx = new Context()
await ctx.plugin(SubagentService)
await scripted.mountScriptedProvider(ctx, { name: 'mock', ...config })
return ctx
}
describe('scripted subagent provider fixture', () => {
it('registers through the real service and returns the scripted reply', async () => {
const ctx = await mount({ reply: 'hello from fixture' })
expect(ctx.subagents.list()).toEqual(['mock'])
const run = await ctx.subagents.start('mock', baseRequest())
await expect(run.result).resolves.toEqual({
output: [{ type: 'text', text: 'hello from fixture' }],
structured: undefined,
stopReason: 'completed',
})
await run.dispose()
})
it('registers under a configurable name', async () => {
const ctx = await mount({ name: 'spawn' })
expect(ctx.subagents.list()).toEqual(['spawn'])
})
it('returns configured and default structured results', async () => {
const configured = await mount({ reply: 'r', structured: { answer: 42 } })
const schema = { type: 'object' as const, properties: { answer: { type: 'number' as const } } }
const configuredRun = await configured.subagents.start('mock', baseRequest({ outputSchema: schema }))
await expect(configuredRun.result).resolves.toMatchObject({ structured: { answer: 42 } })
const fallback = await mount({ reply: 'fallback reply' })
const fallbackRun = await fallback.subagents.start('mock', baseRequest({ outputSchema: schema }))
await expect(fallbackRun.result).resolves.toMatchObject({ structured: { reply: 'fallback reply' } })
})
it('omits structured output when no schema is requested', async () => {
const ctx = await mount({ capabilities: { outputSchema: false } })
const run = await ctx.subagents.start('mock', baseRequest())
expect(await run.result).not.toHaveProperty('structured')
})
it('honors configured and cancellation stop reasons', async () => {
const refused = await mount({ stopReason: 'refusal' })
const refusedRun = await refused.subagents.start('mock', baseRequest())
await expect(refusedRun.result).resolves.toMatchObject({ stopReason: 'refusal' })
const cancelled = await mount()
const controller = new AbortController()
const cancelledRun = await cancelled.subagents.start('mock', baseRequest({ signal: controller.signal }))
controller.abort()
await expect(cancelledRun.result).resolves.toMatchObject({ stopReason: 'aborted' })
})
it('rejects cancellation before or during asynchronous publication', async () => {
const ctx = await mount()
const alreadyAborted = new AbortController()
alreadyAborted.abort()
await expect(ctx.subagents.start('mock', baseRequest({ signal: alreadyAborted.signal })))
.rejects.toThrow('scripted subagent start aborted before publication')
const handoff = new AbortController()
const pending = ctx.subagents.start('mock', baseRequest({ signal: handoff.signal }))
handoff.abort()
await expect(pending).rejects.toThrow('scripted subagent start aborted before publication')
})
it('unregisters with its owning fixture fiber', async () => {
const ctx = new Context()
await ctx.plugin(SubagentService)
const fiber = await scripted.mountScriptedProvider(ctx, { name: 'mock' })
expect(ctx.subagents.list()).toEqual(['mock'])
await fiber.dispose()
expect(ctx.subagents.list()).toEqual([])
})
})

View File

@@ -0,0 +1,104 @@
/** Package-local scripted child boundary for deterministic tool-subagent tests. */
import type { Context } from 'cordis'
import type { ContentBlock } from '@deepseek-ai/dsh-llm'
import { SessionId } from '@deepseek-ai/dsh-session'
import type {
SubagentCapabilities,
SubagentProvider,
SubagentResult,
SubagentRun,
SubagentStartRequest,
SubagentStopReason,
} from '@deepseek-ai/dsh-subagent'
const DEFAULT_CAPABILITIES: SubagentCapabilities = {
outputSchema: true,
depthLimit: true,
toolFilter: true,
persona: true,
}
/** Options for one scripted provider fixture. */
export interface Config {
/** Registry name to register under. */
name: string
/** Final text returned by the scripted child. */
reply?: string
/** Terminal result reason. */
stopReason?: SubagentStopReason
/** Start-time features advertised by the provider. */
capabilities?: Partial<SubagentCapabilities>
/** Whether tool descriptions say the child inherits completed turns. */
inheritsParentContext?: boolean
/** Structured value returned when the request asks for one. */
structured?: unknown
}
/** Scripted provider whose result aborts if its signal or disposer wins first. */
class ScriptedSubagentProvider implements SubagentProvider {
readonly capabilities: SubagentCapabilities
readonly inheritsParentContext: boolean
constructor(
readonly name: string,
private readonly config: Config,
) {
this.capabilities = { ...DEFAULT_CAPABILITIES, ...config.capabilities }
this.inheritsParentContext = config.inheritsParentContext ?? false
}
async start(request: SubagentStartRequest): Promise<SubagentRun> {
if (request.signal.aborted) throw new Error('scripted subagent start aborted before publication')
const reply = this.config.reply ?? 'scripted subagent reply'
const output: ContentBlock[] = [{ type: 'text', text: reply }]
const wantsStructured = request.outputSchema !== undefined && this.capabilities.outputSchema
const stopReason = this.config.stopReason ?? 'completed'
const state = { cancelled: false }
const onAbort = (): void => { state.cancelled = true }
request.signal.addEventListener('abort', onAbort, { once: true })
await Promise.resolve()
if (state.cancelled) {
request.signal.removeEventListener('abort', onAbort)
throw new Error('scripted subagent start aborted before publication')
}
const resultFor = (): SubagentResult => ({
output,
...wantsStructured ? { structured: this.config.structured ?? { reply } } : {},
stopReason: state.cancelled ? 'aborted' : stopReason,
})
const result = new Promise<SubagentResult>((resolve) => {
setTimeout(() => { resolve(resultFor()) }, 0)
}).finally(() => {
request.signal.removeEventListener('abort', onAbort)
})
return {
id: SessionId(`scripted-subagent:${this.name}:${request.parent.id}`),
localAgent: undefined,
result,
dispose(): Promise<void> {
state.cancelled = true
request.signal.removeEventListener('abort', onAbort)
return Promise.resolve()
},
}
}
}
/**
* Mount one scripted provider through an effect-scoped local plugin.
* @param ctx - context carrying the real subagent registry.
* @param config - scripted provider identity and outcome.
* @returns the fixture plugin's disposable fiber.
*/
export function mountScriptedProvider(ctx: Context, config: Config) {
return ctx.plugin({
name: 'scripted-subagent-provider',
inject: ['subagents'],
apply(pluginCtx: Context): void {
pluginCtx.subagents.registerProvider(new ScriptedSubagentProvider(config.name, config))
},
})
}

View File

@@ -9,18 +9,17 @@ import AgentRegistry from '@deepseek-ai/dsh-agent'
import SubagentService from '@deepseek-ai/dsh-subagent'
import TaskService from '@deepseek-ai/dsh-tasks'
import * as ToolTasks from '@deepseek-ai/dsh-tool-tasks'
import * as mock from '@deepseek-ai/dsh-subagent-mock'
import * as mock from './scripted-provider.ts'
import * as tool from '../src/index.ts'
import { runOutcome, settleRun } from '../src/index.ts'
import { SessionId } from '@deepseek-ai/dsh-session'
/**
* Drives the REAL plugin body: mounts `dsh-tool-subagent` on a real
* `ToolRegistry` + `SubagentService`, with the real `dsh-subagent-mock` as the
* backend, and invokes the registered `subagent` tool through
* `ctx.tools.execute`. The mock is the genuine collaborator (we mock only the
* "child agent", the expensive/non-deterministic boundary) — everything
* downstream of the tool is the shipping code path.
* `ToolRegistry` + `SubagentService`, with a package-local scripted child
* boundary, and invokes the registered `subagent` tool through
* `ctx.tools.execute`. Everything downstream of the child boundary is the
* shipping code path.
*/
/** A minimal parent Agent — the tool reads `agent.id` for `parent`. */
@@ -33,7 +32,7 @@ async function setup(toolConfig: tool.Config, mockConfig: Partial<mock.Config> =
await ctx.plugin(SystemPrompt)
await ctx.plugin(ToolRegistry)
await ctx.plugin(SubagentService)
await ctx.plugin(mock, { name: 'mock', ...mockConfig })
await mock.mountScriptedProvider(ctx, { name: 'mock', ...mockConfig })
await ctx.plugin(tool, toolConfig)
return ctx
}
@@ -131,8 +130,8 @@ describe('dsh-tool-subagent', () => {
await ctx.plugin(SystemPrompt)
await ctx.plugin(ToolRegistry)
await ctx.plugin(SubagentService)
await ctx.plugin(mock, { name: 'spawn', reply: 'from spawn' })
await ctx.plugin(mock, { name: 'acp', reply: 'from acp' })
await mock.mountScriptedProvider(ctx, { name: 'spawn', reply: 'from spawn' })
await mock.mountScriptedProvider(ctx, { name: 'acp', reply: 'from acp' })
await ctx.plugin(tool, { provider: 'spawn', toolName: 'subagent' })
await ctx.plugin(tool, { provider: 'acp', toolName: 'subagent_acp' })
@@ -249,7 +248,7 @@ describe('dsh-tool-subagent', () => {
tool.apply(ctx, { provider: 'mock' })
expect(ctx.tools.schemas().some(s => s.name === 'subagent')).toBe(false)
// Backend arrives (as a delayed sibling fiber would): the tool appears.
await ctx.plugin(mock, { name: 'mock', reply: 'late but fine' })
await mock.mountScriptedProvider(ctx, { name: 'mock', reply: 'late but fine' })
expect(ctx.tools.schemas().some(s => s.name === 'subagent')).toBe(true)
const result = await callSubagent(ctx, { description: 'd', prompt: 'p' })
expect(text(result)).toBe('late but fine')
@@ -260,7 +259,7 @@ describe('dsh-tool-subagent', () => {
await ctx.plugin(SystemPrompt)
await ctx.plugin(ToolRegistry)
await ctx.plugin(SubagentService)
const backend = await ctx.plugin(mock, { name: 'mock' }) // fresh conversation (descriptor: false)
const backend = await mock.mountScriptedProvider(ctx, { name: 'mock' }) // fresh conversation (descriptor: false)
await ctx.plugin(tool, { provider: 'mock' })
expect(ctx.tools.schemas().find(s => s.name === 'subagent')!.description).toContain('does not see this conversation')
@@ -270,7 +269,7 @@ describe('dsh-tool-subagent', () => {
// Backend reloads with a DIFFERENT conversation-history descriptor: the wording is re-derived
// from the fresh provider, not served stale from the first mount.
await ctx.plugin(mock, { name: 'mock', inheritsParentContext: true })
await mock.mountScriptedProvider(ctx, { name: 'mock', inheritsParentContext: true })
expect(ctx.tools.schemas().find(s => s.name === 'subagent')!.description).toContain('inherits this conversation')
})
@@ -281,7 +280,7 @@ describe('dsh-tool-subagent', () => {
await ctx.plugin(SubagentService)
// Arm 1: a mounted tool dies with its plugin fiber; the provider survives.
await ctx.plugin(mock, { name: 'mock' })
await mock.mountScriptedProvider(ctx, { name: 'mock' })
const mounted = await ctx.plugin(tool, { provider: 'mock' })
expect(ctx.tools.schemas().some(s => s.name === 'subagent')).toBe(true)
await mounted.dispose()
@@ -293,7 +292,7 @@ describe('dsh-tool-subagent', () => {
// live plugin owns (the zombie mount).
const waiting = await ctx.plugin(tool, { provider: 'later', toolName: 'subagent_later' })
await waiting.dispose()
await ctx.plugin(mock, { name: 'later' })
await mock.mountScriptedProvider(ctx, { name: 'later' })
expect(ctx.tools.schemas().some(s => s.name === 'subagent_later')).toBe(false)
})
@@ -302,11 +301,11 @@ describe('dsh-tool-subagent', () => {
await ctx.plugin(SystemPrompt)
await ctx.plugin(ToolRegistry)
await ctx.plugin(SubagentService)
await ctx.plugin(mock, { name: 'mock' })
await mock.mountScriptedProvider(ctx, { name: 'mock' })
await ctx.plugin(tool, { provider: 'mock' })
// An unrelated provider registering (added-event with another name) and
// unregistering (removed-event with another name) must not touch the tool.
const other = await ctx.plugin(mock, { name: 'other', inheritsParentContext: true })
const other = await mock.mountScriptedProvider(ctx, { name: 'other', inheritsParentContext: true })
expect(ctx.tools.schemas().filter(s => s.name === 'subagent')).toHaveLength(1)
expect(ctx.tools.schemas().find(s => s.name === 'subagent')!.description).toContain('does not see this conversation')
await other.dispose()