refactor(subagent): unify async readiness and cancellation

This commit is contained in:
Tianyi Cui
2026-07-12 22:41:59 +08:00
parent 02ca71db57
commit bb3f6bd736
49 changed files with 1350 additions and 4147 deletions

View File

@@ -2,7 +2,7 @@
A scripted `SubagentProvider` for testing the [subagent seam](../../subagent/subagent/README.md) without a model or a real child agent — the subagent analog of [`dsh-llm-replay`](../llm-replay/README.md).
It lets a test drive `ctx.subagents` and the model-facing `dsh-tool-subagent` through the **real cordis Loader / export path**, exercising provider registration, start-time capability validation, the run lifecycle (`result` / `cancel` / `dispose`), and the structured-output branch — all deterministically and keylessly.
It lets a test drive `ctx.subagents` and the model-facing `dsh-tool-subagent` through the real Cordis loader/export path, exercising provider registration, async start, start-time capability validation, required-signal cancellation, `result`, `dispose`, and structured output deterministically and keylessly.
## Usage
@@ -13,8 +13,8 @@ Load it as a plugin (functional shape: `name`/`inject`/`Config`/`apply`, no defa
| `name` | `mock` | Registry name to register the provider under. |
| `reply` | `mock subagent reply` | The scripted child's final answer text. |
| `stopReason` | `completed` | The stop reason `result` settles with. |
| `capabilities` | all `true` | Which start-time capabilities (`outputSchema`/`depthLimit`/`toolFilter`) the provider advertises. |
| `capabilities` | all `true` | Which start-time capabilities (`outputSchema`, `depthLimit`, `toolFilter`, and `persona`) the provider advertises. |
| `inheritsParentContext` | `false` | Conversation-history descriptor: `false` means fresh, while `true` exercises seeded/fork wording. It says nothing about tool, service, scope, or authority inheritance. |
| `structured` | `{ reply }` | Structured value surfaced when a request carries an `outputSchema` and the capability is on. |
A `cancel()` issued before `result` settles flips the stop reason to `aborted`, so the cancellation path is observable.
Aborting the required request signal or disposing before `result` settles flips the stop reason to `aborted`, so both holder-facing cancellation paths are observable.

View File

@@ -29,11 +29,10 @@ const STOP_REASONS = ['completed', 'aborted', 'error', 'max-tokens', 'refusal']
const DEFAULT_CAPS: SubagentCapabilities = { outputSchema: true, depthLimit: true, toolFilter: true, persona: true }
/**
* A scripted provider: every {@link start} returns a run whose `result`
* resolves on a microtask with the configured reply (and a structured value
* when the request asked for one and the capability is on). `dispose` is a
* no-op; a `cancel()` before the result settles flips the stop reason to
* `aborted`, so the cancellation path is observable in a test.
* A scripted provider: every {@link start} returns a ready run whose `result`
* resolves on the next task with the configured reply (and a structured value
* when the request asked for one and the capability is on). The required
* signal and `dispose()` both flip an unsettled result to `aborted`.
*/
class MockSubagentProvider implements SubagentProvider {
readonly capabilities: SubagentCapabilities
@@ -47,12 +46,22 @@ class MockSubagentProvider implements SubagentProvider {
this.inheritsParentContext = config.inheritsParentContext ?? false
}
start(request: SubagentStartRequest): SubagentRun {
async start(request: SubagentStartRequest): Promise<SubagentRun> {
if (request.signal.aborted) throw new Error('mock subagent start aborted before publication')
const reply = this.config.reply ?? 'mock subagent reply'
const output: ContentBlock[] = [{ type: 'text', text: reply }]
const wantsStructured = request.outputSchema !== undefined && this.capabilities.outputSchema
const baseStop: SubagentStopReason = this.config.stopReason ?? 'completed'
let cancelled = false
const flags = { cancelled: false }
const onAbort = (): void => { flags.cancelled = true }
request.signal.addEventListener('abort', onAbort, { once: true })
// Make publication genuinely asynchronous so a same-turn abort is still
// a provider-owned startup failure rather than a returned live run.
await Promise.resolve()
if (flags.cancelled) {
request.signal.removeEventListener('abort', onAbort)
throw new Error('mock subagent start aborted before publication')
}
// A deterministic child id derived from the parent — no clock/random (both
// banned in deterministic paths here, and unnecessary for a scripted run).
@@ -60,21 +69,22 @@ class MockSubagentProvider implements SubagentProvider {
const resultFor = (): SubagentResult => ({
output,
structured: wantsStructured ? (this.config.structured ?? { reply }) : undefined,
stopReason: cancelled ? 'aborted' : baseStop,
...wantsStructured ? { structured: this.config.structured ?? { reply } } : {},
stopReason: flags.cancelled ? 'aborted' : baseStop,
})
const result = new Promise<SubagentResult>((resolve) => {
setTimeout(() => { resolve(resultFor()) }, 0)
}).finally(() => {
request.signal.removeEventListener('abort', onAbort)
})
return {
id,
// A scripted run has no asynchronous publication phase; it is ready as
// soon as the provider returns the handle.
started: Promise.resolve(),
result: Promise.resolve().then(resultFor),
cancel() {
cancelled = true
},
async dispose() {
// Scripted run holds no resources — nothing to await.
result,
dispose(): Promise<void> {
flags.cancelled = true
request.signal.removeEventListener('abort', onAbort)
return Promise.resolve()
},
}
}

View File

@@ -11,7 +11,7 @@ function fakeParent(id = 'parent-1'): Agent {
}
function baseRequest(over: Partial<SubagentStartRequest> = {}): SubagentStartRequest {
return { prompt: [{ type: 'text', text: 'task' }], parent: fakeParent(), ...over }
return { prompt: [{ type: 'text', text: 'task' }], parent: fakeParent(), signal: new AbortController().signal, ...over }
}
async function mount(config: Partial<mock.Config> = {}): Promise<Context> {
@@ -26,7 +26,7 @@ describe('dsh-subagent-mock', () => {
const ctx = await mount({ reply: 'hello from mock' })
expect(ctx.subagents.list()).toEqual(['mock'])
const run = ctx.subagents.start('mock', baseRequest())
const run = await ctx.subagents.start('mock', baseRequest())
await expect(run.result).resolves.toEqual({
output: [{ type: 'text', text: 'hello from mock' }],
structured: undefined,
@@ -41,13 +41,13 @@ describe('dsh-subagent-mock', () => {
it('surfaces a structured result when the request carries an outputSchema', async () => {
const ctx = await mount({ reply: 'r', structured: { answer: 42 } })
const run = ctx.subagents.start('mock', baseRequest({ outputSchema: { type: 'object', properties: { answer: { type: 'number' } } } }))
const run = await ctx.subagents.start('mock', baseRequest({ outputSchema: { type: 'object', properties: { answer: { type: 'number' } } } }))
await expect(run.result).resolves.toMatchObject({ structured: { answer: 42 } })
})
it('defaults structured output to { reply } when outputSchema is requested but no structured value is configured', async () => {
const ctx = await mount({ reply: 'fallback reply' })
const run = ctx.subagents.start('mock', baseRequest({ outputSchema: { type: 'object', properties: { answer: { type: 'number' } } } }))
const run = await ctx.subagents.start('mock', baseRequest({ outputSchema: { type: 'object', properties: { answer: { type: 'number' } } } }))
await expect(run.result).resolves.toMatchObject({ structured: { reply: 'fallback reply' } })
})
@@ -56,21 +56,22 @@ describe('dsh-subagent-mock', () => {
// The service rejects an outputSchema request against a no-cap provider, so
// the structured path is only reachable when the cap is on; with it off and
// no schema requested, the result has no structured field.
const run = ctx.subagents.start('mock', baseRequest())
const run = await ctx.subagents.start('mock', baseRequest())
const result = await run.result
expect(result).not.toHaveProperty('structured')
})
it('honors a configured stop reason', async () => {
const ctx = await mount({ stopReason: 'refusal' })
const run = ctx.subagents.start('mock', baseRequest())
const run = await ctx.subagents.start('mock', baseRequest())
await expect(run.result).resolves.toMatchObject({ stopReason: 'refusal' })
})
it('flips the stop reason to aborted when cancelled before the result settles', async () => {
it('flips the stop reason to aborted when the signal fires before the result settles', async () => {
const ctx = await mount()
const run = ctx.subagents.start('mock', baseRequest())
run.cancel()
const controller = new AbortController()
const run = await ctx.subagents.start('mock', baseRequest({ signal: controller.signal }))
controller.abort()
await expect(run.result).resolves.toMatchObject({ stopReason: 'aborted' })
})