Merge branch 'master' into feat/tui-package
This commit is contained in:
@@ -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).
|
||||
|
||||
@@ -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:^",
|
||||
|
||||
@@ -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([])
|
||||
})
|
||||
})
|
||||
104
packages/subagent/tool-subagent/tests/scripted-provider.ts
Normal file
104
packages/subagent/tool-subagent/tests/scripted-provider.ts
Normal 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))
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
@@ -9,6 +9,5 @@ Packages that exist to serve development, testing, and the examples rather than
|
||||
| `invariants/` | Runtime event-contract assertions for development diagnostics | (listens on `session/*`, `agent/*`) |
|
||||
| `loader-smoke/` | Shared real-Loader subprocess harness for keyless example smokes | (library — imported by example e2e suites) |
|
||||
| `llm-replay/` | Record/replay adapter: short-circuits `llm/stream` from a recorded session JSONL (keyless snapshot tests) | (listens on `llm/stream`) |
|
||||
| `subagent-mock/` | Scripted `SubagentProvider` for deterministic seam/tool tests | (registers on `ctx.subagents`) |
|
||||
|
||||
`invariants` is development support but has no environment guard: it runs wherever registered, and the default `dsh-agent-spine-demo` bundle mounts it unconditionally. `agent-loop-testkit` centralizes the mandatory service spine for hand-built AgentLoop tests without owning their loop or scenario. `llm-replay` backs the demos and the snapshot test tier under the per-file coverage gate. `acp-snapshot` carries the ACP subprocess/client boundary plus the snapshot harness, normalizers, and suite machinery, while `loader-smoke` owns the parallel stdio/Loader process boundary used by keyless example e2e suites. `subagent-mock` exercises the real `ctx.subagents` load path without a model or child agent. A package graduates OUT of `support/` into a product group only when it gains documented product consumers.
|
||||
`invariants` is development support but has no environment guard: it runs wherever registered, and the default `dsh-agent-spine-demo` bundle mounts it unconditionally. `agent-loop-testkit` centralizes the mandatory service spine for hand-built AgentLoop tests without owning their loop or scenario. `llm-replay` backs the demos and the snapshot test tier under the per-file coverage gate. `acp-snapshot` carries the ACP subprocess/client boundary plus the snapshot harness, normalizers, and suite machinery, while `loader-smoke` owns the parallel stdio/Loader process boundary used by keyless example e2e suites. A package graduates OUT of `support/` into a product group only when it gains documented product consumers.
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
# @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, async start, start-time capability validation, required-signal cancellation, `result`, `dispose`, and structured output 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`, 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. |
|
||||
|
||||
Aborting the required request signal or disposing before `result` settles flips the stop reason to `aborted`, so both holder-facing cancellation paths are observable.
|
||||
|
||||
## Model Experience
|
||||
|
||||
Indirectly, through `dsh-tool-subagent`, which renders this test provider's configured reply or stop-reason error into the parent test history.
|
||||
|
||||
## Known Limitations and Deferred Work
|
||||
|
||||
- **Scripted provider only** — it does not run a model, create a child agent, or exercise real prompt/tool-loop behavior.
|
||||
- **One synthetic outcome per run** — it models no multi-turn, streaming, steering, resume, or subprocess transport behavior.
|
||||
@@ -1,42 +0,0 @@
|
||||
{
|
||||
"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/types/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./lib/types/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./src/*": "./src/*",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"lib/index.js",
|
||||
"lib/types/**/*.d.ts",
|
||||
"lib/types/**/*.d.ts.map",
|
||||
"src"
|
||||
],
|
||||
"license": "BSD-3-Clause",
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/dsh-agent": "^0.0.1",
|
||||
"@deepseek-ai/dsh-llm": "^0.0.1",
|
||||
"@deepseek-ai/dsh-session": "^0.0.1",
|
||||
"@deepseek-ai/dsh-subagent": "^0.0.1",
|
||||
"cordis": "^4.0.0-rc.7"
|
||||
},
|
||||
"dependencies": {
|
||||
"schemastery": "^3.18.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@deepseek-ai/dsh-agent": "workspace:^",
|
||||
"@deepseek-ai/dsh-llm": "workspace:^",
|
||||
"@deepseek-ai/dsh-session": "workspace:^",
|
||||
"@deepseek-ai/dsh-subagent": "workspace:^",
|
||||
"@cordisjs/plugin-loader": "^1.0.0-rc.5",
|
||||
"cordis": "^4.0.0-rc.7"
|
||||
}
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
/**
|
||||
* Scripted, model-free subagent provider for deterministic coverage of registration,
|
||||
* capability checks, lifecycle, the model-facing tool, and structured results through the real
|
||||
* loader path. It is a named-export functional plugin; no default export.
|
||||
* @module @deepseek-ai/dsh-subagent-mock
|
||||
*/
|
||||
|
||||
import type { Context } from 'cordis'
|
||||
import z from 'schemastery'
|
||||
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 STOP_REASONS = ['completed', 'aborted', 'error', 'max-tokens', 'refusal'] as const
|
||||
|
||||
const DEFAULT_CAPS: SubagentCapabilities = { outputSchema: true, depthLimit: true, toolFilter: true, persona: true }
|
||||
|
||||
/** Scripted provider whose configured result aborts if disposed or signalled first. */
|
||||
class MockSubagentProvider implements SubagentProvider {
|
||||
readonly capabilities: SubagentCapabilities
|
||||
readonly inheritsParentContext: boolean
|
||||
|
||||
constructor(
|
||||
readonly name: string,
|
||||
private readonly config: Config,
|
||||
) {
|
||||
this.capabilities = { ...DEFAULT_CAPS, ...config.capabilities }
|
||||
this.inheritsParentContext = config.inheritsParentContext ?? false
|
||||
}
|
||||
|
||||
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'
|
||||
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).
|
||||
const id = SessionId(`mock-subagent:${this.name}:${request.parent.id}`)
|
||||
|
||||
const resultFor = (): SubagentResult => ({
|
||||
output,
|
||||
...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,
|
||||
localAgent: undefined,
|
||||
result,
|
||||
dispose(): Promise<void> {
|
||||
flags.cancelled = true
|
||||
request.signal.removeEventListener('abort', onAbort)
|
||||
return Promise.resolve()
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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>
|
||||
/**
|
||||
* The conversation-history descriptor to declare
|
||||
* ({@link SubagentProvider.inheritsParentContext}); default `false` (fresh
|
||||
* conversation). Set `true` to exercise seeded/fork wording in consumer
|
||||
* tests. This flag says nothing about tool, service, scope, or authority
|
||||
* inheritance.
|
||||
*/
|
||||
inheritsParentContext?: boolean
|
||||
/**
|
||||
* 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(),
|
||||
persona: z.boolean(),
|
||||
}),
|
||||
inheritsParentContext: z.boolean(),
|
||||
structured: z.any(),
|
||||
})
|
||||
|
||||
export function apply(ctx: Context, config: Config): void {
|
||||
ctx.subagents.registerProvider(new MockSubagentProvider(config.name, config))
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { Context } from 'cordis'
|
||||
import Loader from '@cordisjs/plugin-loader'
|
||||
import { type Agent } from '@deepseek-ai/dsh-agent'
|
||||
|
||||
import SubagentService, { type SubagentStartRequest } from '@deepseek-ai/dsh-subagent'
|
||||
import * as mock from '../src/index.ts'
|
||||
import { SessionId } from '@deepseek-ai/dsh-session'
|
||||
|
||||
/** A minimal parent — the mock provider only reads `parent.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<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 = await ctx.subagents.start('mock', baseRequest())
|
||||
await expect(run.result).resolves.toEqual({
|
||||
output: [{ type: 'text', text: 'hello from mock' }],
|
||||
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('surfaces a structured result when the request carries an outputSchema', async () => {
|
||||
const ctx = await mount({ reply: 'r', structured: { answer: 42 } })
|
||||
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 = await ctx.subagents.start('mock', baseRequest({ outputSchema: { type: 'object', properties: { answer: { type: 'number' } } } }))
|
||||
await expect(run.result).resolves.toMatchObject({ structured: { reply: 'fallback reply' } })
|
||||
})
|
||||
|
||||
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 = 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 = await ctx.subagents.start('mock', baseRequest())
|
||||
await expect(run.result).resolves.toMatchObject({ stopReason: 'refusal' })
|
||||
})
|
||||
|
||||
it('flips the stop reason to aborted when the signal fires before the result settles', async () => {
|
||||
const ctx = await mount()
|
||||
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' })
|
||||
})
|
||||
|
||||
it('rejects an already-aborted request before starting publication', async () => {
|
||||
const ctx = await mount()
|
||||
const controller = new AbortController()
|
||||
controller.abort()
|
||||
|
||||
await expect(ctx.subagents.start('mock', baseRequest({ signal: controller.signal })))
|
||||
.rejects.toThrow('mock subagent start aborted before publication')
|
||||
})
|
||||
|
||||
it('rejects when cancellation wins the asynchronous publication handoff', async () => {
|
||||
const ctx = await mount()
|
||||
const controller = new AbortController()
|
||||
const pending = ctx.subagents.start('mock', baseRequest({ signal: controller.signal }))
|
||||
|
||||
controller.abort()
|
||||
|
||||
await expect(pending).rejects.toThrow('mock subagent start aborted before publication')
|
||||
})
|
||||
|
||||
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', () => {
|
||||
// A default export would make Loader unwrap only that value and drop `inject`.
|
||||
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')
|
||||
})
|
||||
})
|
||||
@@ -1,30 +0,0 @@
|
||||
{
|
||||
"extends": "../../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"outDir": "lib/types"
|
||||
},
|
||||
"include": [
|
||||
"src"
|
||||
],
|
||||
"references": [
|
||||
{
|
||||
"path": "../../../vendor/cosmokit"
|
||||
},
|
||||
{
|
||||
"path": "../../../vendor/cordis"
|
||||
},
|
||||
{
|
||||
"path": "../../../vendor/schemastery"
|
||||
},
|
||||
{
|
||||
"path": "../../core/agent"
|
||||
},
|
||||
{
|
||||
"path": "../../llm/llm"
|
||||
},
|
||||
{
|
||||
"path": "../../subagent/subagent"
|
||||
}
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user