refactor: apply repository naming contract

Apply the accepted pre-release package, service, type, directory, and role renames as one repository-wide change.
This commit is contained in:
Tianyi Cui
2026-08-13 00:36:22 +08:00
parent 101df7cf58
commit a2d0f7f411
3281 changed files with 21730 additions and 21592 deletions

View File

@@ -0,0 +1,6 @@
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/subagent/subagent-spawn-in-process/README.md
README.md: f1fb96f2230359cb3ff55c630f29fd34345dbed7
README.zh.md: 940701d6fac78ce75fda24519fa22b268085ea1a

View File

@@ -0,0 +1,55 @@
# @deepseek-ai/dsh-subagent-spawn-in-process
English | [中文](README.zh.md)
The spawn provider creates a fresh child `Agent` in the current process. The child has its own session, sees no parent conversation history, and reuses the host's agent factory and LLM/tool services.
## Behavior
`start(request)` delegates to [`startInProcessRun`](../subagent-in-process-driver/README.md) with no seed and awaits publication before returning. The child receives parent working-directory/session lineage and inherits the parent model unless overridden, but starts with an empty conversation.
The shared driver owns depth checking, persona and tool-filter setup, structured output, required-signal cancellation, one-shot execution, result reading, and quiescent disposal. A startup rejection leaves no published child; provider unload after fulfillment does not revoke the holder-owned run.
## Capabilities
Spawn advertises `{ outputSchema: true, depthLimit: true, toolFilter: true, persona: true }` because it controls the child's creation window and can enforce all four features.
## Config
| Key | Meaning |
|---|---|
| `providerName` | Registry name on `ctx.subagents` (default `spawn`). |
## Model Experience
### Child-agent request
#### What the model sees
The fresh child receives the standalone task content verbatim, inherits the parent model and workspace by default, and sees the global prompt with any configured child-scoped persona shadow. A tool filter removes global wire schemas, executable lookup, and Code Mode SDK bindings for that child but leaves independently registered guidance. It receives zero parent conversation messages; the filter is visibility/composition, not an authority grant inherited from the parent.
#### Token effect
The child pays for a new independent context and history; no parent-history tokens are duplicated. Persona changes this child's repeated prompt cost, while filtering changes its schema or generated SDK cost.
#### KV Cache effect
Independent of the parent request cache. Child history grows append-only, while persona, tool-filter, generated-SDK, provider, or model changes establish a different child prefix.
### Parent tool result, indirectly
#### What the model sees
Through `dsh-tool-subagent`, the parent receives only the child's final output or stop-reason error.
#### Token effect
Parent input grows by one data-dependent result retained until compaction.
#### KV Cache effect
Append-only; newly visible content follows the reusable request prefix and does not invalidate existing KV-cache entries.
## Known Limitations and Deferred Work
- **Fresh means no parent transcript** — the child inherits cwd, lineage, model, and explicitly configured persona/tool restrictions, but none of the parent's conversation; use the fork provider when completed-turn context is required.

View File

@@ -0,0 +1,55 @@
# @deepseek-ai/dsh-subagent-spawn-in-process
[English](README.md) | 中文
spawn 提供方会在当前进程中创建一个全新的子 `Agent`。子 agent智能体有自己的会话看不到父 agent 的对话历史,并复用宿主的 agent 工厂及 LLM大语言模型/工具服务。
## 行为
`start(request)` 不传入 seed直接委托给 [`startInProcessRun`](../subagent-in-process-driver/README.md),并在子 agent 发布后才返回。子 agent 获得父 agent 的工作目录/会话谱系,并默认继承父 agent 模型(除非覆盖),但以空对话开始运行。
共享驱动器负责深度检查、persona 与工具过滤器设置、结构化输出、通过必需的信号执行取消、单次执行、结果读取和完全停稳后的 dispose资源释放。启动遭拒不会留下已发布的子 agent启动调用兑现后卸载提供方也不会撤销由持有方拥有的运行。
## 能力
spawn 声明 `{ outputSchema: true, depthLimit: true, toolFilter: true, persona: true }`,因为它控制子 agent 的创建窗口,能够强制执行全部四项功能。
## 配置
| 键 | 含义 |
|---|---|
| `providerName` | `ctx.subagents` 上的注册表名称(默认 `spawn`)。 |
## 模型体验
### 子 agent 请求
#### 模型看到的内容
全新的子 agent 逐字接收独立任务内容,默认继承父 agent 的模型和工作区,并看到带有已配置子 agent 作用域 persona 遮蔽的全局提示词。工具过滤器会为该子 agent 移除全局协议 schema、可执行工具查找和 Code Mode SDK 绑定,但保留独立注册的指导内容。它不接收任何父 agent 对话消息;过滤控制的是可见性与组合,并非从父 agent 继承的权限授予。
#### Token 影响
子 agent 会为全新的独立上下文和历史消耗 token不会复制父 agent 历史的 token。persona 会改变该子 agent 反复使用的提示词成本,过滤则会改变其 schema 或生成 SDK 的成本。
#### KV Cache 影响
与父 agent 请求缓存相互独立。子 agent 历史仅追加persona、工具过滤、生成 SDK、提供方或模型变化会建立不同的子 agent 前缀。
### 父 agent 工具结果(间接)
#### 模型看到的内容
通过 `dsh-tool-subagent`,父 agent 只接收子 agent 的最终输出或结束原因错误。
#### Token 影响
父 agent 输入会增加一个取决于数据的结果并保留到压缩compaction为止。
#### KV Cache 影响
仅追加;新增可见内容位于可复用请求前缀之后,不会使现有 KV Cache 条目失效。
## 已知限制与暂缓事项
- **全新表示不含父 agent transcript文本记录**:子 agent 会继承 cwd、谱系、模型及显式配置的 persona/工具限制,但不继承父 agent 的任何对话;需要已完成轮次上下文时,请使用 fork 提供方。

View File

@@ -0,0 +1,60 @@
{
"name": "@deepseek-ai/dsh-subagent-spawn-in-process",
"description": "In-process spawn subagent backend: runs a fresh child agent on ctx.agents",
"version": "0.0.1-rc.2",
"publishConfig": {
"access": "restricted"
},
"repository": {
"type": "git",
"url": "git+https://github.com/deepseek-ai/deepseek-harness.git",
"directory": "packages/subagent/subagent-spawn-in-process"
},
"type": "module",
"main": "lib/index.js",
"types": "lib/types/index.d.ts",
"exports": {
".": {
"types": "./lib/types/index.d.ts",
"default": "./lib/index.js"
},
"./invariant": {
"types": "./lib/types/invariant.d.ts",
"default": "./lib/invariant.js"
},
"./src/*": "./src/*",
"./package.json": "./package.json"
},
"files": [
"lib/index.js",
"lib/invariant.js",
"lib/types/**/*.d.ts"
],
"license": "BSD-3-Clause",
"peerDependencies": {
"@deepseek-ai/dsh-invariants": "workspace:^",
"@deepseek-ai/dsh-subagent": "workspace:^",
"@deepseek-ai/dsh-subagent-in-process-driver": "workspace:^",
"@deepseek-ai/cordis": "workspace:^"
},
"dependencies": {
"@deepseek-ai/schemastery": "workspace:^"
},
"devDependencies": {
"@deepseek-ai/cordis-plugin-loader": "workspace:^",
"@deepseek-ai/dsh-agent": "workspace:^",
"@deepseek-ai/dsh-agent-loop": "workspace:^",
"@deepseek-ai/dsh-agent-loop-testkit": "workspace:^",
"@deepseek-ai/dsh-bash-local": "workspace:^",
"@deepseek-ai/dsh-subprocess-local": "workspace:^",
"@deepseek-ai/dsh-invariants": "workspace:^",
"@deepseek-ai/dsh-llm": "workspace:^",
"@deepseek-ai/dsh-llm-deepseek": "workspace:^",
"@deepseek-ai/dsh-session": "workspace:^",
"@deepseek-ai/dsh-subagent": "workspace:^",
"@deepseek-ai/dsh-subagent-in-process-driver": "workspace:^",
"@deepseek-ai/dsh-tool-bash": "workspace:^",
"@deepseek-ai/dsh-tool-subagent": "workspace:^",
"@deepseek-ai/cordis": "workspace:^"
}
}

View File

@@ -0,0 +1,64 @@
/**
* The in-process SPAWN subagent backend: registers a {@link SubagentProvider} on
* `ctx.subagents` that runs each child as a fresh child {@link Agent} on the same cordis
* context (its own session, own system prompt, zero parent context). The cheapest transport,
* reusing the agent factory's quiescent teardown.
* @module @deepseek-ai/dsh-subagent-spawn-in-process
*/
import type { Context } from '@deepseek-ai/cordis'
import z from '@deepseek-ai/schemastery'
import type {
ContinuableCreateSpec,
ResolvedSubagentStartRequest,
SubagentCapabilities,
SubagentProvider,
} from '@deepseek-ai/dsh-subagent'
import { startInProcessRun } from '@deepseek-ai/dsh-subagent-in-process-driver'
export const name = 'subagent-spawn-in-process'
// `tools` is deliberately not injected: the child factory already provides it during setup,
// and adding it here would unnecessarily change this provider's apply timing.
export const inject = ['subagents']
/** Config: the registry name to register the provider under. */
export interface Config {
/** Provider name on `ctx.subagents` (default `spawn`). */
providerName: string
}
export const Config: z<Config> = z.object({
providerName: z.string().default('spawn'),
})
/**
* The spawn provider. Supports every start-time capability: `depthLimit` (it
* constructs the child, so it can enforce a recursion cap), `outputSchema`
* (the scoped structured runtime), and `toolFilter`/`persona` (scoped
* `restrict()` and a scoped shadowing persona section, applied in the child's
* creation window).
*/
class SpawnInProcessProvider implements SubagentProvider {
readonly capabilities: SubagentCapabilities = { outputSchema: true, depthLimit: true, toolFilter: true, persona: true }
// Context contract: a spawned child starts fresh — it never sees the parent conversation.
readonly inheritsParentContext = false
constructor(readonly name: string) {}
start(request: ResolvedSubagentStartRequest) {
// Fresh child: no seed. The shared driver mints ids, stamps cwd/lineage/
// depth, drives the one-shot (including the structured capture when the
// request carries an outputSchema), and maps the result.
return startInProcessRun(request, {})
}
prepareContinuable(): Promise<ContinuableCreateSpec> {
// A spawned child starts fresh, so it contributes no seed; the continuation
// manager owns every later operation on it.
return Promise.resolve({})
}
}
export function apply(ctx: Context, config: Config): void {
ctx.subagents.registerProvider(new SpawnInProcessProvider(config.providerName))
}

View File

@@ -0,0 +1,30 @@
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-subagent-spawn-in-process`.
* @module @deepseek-ai/dsh-subagent-spawn-in-process/invariant
*/
/* jscpd:ignore-start */
import type { Context } from '@deepseek-ai/cordis'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
const PACKAGE_NAME = '@deepseek-ai/dsh-subagent-spawn-in-process'
/** Cordis companion plugin name. */
export const name = 'subagent-spawn-in-process-invariant'
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/**
* No runtime invariant: this package exposes no independent event sequence or mutable data relation
* beyond contracts enforced at its owning seam.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
* @param ctx - Cordis context carrying the invariant service.
* @returns the installed registration's disposer after setup succeeds.
*/
export const apply = (ctx: Context): Promise<() => void> =>
Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))
/* jscpd:ignore-end */

View File

@@ -0,0 +1,52 @@
import { Context } from '@deepseek-ai/cordis'
import type { Agent } from '@deepseek-ai/dsh-agent'
import AgentLoop from '@deepseek-ai/dsh-agent-loop'
import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit'
import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local'
import * as BashEnvPlugin from '@deepseek-ai/dsh-shell-env'
import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local'
import * as ToolBash from '@deepseek-ai/dsh-tool-bash'
import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek'
import SubagentRuntime from '@deepseek-ai/dsh-subagent'
import * as Spawn from '../src/index.ts'
import * as ToolSubagent from '@deepseek-ai/dsh-tool-subagent'
/**
* Shared harness for the spawn-backend e2e: the full real stack (DeepSeek
* adapter + real bash tool + the subagent tool bound to the spawn backend), so
* a real parent agent can delegate to a real in-process child that does real
* work (writes a file). Lives outside the *.e2e.ts pattern so importing it never
* re-registers another file's tests.
*/
export async function spawnHarness(workdir: string): Promise<Context> {
const ctx = new Context()
// This harness installs only the global default persona, so both parent and
// spawned children render it. It stays neutral for both roles; the
// delegation nudge lives in the e2e's user prompt and the subagent tool's
// own description.
await mountAgentLoopTestDependencies(ctx, {
systemPrompt: { persona: 'You are a coding agent. Report only when the requested work is done.' },
})
await ctx.plugin(AgentLoop, { agents: [] })
await ctx.plugin(LlmDeepSeek)
await ctx.plugin(LocalSubprocessRuntime)
await ctx.plugin(BashEnvPlugin)
await ctx.plugin(LocalBashExecutor, { cwd: workdir, timeoutMs: 30_000 })
await ctx.plugin(ToolBash)
await ctx.plugin(SubagentRuntime)
await ctx.plugin(Spawn, { providerName: 'spawn' })
// The model-facing subagent tool, bound to the spawn backend.
await ctx.plugin(ToolSubagent, { provider: 'spawn' })
return ctx
}
export function waitForIdle(ctx: Context, agent: Agent): Promise<void> {
return new Promise((resolve) => {
const dispose = ctx.on('agent/status', ({ agent: subject, status }) => {
if (subject === agent && status === 'idle') {
dispose()
resolve()
}
})
})
}

View File

@@ -0,0 +1,45 @@
import { createUserMessage } from '@deepseek-ai/dsh-llm'
import { mkdtemp, readFile, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import type { Context } from '@deepseek-ai/cordis'
import { spawnHarness, waitForIdle } from './harness.ts'
import { SessionId } from '@deepseek-ai/dsh-session'
/** Key-gated smoke for a real parent delegating filesystem work to a real child. */
let ctx: Context | undefined
let workdir: string | undefined
afterEach(async () => {
await ctx?.fiber.dispose()
ctx = undefined
if (workdir !== undefined) await rm(workdir, { recursive: true, force: true })
workdir = undefined
})
describe.skipIf(!process.env.DEEPSEEK_API_KEY)('spawn backend with-key smoke', () => {
it('a parent delegates to a child that writes a file on disk', async () => {
workdir = await mkdtemp(join(tmpdir(), 'dsh-subagent-spawn-e2e-'))
ctx = await spawnHarness(workdir)
const parent = ctx.agentLoop.create(SessionId('e2e-parent'), { provider: 'deepseek-official', model: 'deepseek-v4-flash' })
parent.followup(createUserMessage({
content: [{ type: 'text', text:
'Use the subagent tool to delegate this exact task: "Use the bash tool to write the text '
+ 'SUBAGENT_WAS_HERE into a file named proof.txt in the current directory." '
+ 'After the subagent finishes, tell me it is done.' }], source: { kind: 'user' } }))
await waitForIdle(ctx, parent)
// Assert the filesystem effect independently of the model response.
const proof = await readFile(join(workdir, 'proof.txt'), 'utf8')
expect(proof).toContain('SUBAGENT_WAS_HERE')
// The parent's log records the subagent tool/call + its result (not the
// child's internal steps).
const events = [...parent.session.events]
const subagentCalls = events.filter(e => e.type === 'tool/call' && e.data.name === 'subagent')
expect(subagentCalls.length).toBeGreaterThan(0)
}, 180_000)
})

View File

@@ -0,0 +1,496 @@
import { createUserMessage } from '@deepseek-ai/dsh-llm'
import { describe, expect, it } from 'vitest'
import { Context, symbols, type EffectMeta } from '@deepseek-ai/cordis'
import Loader from '@deepseek-ai/cordis-plugin-loader'
import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent'
import { SessionId } from '@deepseek-ai/dsh-session'
import AgentLoop from '@deepseek-ai/dsh-agent-loop'
import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit'
import InvariantRegistry from '@deepseek-ai/dsh-invariants'
import * as SessionInvariant from '@deepseek-ai/dsh-session/invariant'
import * as AgentInvariant from '@deepseek-ai/dsh-agent/invariant'
import * as AgentLoopInvariant from '@deepseek-ai/dsh-agent-loop/invariant'
import SubagentRuntime, { type SubagentStartRequest } from '@deepseek-ai/dsh-subagent'
import { MockAdapter, maxTokensResponse, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts'
import * as spawn from '../src/index.ts'
import { STRUCTURED_OUTPUT_TOOL } from '@deepseek-ai/dsh-subagent-in-process-driver'
import { defineContentToolFixture } from '@deepseek-ai/dsh-tools'
type Script = ConstructorParameters<typeof MockAdapter>[0]
async function mountInvariants(ctx: Context): Promise<void> {
await ctx.plugin(InvariantRegistry)
await ctx.plugin(SessionInvariant)
await ctx.plugin(AgentInvariant)
await ctx.plugin(AgentLoopInvariant)
}
/**
* Drives the REAL spawn backend end-to-end: a real agent loop + a scripted mock
* MODEL (the only mocked boundary) + the real SubagentRuntime + the real
* invariant service plus package companions (so a malformed child session log would fail the test).
* The parent is a real config agent; the spawn provider creates a real child
* agent on the same context and we assert its output.
*/
async function setup(script: Script) {
const ctx = new Context()
const adapter = new MockAdapter(script)
await mountAgentLoopTestDependencies(ctx)
await mountInvariants(ctx)
await ctx.plugin(AgentLoop, { agents: [] })
await ctx.plugin(SubagentRuntime)
await ctx.plugin(spawn, { providerName: 'spawn' })
ctx.llm.registerAdapter(['mock'], adapter)
const parent = ctx.agentLoop.create(SessionId('parent'), { provider: 'mock', model: 'mock' })
return { ctx, parent, adapter }
}
function text(blocks: { type: string; text?: string }[]): string {
return blocks.filter(b => b.type === 'text').map(b => b.text).join('')
}
function start(ctx: Context, provider: string, request: Omit<SubagentStartRequest, 'signal'> & { signal?: AbortSignal }) {
return ctx.subagents.start(provider, { signal: request.signal ?? new AbortController().signal, ...request })
}
/** Invoke the child lifecycle effect while its parent-owned setup is still unpublished. */
function disposeChildLifecycle(parent: Agent): void {
const lifecycle = [...parent.ctx.fiber._disposables]
.find((dispose) => {
const effect = (dispose as typeof dispose & { [symbols.effect]?: EffectMeta })[symbols.effect]
return effect?.label.startsWith('agentLoop.lifecycle(') === true
})
if (lifecycle === undefined) throw new Error('child lifecycle effect not found')
void lifecycle()
}
describe('dsh-subagent-spawn-in-process', () => {
it('runs a fresh child to completion and returns its final assistant output', async () => {
// One model call for the child: a plain text answer.
const { ctx, parent } = await setup([textResponse('child answer')])
const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'do X' }], parent })
const result = await run.result
expect(result.stopReason).toBe('completed')
expect(text(result.output)).toBe('child answer')
await run.dispose()
})
it('emits subagent/start only after the fresh child is published', async () => {
const { ctx, parent } = await setup([textResponse('child answer')])
let childAtStart: ReturnType<typeof ctx.agents.get>
ctx.on('subagent/start', (info) => {
if (info.provider === 'spawn') childAtStart = ctx.agents.get(info.id)
})
const starting = start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'do X' }], parent })
// Creation is asynchronous; no lifecycle claim is made while the child is
// still inside its unpublished setup transaction.
expect(childAtStart).toBeUndefined()
const run = await starting
expect(childAtStart).toBe(ctx.agents.get(run.id))
expect(childAtStart?.id).toBe(run.id)
await run.result
await run.dispose()
})
it('gives the child its OWN session (not the parent\'s), with parentSession lineage', async () => {
const { ctx, parent } = await setup([textResponse('hi')])
const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent })
await run.result
const child = ctx.agents.get(run.id)!
expect(child.session.header.id).not.toBe(parent.session.header.id)
expect(child.session.header.parentSession).toBe(parent.session.header.id)
await run.dispose()
})
it('a fresh child does NOT inherit the parent conversation (its log starts empty before the prompt)', async () => {
// Drive the parent through one real turn so it has history, THEN spawn.
const { ctx, parent } = await setup([textResponse('parent turn'), textResponse('child sees nothing')])
parent.followup(createUserMessage({ content: [{ type: 'text', text: 'parent prompt' }], source: { kind: 'user' } }))
await parent.whenIdle()
const parentEventCount = parent.session.events.length
expect(parentEventCount).toBeGreaterThan(0)
const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'child prompt' }], parent })
await run.result
const child = ctx.agents.get(run.id)!
// The child's first user/message is its OWN prompt, not the parent's history.
const firstUser = child.session.events.find(e => e.type === 'user/message')
expect(firstUser).toBeDefined()
await run.dispose()
})
it('disposes the child to quiescence (agent removed from the registry)', async () => {
const { ctx, parent } = await setup([textResponse('x')])
const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent })
await run.result
expect(ctx.agents.get(run.id)).toBeDefined()
await run.dispose()
// After dispose, the child is unregistered (the AgentHandle teardown ran).
expect(ctx.agents.get(run.id)).toBeUndefined()
})
it('stamps child depth = parent depth + 1 (via the merged AgentOptions field)', async () => {
const { ctx, parent } = await setup([textResponse('x')])
expect(parent.options.subagentDepth).toBeUndefined()
const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent })
await run.result
const child = ctx.agents.get(run.id)!
expect(child.options.subagentDepth).toBe(1)
await run.dispose()
})
it('refuses to spawn past maxDepth (depthLimit capability)', async () => {
const { ctx, parent } = await setup([])
// parent is depth 0, child would be depth 1 — cap at 0 forbids any child.
await expect(start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent, maxDepth: 0 }))
.rejects.toThrow('subagent depth 1 exceeds maxDepth 0')
})
it('maps a child that hit its token ceiling to stopReason "max-tokens"', async () => {
const { ctx, parent } = await setup([maxTokensResponse('cut off')])
const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent })
const result = await run.result
expect(result.stopReason).toBe('max-tokens')
await run.dispose()
})
it('maps a child whose turn errored (script exhausted) to stopReason "error" with empty output', async () => {
// Empty script: the child's first model call throws "script exhausted", the
// turn ends `error`, and there is no assistant/message → empty output.
const { ctx, parent } = await setup([])
const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent })
const result = await run.result
expect(result.stopReason).toBe('error')
expect(result.output).toEqual([])
await run.dispose()
})
it('rejects without publishing when the request signal is already aborted', async () => {
// An already-aborted signal emits no future event, so start must check it before listening and
// settle aborted without running the child. The empty model script proves no turn occurs.
const controller = new AbortController()
controller.abort()
const { ctx, parent } = await setup([])
await expect(start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent, signal: controller.signal }))
.rejects.toThrow('aborted before child publication')
})
it('same-tick cancellation rejects start and prevents child publication', async () => {
// Same-tick cancellation must win before async factory publication: no child may become
// visible, `started` must not fulfill, and the empty script proves no model turn occurs.
const { ctx, parent } = await setup([])
const beforeAgents = ctx.agents.list().length
const beforeSessions = ctx.sessions.list().length
const published: string[] = []
ctx.on('session/created', () => void published.push('session/created'))
ctx.on('agent/created', () => void published.push('agent/created'))
ctx.on('agent/session-start', () => void published.push('agent/session-start'))
ctx.on('subagent/start', () => void published.push('subagent/start'))
ctx.on('subagent/end', () => void published.push('subagent/end'))
const controller = new AbortController()
const starting = start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent, signal: controller.signal })
controller.abort('early')
await expect(starting).rejects.toThrow()
await Promise.resolve()
expect(ctx.agents.list()).toHaveLength(beforeAgents)
expect(ctx.sessions.list()).toHaveLength(beforeSessions)
expect(published).toEqual([])
})
it('cancelling a running child settles the run as aborted (the abort bridge + cancel())', async () => {
// 'hang' makes the child's model stream one chunk then wait until aborted.
const controller = new AbortController()
const { ctx, parent } = await setup(['hang'])
const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent, signal: controller.signal })
// Let the child's turn start, then abort via the request signal (the
// backend bridges it to child.cancel()).
await new Promise(r => setTimeout(r, 30))
controller.abort()
const result = await run.result
expect(result.stopReason).toBe('aborted')
await run.dispose()
})
it('dispose cancels the child and reaches quiescence', async () => {
const { ctx, parent } = await setup(['hang'])
const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent })
await new Promise(r => setTimeout(r, 30))
await run.dispose()
const result = await run.result
expect(result.stopReason).toBe('aborted')
})
it('a one-shot run exposes neither steer nor resume; continuable creation is a provider capability', async () => {
const { ctx, parent } = await setup([textResponse('x')])
const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent })
// A run is one disposable foreground activation: it has no steering and no
// cold resume. Continuable conversations never become a run — the
// continuation manager drives them through the provider's
// `prepareContinuable` capability instead.
expect('steer' in run).toBe(false)
expect('resume' in run).toBe(false)
await run.result
// The spawn provider DOES advertise continuable creation, and — because a
// spawned child starts fresh — contributes no seed.
const provider = ctx.subagents.getProvider('spawn')!
expect(typeof provider.prepareContinuable).toBe('function')
const spec = await provider.prepareContinuable!({
sessionId: SessionId('continuable-child'),
parent,
signal: new AbortController().signal,
})
expect(spec.seed).toBeUndefined()
await run.dispose()
})
it('inherits the parent cwd into the child session', async () => {
const { ctx } = await setup([textResponse('x')])
// A parent WITH a cwd (config agents have none, so create one explicitly).
const parentHandle = await ctx.agents.create({
sessionId: SessionId('cwd-parent-session'),
meta: { cwd: '/tmp/parent-workspace' },
agentOptions: { provider: 'mock', model: 'mock' },
})
const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent: parentHandle.agent })
await run.result
const child = ctx.agents.get(run.id)!
expect(child.session.header.cwd).toBe('/tmp/parent-workspace')
await run.dispose()
await parentHandle.dispose()
})
it('uses request.agentOptions.model when the parent has no model of its own', async () => {
const { ctx } = await setup([textResponse('explicit model child')])
// A parent with NO model (its own turns would need one supplied per-request).
const parentHandle = await ctx.agents.create({
sessionId: SessionId('modelless-parent-session'),
agentOptions: {},
})
// The request supplies the child's model explicitly.
const run = await start(ctx, 'spawn', {
prompt: [{ type: 'text', text: 'p' }],
parent: parentHandle.agent,
agentOptions: { provider: 'mock', model: 'mock' },
})
const result = await run.result
expect(result.stopReason).toBe('completed')
expect(text(result.output)).toBe('explicit model child')
await run.dispose()
await parentHandle.dispose()
})
it('advertises every start-time capability (depthLimit, outputSchema, toolFilter, persona)', async () => {
const { ctx } = await setup([])
const provider = ctx.subagents.getProvider('spawn')!
expect(provider.capabilities).toEqual({ outputSchema: true, depthLimit: true, toolFilter: true, persona: true })
})
it('unregisters the provider when its fiber is disposed (HMR safety)', async () => {
const ctx = new Context()
await ctx.plugin(SubagentRuntime)
await ctx.plugin(AgentRegistry)
const fiber = await ctx.plugin(spawn, { providerName: 'spawn' })
expect(ctx.subagents.list()).toEqual(['spawn'])
await fiber.dispose()
expect(ctx.subagents.list()).toEqual([])
})
it('captures structured output through the shipped plugin (driver runtime, plugin wiring)', async () => {
const { ctx, parent } = await setup([
toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 42 }),
])
const run = await start(ctx, 'spawn', {
prompt: [{ type: 'text', text: 'produce the answer' }],
parent,
outputSchema: { type: 'object', properties: { answer: { type: 'number' } }, required: ['answer'] },
})
const result = await run.result
expect(result.stopReason).toBe('completed')
expect(result.structured).toEqual({ answer: 42 })
// Run-scoped runtime: the settle released the last acquisition.
expect(ctx.tools.get(STRUCTURED_OUTPUT_TOOL)).toBeUndefined()
await run.dispose()
})
it('a backend unload does not revoke an accepted holder-owned run', async () => {
// Rebuild the stack by hand so we hold the backend's fiber.
const ctx = new Context()
const adapter = new MockAdapter(['hang'])
await mountAgentLoopTestDependencies(ctx)
await mountInvariants(ctx)
await ctx.plugin(AgentLoop, { agents: [] })
await ctx.plugin(SubagentRuntime)
const fiber = await ctx.plugin(spawn, { providerName: 'spawn' })
ctx.llm.registerAdapter(['mock'], adapter)
const parent = ctx.agentLoop.create(SessionId('parent'), { provider: 'mock', model: 'mock' })
const controller = new AbortController()
const run = await start(ctx, 'spawn', {
prompt: [{ type: 'text', text: 'q' }],
parent,
signal: controller.signal,
outputSchema: { type: 'object', properties: { a: { type: 'number' } } },
})
// Provider removal prevents new starts but the returned run belongs to its
// holder and remains live.
await new Promise(resolve => setTimeout(resolve, 30))
await fiber.dispose()
expect(ctx.subagents.getProvider('spawn')).toBeUndefined()
expect(ctx.agents.get(run.id)).toBeDefined()
controller.abort('test complete')
const result = await run.result
expect(result.stopReason).toBe('aborted')
expect(ctx.tools.get(STRUCTURED_OUTPUT_TOOL)).toBeUndefined()
await run.dispose()
})
it('a start racing an already-unloading backend cannot begin child creation', async () => {
const ctx = new Context()
await mountAgentLoopTestDependencies(ctx)
await ctx.plugin(AgentLoop, { agents: [] })
await ctx.plugin(SubagentRuntime)
const fiber = await ctx.plugin(spawn, { providerName: 'spawn' })
const parent = ctx.agentLoop.create(SessionId('parent'), { provider: 'mock', model: 'mock' })
const parentEffects = parent.ctx.fiber.getEffects().length
const published: string[] = []
ctx.on('session/created', () => void published.push('session/created'))
ctx.on('agent/created', () => void published.push('agent/created'))
const unloading = fiber.dispose()
await unloading
await expect(start(ctx, 'spawn', {
prompt: [{ type: 'text', text: 'must never start' }], parent,
})).rejects.toThrow(/no subagent provider/)
expect(parent.ctx.fiber.getEffects()).toHaveLength(parentEffects)
expect(published).toEqual([])
})
it('has the namespace-plugin export shape (no stray default)', () => {
expect('default' in spawn).toBe(false)
expect(spawn.name).toBe('subagent-spawn-in-process')
expect(spawn.inject).toEqual(['subagents'])
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-in-process')
expect(unwrapped.inject).toEqual(['subagents'])
expect(typeof unwrapped.apply).toBe('function')
})
describe('persona and toolFilter (the scoped child world)', () => {
it('a per-child persona shadows the deployment persona in the child request only', async () => {
const { ctx, parent, adapter } = await setup([
textResponse('parent answer'),
textResponse('child answer'),
])
parent.followup(createUserMessage({ content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } }))
await parent.whenIdle()
const run = await start(ctx, 'spawn', {
prompt: [{ type: 'text', text: 'do X' }],
parent,
persona: 'You are the tersest test runner.',
})
await run.result
const childRequest = adapter.requests.at(-1)!
expect(childRequest.system).toContain('You are the tersest test runner.')
// The parent's earlier request carried no such persona.
expect(adapter.requests[0]!.system ?? '').not.toContain('tersest test runner')
await run.dispose()
})
it('toolFilter hides denied tools from the child prompt AND refuses their execution', async () => {
const { ctx, parent, adapter } = await setup([
// The child tries the denied tool anyway, then answers.
toolCallResponse('c1', 'forbidden_tool', {}),
textResponse('done'),
])
ctx.tools.register(defineContentToolFixture({
name: 'forbidden_tool', description: 'global', parameters: {},
execute: () => Promise.resolve([{ type: 'text', text: 'ran' }]),
}))
const run = await start(ctx, 'spawn', {
prompt: [{ type: 'text', text: 'do X' }],
parent,
toolFilter: { deny: ['forbidden_tool'] },
})
const result = await run.result
expect(result.stopReason).toBe('completed')
// Not advertised…
const childRequest = adapter.requests[0]!
expect((childRequest.tools ?? []).map(t => t.name)).not.toContain('forbidden_tool')
// …and the attempted call executed as UNKNOWN_TOOL (visible in the log).
const child = ctx.agents.get(run.id)!
const toolResult = child.session.events.find(e => e.type === 'tool/result')!
expect(JSON.stringify(toolResult.data)).toContain('unknown tool')
await run.dispose()
})
it('an unknown toolFilter name fails the spawn loudly with no orphaned child', async () => {
const { ctx, parent } = await setup([])
const before = ctx.agents.list().length
await expect(start(ctx, 'spawn', {
prompt: [{ type: 'text', text: 'do X' }],
parent,
toolFilter: { deny: ['no_such_tool'] },
})).rejects.toThrow(/unknown global tool "no_such_tool"/)
expect(ctx.agents.list().length).toBe(before)
})
})
it('spawning from a DISPOSING parent fails loud with no orphaned child (INACTIVE_EFFECT teaching error)', async () => {
const { ctx } = await setup([])
// A handle-owned parent we can dispose (config agents dispose with the loop fiber).
const parentHandle = await ctx.agents.create({
sessionId: SessionId('doomed-s'),
agentOptions: { provider: 'mock', model: 'mock' },
})
await parentHandle.dispose()
const before = ctx.agents.list().length
const sessionsBefore = ctx.sessions.list().length
const published: string[] = []
ctx.on('session/created', () => void published.push('session/created'))
ctx.on('agent/created', () => void published.push('agent/created'))
ctx.on('agent/session-start', () => void published.push('agent/session-start'))
await expect(start(ctx, 'spawn', {
prompt: [{ type: 'text', text: 'do X' }],
parent: parentHandle.agent,
})).rejects.toThrow(/inactive context/)
expect(ctx.agents.list().length).toBe(before)
expect(ctx.sessions.list()).toHaveLength(sessionsBefore)
expect(published).toEqual([])
})
it('parent disposal during the child setup transaction prevents every publication notification', async () => {
const { ctx } = await setup([])
const parentHandle = await ctx.agents.create({
sessionId: SessionId('setup-race-parent-session'),
agentOptions: { provider: 'mock', model: 'mock' },
})
const published: string[] = []
ctx.on('session/created', () => void published.push('session/created'))
ctx.on('agent/created', () => void published.push('agent/created'))
ctx.on('agent/session-start', () => void published.push('agent/session-start'))
let teardownStarted = false
ctx.on('internal/plugin', (fiber) => {
if (teardownStarted || fiber.name !== 'scope') return
teardownStarted = true
disposeChildLifecycle(parentHandle.agent)
})
const starting = start(ctx, 'spawn', {
prompt: [{ type: 'text', text: 'must never run' }],
parent: parentHandle.agent,
})
// The factory has entered its awaited unpublished setup transaction. The
// parent context owns that transaction, so disposal wins without an
// observer ever seeing the child.
await expect(starting).rejects.toThrow(/owner disposed during setup|inactive context/)
await parentHandle.dispose()
expect(published).toEqual([])
})
})

View File

@@ -0,0 +1,30 @@
{
"extends": "../../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "lib/types"
},
"include": [
"src"
],
"references": [
{
"path": "../../../vendor/cosmokit"
},
{
"path": "../../../vendor/cordis"
},
{
"path": "../../../vendor/schemastery"
},
{
"path": "../subagent"
},
{
"path": "../subagent-in-process-driver"
},
{
"path": "../../runtime-diagnostics/invariants"
}
]
}