Add subagent capability seam: interface, mock backend, model-facing tool

Introduce the `packages/subagent/` group and the abstract subagent seam — an
agent delegating to a child agent — as a named-provider registry (`ctx.subagents`),
unlike the single-implementation bash seam, so multiple transports (in-process,
ACP, future A2A) coexist. This first PR lands the interface, a scripted test
backend, and the model-facing tool, validated through the real cordis load path.

- dsh-subagent: SubagentService registry + SubagentProvider/SubagentRun
  vocabulary + subagent/start|end events. Start-time capabilities (outputSchema,
  depthLimit, toolFilter) are checked pre-start and rejected loud; runtime
  capabilities (sendMessage, resume) are optional methods on SubagentRun.
- dsh-subagent-mock (support): scripted provider for keyless, deterministic
  tests through the real Loader/export path.
- dsh-tool-subagent: the model-facing `subagent` tool, config-bound to one
  provider; synchronous collect with try/finally dispose, signal->cancel
  bridging, and non-completed-stop-reason -> isError mapping.
- Proposed RFC documenting the seam, the fork-vs-spawn-as-separate-backends
  decision, own-session isolation, synchronous-collect scope, and the deferral
  of background/poll/spill to a future unification with bash.
- Wire the new group into tsconfigs, build refs, package hierarchy docs, the
  module graph, and the cordis catalog.

RFC: docs/rfc/proposed/feature/2026-06-21-subagent-capability-seam.md
This commit is contained in:
Tianyi Cui
2026-06-21 22:31:56 +08:00
parent 6b4dc48fbd
commit 1a81f2cccd
26 changed files with 1605 additions and 3 deletions

View File

@@ -0,0 +1,19 @@
# @deepseek-ai/dsh-subagent-mock
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.
## Usage
Load it as a plugin (functional shape: `name`/`inject`/`Config`/`apply`, no default). Config (all optional):
| Key | Default | Meaning |
|---|---|---|
| `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. |
| `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.

View File

@@ -0,0 +1,38 @@
{
"name": "@deepseek-ai/dsh-subagent-mock",
"description": "Scripted subagent provider for testing the subagent seam (keyless, deterministic)",
"version": "0.0.1",
"private": true,
"type": "module",
"main": "lib/index.js",
"types": "lib/index.d.ts",
"exports": {
".": {
"types": "./lib/index.d.ts",
"default": "./lib/index.js"
},
"./src/*": "./src/*",
"./package.json": "./package.json"
},
"files": [
"lib",
"src"
],
"license": "BSD-3-Clause",
"peerDependencies": {
"@deepseek-ai/dsh-agent": "^0.0.1",
"@deepseek-ai/dsh-llm": "^0.0.1",
"@deepseek-ai/dsh-subagent": "^0.0.1",
"cordis": "^4.0.0-rc.6"
},
"dependencies": {
"schemastery": "^3.18.0"
},
"devDependencies": {
"@deepseek-ai/dsh-agent": "workspace:^",
"@deepseek-ai/dsh-llm": "workspace:^",
"@deepseek-ai/dsh-subagent": "workspace:^",
"@cordisjs/plugin-loader": "^1.0.0-rc.4",
"cordis": "^4.0.0-rc.6"
}
}

View File

@@ -0,0 +1,112 @@
/**
* A scripted {@link SubagentProvider} for testing the subagent seam WITHOUT a
* model or a real child agent. Mirrors `@deepseek-ai/dsh-llm-replay`: it lets a
* test drive the service and the model-facing tool through the REAL cordis
* Loader / export path, exercising registration, capability validation, the
* run lifecycle, and the structured-output branch deterministically.
*
* Plugin export shape: named `name`/`inject`/`Config`/`apply`, NO default —
* a functional plugin (it only registers a provider; it is never injected).
*
* @module @deepseek-ai/dsh-subagent-mock
*/
import type { Context } from 'cordis'
import z from 'schemastery'
import { AgentId } from '@deepseek-ai/dsh-agent'
import type { ContentBlock } from '@deepseek-ai/dsh-llm'
import type {
SubagentCapabilities,
SubagentProvider,
SubagentResult,
SubagentRun,
SubagentStartRequest,
SubagentStopReason,
} from '@deepseek-ai/dsh-subagent'
const STOP_REASONS = ['completed', 'aborted', 'error', 'max-tokens', 'refusal'] as const
const DEFAULT_CAPS: SubagentCapabilities = { outputSchema: true, depthLimit: true, toolFilter: 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.
*/
class MockSubagentProvider implements SubagentProvider {
readonly capabilities: SubagentCapabilities
constructor(
readonly name: string,
private readonly config: Config,
) {
this.capabilities = { ...DEFAULT_CAPS, ...config.capabilities }
}
start(request: SubagentStartRequest): SubagentRun {
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
// A deterministic child id derived from the parent — no clock/random (both
// banned in deterministic paths here, and unnecessary for a scripted run).
const id = AgentId(`mock-subagent:${this.name}:${request.parent.id}`)
const resultFor = (): SubagentResult => ({
output,
structured: wantsStructured ? (this.config.structured ?? { reply }) : undefined,
stopReason: cancelled ? 'aborted' : baseStop,
})
return {
id,
result: Promise.resolve().then(resultFor),
cancel() {
cancelled = true
},
async dispose() {
// Scripted run holds no resources — nothing to await.
},
}
}
}
export const name = 'subagent-mock'
export const inject = ['subagents']
/** Config for the mock provider; all optional with test-friendly defaults. */
export interface Config {
/** Registry name to register under. */
name: string
/** The text the scripted child "returns" as its final answer. */
reply?: string
/** The stop reason the run settles with. */
stopReason?: SubagentStopReason
/** Which start-time capabilities to advertise (default: all `true`). */
capabilities?: Partial<SubagentCapabilities>
/**
* Structured value surfaced when a request carries an `outputSchema` and the
* `outputSchema` capability is on (default: `{ reply }`).
*/
structured?: unknown
}
export const Config: z<Config> = z.object({
name: z.string().default('mock'),
reply: z.string(),
stopReason: z.union(STOP_REASONS),
capabilities: z.object({
outputSchema: z.boolean(),
depthLimit: z.boolean(),
toolFilter: z.boolean(),
}),
structured: z.any(),
})
export function apply(ctx: Context, config: Config): void {
ctx.subagents.registerProvider(new MockSubagentProvider(config.name, config))
}

View File

@@ -0,0 +1,95 @@
import { describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import Loader from '@cordisjs/plugin-loader'
import { AgentId, type Agent } from '@deepseek-ai/dsh-agent'
import SubagentService, { type SubagentStartRequest } from '@deepseek-ai/dsh-subagent'
import * as mock from '../src/index.ts'
/** A minimal parent — the mock provider only reads `parent.id`. */
function fakeParent(id = 'parent-1'): Agent {
return { id: AgentId(id) } as unknown as Agent
}
function baseRequest(over: Partial<SubagentStartRequest> = {}): SubagentStartRequest {
return { prompt: [{ type: 'text', text: 'task' }], parent: fakeParent(), ...over }
}
async function mount(config: Partial<mock.Config> = {}): Promise<Context> {
const ctx = new Context()
await ctx.plugin(SubagentService)
await ctx.plugin(mock, { name: 'mock', ...config })
return ctx
}
describe('dsh-subagent-mock', () => {
it('registers a provider on ctx.subagents and returns the scripted reply', async () => {
const ctx = await mount({ reply: 'hello from mock' })
expect(ctx.subagents.list()).toEqual(['mock'])
const run = ctx.subagents.start('mock', baseRequest())
await expect(run.result).resolves.toEqual({
output: [{ type: 'text', text: 'hello from mock' }],
structured: undefined,
stopReason: 'completed',
})
})
it('registers under a configurable name', async () => {
const ctx = await mount({ name: 'spawn' })
expect(ctx.subagents.list()).toEqual(['spawn'])
})
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: { answer: { type: 'number' } } }))
await expect(run.result).resolves.toMatchObject({ structured: { answer: 42 } })
})
it('omits structured output when outputSchema capability is off', async () => {
const ctx = await mount({ capabilities: { outputSchema: false } })
// 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())
await expect(run.result).resolves.toMatchObject({ structured: undefined })
})
it('honors a configured stop reason', async () => {
const ctx = await mount({ stopReason: 'refusal' })
const run = 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 () => {
const ctx = await mount()
const run = ctx.subagents.start('mock', baseRequest())
run.cancel()
await expect(run.result).resolves.toMatchObject({ stopReason: 'aborted' })
})
it('unregisters the provider when the owning fiber is disposed (HMR safety)', async () => {
const ctx = new Context()
await ctx.plugin(SubagentService)
const fiber = await ctx.plugin(mock, { name: 'mock' })
expect(ctx.subagents.list()).toEqual(['mock'])
await fiber.dispose()
expect(ctx.subagents.list()).toEqual([])
})
it('has the namespace-plugin export shape (no stray default) so the Loader keeps name/inject/Config/apply', () => {
// Postmortem 0001 guard: this plugin HAS `inject = ['subagents']`, so a stray
// `export default apply` would collapse the module via `unwrapExports`
// (`exports.default ?? exports`), DROP `inject`, and crash at load with
// "cannot get property … without inject". Guard the shape directly.
expect('default' in mock).toBe(false)
expect(mock.name).toBe('subagent-mock')
expect(mock.inject).toEqual(['subagents'])
const loader = Object.create(Loader.prototype) as Loader
const unwrapped = loader.unwrapExports(mock) as Record<string, unknown>
expect(unwrapped).toBe(mock)
expect(unwrapped.name).toBe('subagent-mock')
expect(unwrapped.inject).toEqual(['subagents'])
expect(typeof unwrapped.apply).toBe('function')
})
})

View File

@@ -0,0 +1,30 @@
{
"extends": "../../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "lib"
},
"include": [
"src"
],
"references": [
{
"path": "../../../vendor/cosmokit"
},
{
"path": "../../../vendor/cordis"
},
{
"path": "../../../vendor/schemastery"
},
{
"path": "../../core/agent"
},
{
"path": "../../llm/llm"
},
{
"path": "../../subagent/subagent"
}
]
}