tool-subagent.spec.ts 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117
  1. import { afterEach, describe, expect, it, vi } from 'vitest'
  2. import { mkdtempSync, rmSync } from 'node:fs'
  3. import { tmpdir } from 'node:os'
  4. import path from 'node:path'
  5. import { Context } from 'cordis'
  6. import Loader from '@cordisjs/plugin-loader'
  7. import { CallId } from '@deepseek-ai/dsh-llm'
  8. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  9. import ToolRegistry, { TOOL_ABORTED_BEFORE_DISPATCH } from '@deepseek-ai/dsh-tools'
  10. import { type Agent } from '@deepseek-ai/dsh-agent'
  11. import AgentRegistry from '@deepseek-ai/dsh-agent'
  12. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  13. import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit'
  14. import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl'
  15. import SubagentService from '@deepseek-ai/dsh-subagent'
  16. import type { SubagentStartRequest } from '@deepseek-ai/dsh-subagent'
  17. import LocalTaskService from '@deepseek-ai/dsh-tasks-local'
  18. import * as SubagentSpawn from '@deepseek-ai/dsh-subagent-spawn'
  19. import * as ToolTasks from '@deepseek-ai/dsh-tool-tasks'
  20. import { MockAdapter, textResponse } from '../../../core/agent-loop/tests/mock-adapter.ts'
  21. import * as mock from './scripted-provider.ts'
  22. import * as tool from '../src/index.ts'
  23. import { SessionId } from '@deepseek-ai/dsh-session'
  24. const testToolSignal = new AbortController().signal
  25. /**
  26. * Drives the REAL plugin body: mounts `dsh-tool-subagent` on a real
  27. * `ToolRegistry` + `SubagentService`, with a package-local scripted child
  28. * boundary, and invokes the registered `subagent` tool through
  29. * `ctx.tools.execute`. Everything downstream of the child boundary is the
  30. * shipping code path.
  31. */
  32. /** A minimal parent Agent passed through to the provider request. */
  33. function fakeAgent(id = 'parent-1'): Agent {
  34. return { id: SessionId(id) } as unknown as Agent
  35. }
  36. async function setup(toolConfig: tool.Config, mockConfig: Partial<mock.Config> = {}) {
  37. const ctx = new Context()
  38. await ctx.plugin(SystemPrompt)
  39. await ctx.plugin(ToolRegistry)
  40. await ctx.plugin(SubagentService)
  41. await mock.mountScriptedProvider(ctx, { name: 'mock', ...mockConfig })
  42. await ctx.plugin(tool, toolConfig)
  43. return ctx
  44. }
  45. let callCounter = 0
  46. function callSubagent(ctx: Context, args: unknown, over: { agent?: Agent | undefined; signal?: AbortSignal } = {}) {
  47. // Distinguish "no override" (use a default agent) from an explicit
  48. // `{ agent: undefined }` (test the no-agent path). Under
  49. // exactOptionalPropertyTypes the key is omitted rather than set to undefined.
  50. const agent = 'agent' in over ? over.agent : fakeAgent()
  51. return ctx.tools.execute({
  52. signal: testToolSignal,
  53. callId: CallId(`call-${++callCounter}`),
  54. name: 'subagent',
  55. arguments: args,
  56. ...agent ? { agent } : {},
  57. ...over.signal ? { signal: over.signal } : {},
  58. })
  59. }
  60. function text(result: { content: { type: string; text?: string }[] }): string {
  61. return result.content.filter(b => b.type === 'text').map(b => b.text).join('')
  62. }
  63. describe('dsh-tool-subagent', () => {
  64. it('rejects continuable background policy when the provider cannot prepare continuable children', async () => {
  65. let failure: unknown
  66. try {
  67. await setup({
  68. provider: 'mock',
  69. backgroundMode: 'continuable',
  70. })
  71. } catch (error: unknown) {
  72. failure = error
  73. }
  74. expect(String(failure)).toContain(
  75. 'provider "mock" does not support `backgroundMode: continuable`',
  76. )
  77. })
  78. it('registers a `subagent` tool that delegates to the configured provider and returns its output', async () => {
  79. const ctx = await setup({ provider: 'mock' }, { reply: 'child says hi' })
  80. const result = await callSubagent(ctx, { description: 'do a thing', prompt: 'go research X' })
  81. expect(result.isError).toBe(false)
  82. if (result.isError) throw new Error('expected subagent success')
  83. expect(result.value).toEqual({
  84. kind: 'foreground',
  85. runId: 'scripted-subagent:mock:parent-1',
  86. output: [{ type: 'text', text: 'child says hi' }],
  87. })
  88. expect(text(result)).toBe('child says hi')
  89. })
  90. it('exposes description + prompt + run_in_background to the model (no provider/type parameter)', async () => {
  91. const ctx = await setup({ provider: 'mock' })
  92. const schema = ctx.tools.schemas().find(s => s.name === 'subagent')
  93. expect(schema).toBeDefined()
  94. const props = (schema!.parameters as { properties?: Record<string, unknown> }).properties ?? {}
  95. expect(Object.keys(props).sort()).toEqual(['description', 'prompt', 'run_in_background'])
  96. expect(schema!.description).toContain('task_output')
  97. })
  98. it('omits run_in_background entirely when the instance disables it (schema and capability never disagree)', async () => {
  99. const ctx = await setup({ provider: 'mock', enableRunInBackground: false })
  100. const schema = ctx.tools.schemas().find(s => s.name === 'subagent')
  101. const props = (schema!.parameters as { properties?: Record<string, unknown> }).properties ?? {}
  102. expect(Object.keys(props).sort()).toEqual(['description', 'prompt'])
  103. expect(schema!.description).not.toContain('task_output')
  104. })
  105. it('refuses a forced run_in_background at execution time when the instance disables it', async () => {
  106. // Schema omission is advertising, not enforcement: the arg validator
  107. // allows undeclared keys, so the opt-out must also hold in execute().
  108. const ctx = await setup({ provider: 'mock', enableRunInBackground: false })
  109. const parent = { id: SessionId('sess-off'), inject: () => {}, options: {}, session: { header: { version: 0, id: 'sess-off', createdAt: 0 } } } as unknown as Agent
  110. const forced = await callSubagent(ctx, { description: 'd', prompt: 'p', run_in_background: true }, { agent: parent })
  111. expect(forced.isError).toBe(true)
  112. expect(text(forced)).toContain('run_in_background is disabled for this tool instance')
  113. // The provider was never asked to start a child.
  114. expect(ctx.subagents.getProvider('mock')).toBeDefined()
  115. const foreground = await callSubagent(ctx, { description: 'd', prompt: 'p' }, { agent: parent })
  116. expect(foreground.isError).toBe(false)
  117. })
  118. it('keeps foreground and background calls exclusive', async () => {
  119. const ctx = await setup({ provider: 'mock' })
  120. expect(ctx.tools.executionMode({
  121. signal: testToolSignal,
  122. callId: CallId('subagent-foreground'),
  123. name: 'subagent',
  124. arguments: { description: 'do work', prompt: 'Reply OK' },
  125. })).toEqual({ kind: 'exclusive' })
  126. expect(ctx.tools.executionMode({
  127. signal: testToolSignal,
  128. callId: CallId('subagent-background'),
  129. name: 'subagent',
  130. arguments: { description: 'do work', prompt: 'Reply OK', run_in_background: true },
  131. })).toEqual({ kind: 'exclusive' })
  132. })
  133. it.each([
  134. { stopReason: 'aborted' as const, fragment: 'cancelled' },
  135. { stopReason: 'error' as const, fragment: 'failed' },
  136. { stopReason: 'max-tokens' as const, fragment: 'token limit' },
  137. { stopReason: 'refusal' as const, fragment: 'declined' },
  138. ])('maps stop reason $stopReason to an isError result (not partial success)', async ({ stopReason, fragment }) => {
  139. const ctx = await setup({ provider: 'mock' }, { stopReason })
  140. const result = await callSubagent(ctx, { description: 'd', prompt: 'p' })
  141. expect(result.isError).toBe(true)
  142. expect(text(result)).toContain(fragment)
  143. })
  144. it('registers under a configurable toolName so multiple providers can coexist', async () => {
  145. // The defining multi-provider use case: two loads, two distinct tool names,
  146. // each bound to a different provider — the tool registry rejects duplicate
  147. // names, so a configurable name is what makes this work.
  148. const ctx = new Context()
  149. await ctx.plugin(SystemPrompt)
  150. await ctx.plugin(ToolRegistry)
  151. await ctx.plugin(SubagentService)
  152. await mock.mountScriptedProvider(ctx, { name: 'spawn', reply: 'from spawn' })
  153. await mock.mountScriptedProvider(ctx, { name: 'acp', reply: 'from acp' })
  154. await ctx.plugin(tool, { provider: 'spawn', toolName: 'subagent' })
  155. await ctx.plugin(tool, { provider: 'acp', toolName: 'subagent_acp' })
  156. const names = ctx.tools.schemas().map(s => s.name).filter(n => n.startsWith('subagent')).sort()
  157. expect(names).toEqual(['subagent', 'subagent_acp'])
  158. const viaSpawn = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c-spawn'), name: 'subagent', arguments: { description: 'd', prompt: 'p' }, agent: fakeAgent() })
  159. const viaAcp = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c-acp'), name: 'subagent_acp', arguments: { description: 'd', prompt: 'p' }, agent: fakeAgent() })
  160. expect(text(viaSpawn)).toBe('from spawn')
  161. expect(text(viaAcp)).toBe('from acp')
  162. })
  163. it('treats an unknown (plugin-added) stop reason as an isError result', async () => {
  164. // SubagentStopReason is merge-extensible; the tool's stopReasonError default
  165. // arm must treat an unrecognized terminal reason as a failure, not success.
  166. const ctx = new Context()
  167. await ctx.plugin(SystemPrompt)
  168. await ctx.plugin(ToolRegistry)
  169. await ctx.plugin(SubagentService)
  170. ctx.subagents.registerProvider({
  171. name: 'weird',
  172. capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  173. inheritsParentContext: false,
  174. start: async () => ({
  175. id: SessionId('weird-child'),
  176. localAgent: undefined,
  177. result: Promise.resolve({ output: [{ type: 'text', text: 'partial' }], stopReason: 'frobnicated' as never }),
  178. dispose: async () => {},
  179. }),
  180. })
  181. await ctx.plugin(tool, { provider: 'weird', maxDepth: 'provider-managed' })
  182. const result = await callSubagent(ctx, { description: 'd', prompt: 'p' })
  183. expect(result.isError).toBe(true)
  184. expect(text(result)).toContain('abnormally')
  185. })
  186. it('forwards configured agentOptions into the start request', async () => {
  187. // Cover the `config.agentOptions ? … : {}` spread: a provider that captures
  188. // the request lets us assert the agentOptions reached it.
  189. let seen: { agentOptions?: { model?: string } } | undefined
  190. const ctx = new Context()
  191. await ctx.plugin(SystemPrompt)
  192. await ctx.plugin(ToolRegistry)
  193. await ctx.plugin(SubagentService)
  194. ctx.subagents.registerProvider({
  195. name: 'capture',
  196. capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  197. inheritsParentContext: false,
  198. start: async (request) => {
  199. seen = request
  200. return {
  201. id: SessionId('capture-child'),
  202. localAgent: undefined,
  203. result: Promise.resolve({ output: [{ type: 'text', text: 'ok' }], stopReason: 'completed' as const }),
  204. dispose: async () => {},
  205. }
  206. },
  207. })
  208. await ctx.plugin(tool, { provider: 'capture', agentOptions: { model: 'child-model' }, maxDepth: 'provider-managed' })
  209. await callSubagent(ctx, { description: 'd', prompt: 'p' })
  210. expect(seen?.agentOptions).toEqual({ model: 'child-model' })
  211. })
  212. it('defaults toolName and omits agentOptions when apply() is called directly (schema bypass)', async () => {
  213. // `ctx.plugin` validates+defaults config first (toolName→'subagent', the
  214. // agentOptions object→{}), so the runtime `?? 'subagent'` fallback and the
  215. // no-agentOptions branch are only reachable via a direct apply() that
  216. // bypasses schemastery — the same pattern acp-agent uses for its defaults.
  217. let seen: { agentOptions?: unknown } | undefined
  218. const ctx = new Context()
  219. await ctx.plugin(SystemPrompt)
  220. await ctx.plugin(ToolRegistry)
  221. await ctx.plugin(SubagentService)
  222. ctx.subagents.registerProvider({
  223. name: 'bare',
  224. capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  225. inheritsParentContext: false,
  226. start: async (request) => {
  227. seen = request
  228. return {
  229. id: SessionId('bare-child'),
  230. localAgent: undefined,
  231. result: Promise.resolve({ output: [{ type: 'text', text: 'ok' }], stopReason: 'completed' as const }),
  232. dispose: async () => {},
  233. }
  234. },
  235. })
  236. // Direct apply with only `provider` — no toolName, no agentOptions.
  237. tool.apply(ctx, { provider: 'bare' })
  238. await new Promise(r => setTimeout(r, 10))
  239. expect(ctx.tools.schemas().some(s => s.name === 'subagent')).toBe(true)
  240. await callSubagent(ctx, { description: 'd', prompt: 'p' })
  241. expect(seen?.agentOptions).toBeUndefined()
  242. })
  243. it('fails loud when invoked without a calling agent', async () => {
  244. const ctx = await setup({ provider: 'mock' })
  245. const result = await callSubagent(ctx, { description: 'd', prompt: 'p' }, { agent: undefined })
  246. expect(result.isError).toBe(true)
  247. expect(text(result)).toContain('requires a calling agent')
  248. })
  249. it('registers when the provider appears LATER — no load-order requirement (Loader starts siblings concurrently)', async () => {
  250. const ctx = new Context()
  251. await ctx.plugin(SystemPrompt)
  252. await ctx.plugin(ToolRegistry)
  253. await ctx.plugin(SubagentService)
  254. // Tool first: no provider yet — the tool must be absent, not broken.
  255. // Direct apply (schema bypass): also covers the waiting-note's default
  256. // toolName fallback, which validated config pre-fills.
  257. tool.apply(ctx, { provider: 'mock' })
  258. expect(ctx.tools.schemas().some(s => s.name === 'subagent')).toBe(false)
  259. // Backend arrives (as a delayed sibling fiber would): the tool appears.
  260. await mock.mountScriptedProvider(ctx, { name: 'mock', reply: 'late but fine' })
  261. expect(ctx.tools.schemas().some(s => s.name === 'subagent')).toBe(true)
  262. const result = await callSubagent(ctx, { description: 'd', prompt: 'p' })
  263. expect(text(result)).toBe('late but fine')
  264. })
  265. it('mirrors the provider lifecycle: gone on backend dispose, re-derived wording on re-registration', async () => {
  266. const ctx = new Context()
  267. await ctx.plugin(SystemPrompt)
  268. await ctx.plugin(ToolRegistry)
  269. await ctx.plugin(SubagentService)
  270. const backend = await mock.mountScriptedProvider(ctx, { name: 'mock' }) // fresh conversation (descriptor: false)
  271. await ctx.plugin(tool, { provider: 'mock' })
  272. expect(ctx.tools.schemas().find(s => s.name === 'subagent')!.description).toContain('does not see this conversation')
  273. // Backend unloads (HMR shape): the tool must not outlive its provider.
  274. await backend.dispose()
  275. expect(ctx.tools.schemas().some(s => s.name === 'subagent')).toBe(false)
  276. // Backend reloads with a DIFFERENT conversation-history descriptor: the wording is re-derived
  277. // from the fresh provider, not served stale from the first mount.
  278. await mock.mountScriptedProvider(ctx, { name: 'mock', inheritsParentContext: true })
  279. expect(ctx.tools.schemas().find(s => s.name === 'subagent')!.description).toContain('inherits this conversation')
  280. })
  281. it('the tool PLUGIN fiber owns its lifecycle listeners: disposal unmounts, and a disposed fiber never zombie-mounts', async () => {
  282. const ctx = new Context()
  283. await ctx.plugin(SystemPrompt)
  284. await ctx.plugin(ToolRegistry)
  285. await ctx.plugin(SubagentService)
  286. // Arm 1: a mounted tool dies with its plugin fiber; the provider survives.
  287. await mock.mountScriptedProvider(ctx, { name: 'mock' })
  288. const mounted = await ctx.plugin(tool, { provider: 'mock' })
  289. expect(ctx.tools.schemas().some(s => s.name === 'subagent')).toBe(true)
  290. await mounted.dispose()
  291. expect(ctx.tools.schemas().some(s => s.name === 'subagent')).toBe(false)
  292. expect(ctx.subagents.getProvider('mock')).toBeDefined()
  293. // Arm 2: a fiber disposed while WAITING must not react to the provider
  294. // arriving later — a surviving listener would re-register a tool that no
  295. // live plugin owns (the zombie mount).
  296. const waiting = await ctx.plugin(tool, { provider: 'later', toolName: 'subagent_later' })
  297. await waiting.dispose()
  298. await mock.mountScriptedProvider(ctx, { name: 'later' })
  299. expect(ctx.tools.schemas().some(s => s.name === 'subagent_later')).toBe(false)
  300. })
  301. it('ignores lifecycle events for OTHER providers', async () => {
  302. const ctx = new Context()
  303. await ctx.plugin(SystemPrompt)
  304. await ctx.plugin(ToolRegistry)
  305. await ctx.plugin(SubagentService)
  306. await mock.mountScriptedProvider(ctx, { name: 'mock' })
  307. await ctx.plugin(tool, { provider: 'mock' })
  308. // An unrelated provider registering (added-event with another name) and
  309. // unregistering (removed-event with another name) must not touch the tool.
  310. const other = await mock.mountScriptedProvider(ctx, { name: 'other', inheritsParentContext: true })
  311. expect(ctx.tools.schemas().filter(s => s.name === 'subagent')).toHaveLength(1)
  312. expect(ctx.tools.schemas().find(s => s.name === 'subagent')!.description).toContain('does not see this conversation')
  313. await other.dispose()
  314. expect(ctx.tools.schemas().some(s => s.name === 'subagent')).toBe(true)
  315. })
  316. it('derives spawn-shaped wording from a fresh-conversation provider (default mock)', async () => {
  317. const ctx = await setup({ provider: 'mock' })
  318. const schema = ctx.tools.schemas().find(s => s.name === 'subagent')!
  319. expect(schema.description).toContain('does not see this conversation')
  320. const props = (schema.parameters as { properties: Record<string, { description: string }> }).properties
  321. expect(props['prompt']!.description).toContain('include everything it needs')
  322. })
  323. it('derives inherited-context wording from a seeded-conversation provider', async () => {
  324. const ctx = await setup({ provider: 'mock', toolName: 'subagent' }, { inheritsParentContext: true })
  325. const schema = ctx.tools.schemas().find(s => s.name === 'subagent')!
  326. expect(schema.description).toContain('inherits this conversation')
  327. expect(schema.description).not.toContain('does not see this conversation')
  328. const props = (schema.parameters as { properties: Record<string, { description: string }> }).properties
  329. expect(props['prompt']!.description).toContain('completed turns')
  330. })
  331. it('disposes the run on the success path (no leaked child)', async () => {
  332. // Spy on the provider's run.dispose via a wrapping provider registered
  333. // directly on the service, then point the tool at it.
  334. const disposed = vi.fn()
  335. const ctx = new Context()
  336. await ctx.plugin(SystemPrompt)
  337. await ctx.plugin(ToolRegistry)
  338. await ctx.plugin(SubagentService)
  339. ctx.subagents.registerProvider({
  340. name: 'spy',
  341. capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  342. inheritsParentContext: false,
  343. start: async () => ({
  344. id: SessionId('spy-child'),
  345. localAgent: undefined,
  346. result: Promise.resolve({ output: [{ type: 'text', text: 'ok' }], stopReason: 'completed' as const }),
  347. dispose: async () => void disposed(),
  348. }),
  349. })
  350. await ctx.plugin(tool, { provider: 'spy', maxDepth: 'provider-managed' })
  351. await callSubagent(ctx, { description: 'd', prompt: 'p' })
  352. expect(disposed).toHaveBeenCalledTimes(1)
  353. })
  354. it('disposes the run on the error path too', async () => {
  355. const disposed = vi.fn()
  356. const ctx = new Context()
  357. await ctx.plugin(SystemPrompt)
  358. await ctx.plugin(ToolRegistry)
  359. await ctx.plugin(SubagentService)
  360. ctx.subagents.registerProvider({
  361. name: 'spy',
  362. capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  363. inheritsParentContext: false,
  364. start: async () => ({
  365. id: SessionId('spy-child'),
  366. localAgent: undefined,
  367. result: Promise.resolve({ output: [], stopReason: 'error' as const }),
  368. dispose: async () => void disposed(),
  369. }),
  370. })
  371. await ctx.plugin(tool, { provider: 'spy', maxDepth: 'provider-managed' })
  372. const result = await callSubagent(ctx, { description: 'd', prompt: 'p' })
  373. expect(result.isError).toBe(true)
  374. expect(disposed).toHaveBeenCalledTimes(1)
  375. })
  376. it('preserves independent foreground result and disposal failures', async () => {
  377. const disposed = vi.fn()
  378. const ctx = new Context()
  379. await ctx.plugin(SystemPrompt)
  380. await ctx.plugin(ToolRegistry)
  381. await ctx.plugin(SubagentService)
  382. ctx.subagents.registerProvider({
  383. name: 'spy',
  384. capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  385. inheritsParentContext: false,
  386. start: async () => ({
  387. id: SessionId('spy-child'),
  388. localAgent: undefined,
  389. result: Promise.reject(new Error('published run failed')),
  390. dispose: async () => {
  391. disposed()
  392. throw new Error('published handle disposal failed')
  393. },
  394. }),
  395. })
  396. await ctx.plugin(tool, { provider: 'spy', maxDepth: 'provider-managed' })
  397. const result = await callSubagent(ctx, { description: 'd', prompt: 'p' })
  398. expect(result.isError).toBe(true)
  399. expect(text(result)).toContain('published run failed')
  400. expect(text(result)).toContain('published handle disposal failed')
  401. expect(disposed).toHaveBeenCalledTimes(1)
  402. })
  403. it('reports a foreground disposal failure after a completed result', async () => {
  404. const ctx = new Context()
  405. await ctx.plugin(SystemPrompt)
  406. await ctx.plugin(ToolRegistry)
  407. await ctx.plugin(SubagentService)
  408. ctx.subagents.registerProvider({
  409. name: 'spy',
  410. capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  411. inheritsParentContext: false,
  412. start: async () => ({
  413. id: SessionId('spy-child'),
  414. localAgent: undefined,
  415. result: Promise.resolve({
  416. output: [{ type: 'text', text: 'completed before disposal' }],
  417. stopReason: 'completed',
  418. }),
  419. dispose: () => Promise.reject(new Error('published handle disposal failed')),
  420. }),
  421. })
  422. await ctx.plugin(tool, { provider: 'spy', maxDepth: 'provider-managed' })
  423. const result = await callSubagent(ctx, { description: 'd', prompt: 'p' })
  424. expect(result.isError).toBe(true)
  425. expect(text(result)).toContain('published handle disposal failed')
  426. })
  427. it('passes the tool abort signal as the provider cancellation channel', async () => {
  428. const cancelled = vi.fn()
  429. const ctx = new Context()
  430. await ctx.plugin(SystemPrompt)
  431. await ctx.plugin(ToolRegistry)
  432. await ctx.plugin(SubagentService)
  433. ctx.subagents.registerProvider({
  434. name: 'spy',
  435. capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  436. inheritsParentContext: false,
  437. start: async (request) => {
  438. if (request.signal.aborted) throw new Error('start aborted')
  439. let resolveResult: (r: { output: never[]; stopReason: 'aborted' }) => void
  440. const result = new Promise<{ output: never[]; stopReason: 'aborted' }>((res) => { resolveResult = res })
  441. request.signal.addEventListener('abort', () => {
  442. cancelled()
  443. resolveResult({ output: [], stopReason: 'aborted' })
  444. }, { once: true })
  445. return {
  446. id: SessionId('spy-child'),
  447. localAgent: undefined,
  448. result,
  449. dispose: async () => {},
  450. }
  451. },
  452. })
  453. await ctx.plugin(tool, { provider: 'spy', maxDepth: 'provider-managed' })
  454. const controller = new AbortController()
  455. const pending = callSubagent(ctx, { description: 'd', prompt: 'p' }, { signal: controller.signal })
  456. // Let provider.start install its listener before aborting.
  457. await Promise.resolve()
  458. await Promise.resolve()
  459. controller.abort()
  460. const result = await pending
  461. expect(cancelled).toHaveBeenCalledTimes(1)
  462. expect(result.isError).toBe(true)
  463. })
  464. it('skips provider startup for an already-aborted signal', async () => {
  465. const sawAborted = vi.fn()
  466. const ctx = new Context()
  467. await ctx.plugin(SystemPrompt)
  468. await ctx.plugin(ToolRegistry)
  469. await ctx.plugin(SubagentService)
  470. ctx.subagents.registerProvider({
  471. name: 'spy',
  472. capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  473. inheritsParentContext: false,
  474. start: async (request) => {
  475. if (request.signal.aborted) sawAborted()
  476. throw new Error('start aborted')
  477. },
  478. })
  479. await ctx.plugin(tool, { provider: 'spy', maxDepth: 'provider-managed' })
  480. const controller = new AbortController()
  481. controller.abort() // already aborted BEFORE the tool runs
  482. const result = await callSubagent(ctx, { description: 'd', prompt: 'p' }, { signal: controller.signal })
  483. expect(sawAborted).not.toHaveBeenCalled()
  484. expect(result.isError).toBe(true)
  485. expect(result.error).toEqual({
  486. message: 'tool call aborted before dispatch',
  487. info: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH },
  488. })
  489. })
  490. it('tools depend on the service: no `subagent` tool without ctx.subagents', async () => {
  491. const ctx = new Context()
  492. await ctx.plugin(SystemPrompt)
  493. await ctx.plugin(ToolRegistry)
  494. // No SubagentService mounted. The tool injects ['tools','subagents'] so its
  495. // apply never runs; the tool is absent rather than half-registered.
  496. let booted = true
  497. try {
  498. await ctx.plugin(tool, { provider: 'mock' })
  499. await new Promise(r => setTimeout(r, 20))
  500. } catch {
  501. booted = false
  502. }
  503. // Either it never booted, or it booted but registered no tool.
  504. const present = ctx.get('tools')?.schemas().some(s => s.name === 'subagent') ?? false
  505. expect(booted && present).toBe(false)
  506. })
  507. it('has the namespace-plugin export shape (no stray default) so the Loader keeps name/inject/Config/apply', () => {
  508. // Postmortem 0001 guard: this plugin HAS `inject = ['tools','subagents']`, so
  509. // a stray `export default apply` would collapse the module via
  510. // `unwrapExports` (`exports.default ?? exports`), DROP `inject`, and crash at
  511. // load with "cannot get property … without inject". Guard the shape directly.
  512. expect('default' in tool).toBe(false)
  513. expect(tool.name).toBe('tool-subagent')
  514. expect(tool.inject).toEqual(['tools', 'subagents'])
  515. const loader = Object.create(Loader.prototype) as Loader
  516. const unwrapped = loader.unwrapExports(tool) as Record<string, unknown>
  517. expect(unwrapped).toBe(tool)
  518. expect(unwrapped.name).toBe('tool-subagent')
  519. expect(unwrapped.inject).toEqual(['tools', 'subagents'])
  520. expect(typeof unwrapped.apply).toBe('function')
  521. expect(unwrapped.Config).toBeDefined()
  522. })
  523. it('passes persona/toolFilter/maxDepth config through to the start request', async () => {
  524. let seen: { persona?: string; toolFilter?: unknown; maxDepth?: number } | undefined
  525. const ctx = new Context()
  526. await ctx.plugin(SystemPrompt)
  527. await ctx.plugin(ToolRegistry)
  528. await ctx.plugin(SubagentService)
  529. ctx.subagents.registerProvider({
  530. name: 'capture2',
  531. capabilities: { outputSchema: false, depthLimit: true, toolFilter: true, persona: true },
  532. inheritsParentContext: false,
  533. start: async (request) => {
  534. seen = request
  535. return {
  536. id: SessionId('capture2-child'),
  537. localAgent: undefined,
  538. result: Promise.resolve({ output: [{ type: 'text', text: 'ok' }], stopReason: 'completed' as const }),
  539. dispose: async () => {},
  540. }
  541. },
  542. })
  543. await ctx.plugin(tool, {
  544. provider: 'capture2',
  545. persona: 'You are the child.',
  546. toolFilter: { deny: ['subagent'] },
  547. maxDepth: 2,
  548. })
  549. await callSubagent(ctx, { description: 'd', prompt: 'p' })
  550. expect(seen?.persona).toBe('You are the child.')
  551. expect(seen?.toolFilter).toMatchObject({ deny: ['subagent'] })
  552. expect(seen?.maxDepth).toBe(2)
  553. })
  554. it.each([
  555. { label: 'a string', value: '1' as unknown as number },
  556. { label: 'NaN', value: Number.NaN },
  557. { label: 'positive infinity', value: Number.POSITIVE_INFINITY },
  558. { label: 'negative infinity', value: Number.NEGATIVE_INFINITY },
  559. { label: 'a negative integer', value: -1 },
  560. { label: 'a fractional number', value: 1.5 },
  561. { label: 'negative zero', value: -0 },
  562. { label: 'an unsafe integer', value: Number.MAX_SAFE_INTEGER + 1 },
  563. ])('rejects maxDepth=$label when the plugin loads', async ({ value }) => {
  564. await expect(setup({ provider: 'mock', maxDepth: value }))
  565. .rejects.toThrow()
  566. })
  567. it('validates maxDepth when apply() is invoked directly without Schemastery', () => {
  568. const ctx = new Context()
  569. expect(() => {
  570. tool.apply(ctx, {
  571. provider: 'unused',
  572. maxDepth: Number.NaN,
  573. })
  574. }).toThrow('subagent maxDepth must be a non-negative safe integer')
  575. })
  576. it('a partial toolFilter (deny only) does not materialize an empty allow-list (deny-all trap)', async () => {
  577. let seen: { toolFilter?: { readonly allow?: readonly string[]; readonly deny?: readonly string[] } } | undefined
  578. const ctx = new Context()
  579. await ctx.plugin(SystemPrompt)
  580. await ctx.plugin(ToolRegistry)
  581. await ctx.plugin(SubagentService)
  582. ctx.subagents.registerProvider({
  583. name: 'capture3',
  584. capabilities: { outputSchema: false, depthLimit: false, toolFilter: true, persona: false },
  585. inheritsParentContext: false,
  586. start: async (request) => {
  587. seen = request
  588. return {
  589. id: SessionId('capture3-child'),
  590. localAgent: undefined,
  591. result: Promise.resolve({ output: [{ type: 'text', text: 'ok' }], stopReason: 'completed' as const }),
  592. dispose: async () => {},
  593. }
  594. },
  595. })
  596. await ctx.plugin(tool, { provider: 'capture3', toolFilter: { deny: ['subagent'] }, maxDepth: 'provider-managed' })
  597. await callSubagent(ctx, { description: 'd', prompt: 'p' })
  598. expect(seen?.toolFilter).toEqual({ deny: ['subagent'] })
  599. expect(seen?.toolFilter).not.toHaveProperty('allow')
  600. })
  601. it('an omitted agentOptions does not materialize an empty object onto the request', async () => {
  602. // Same schemastery trap as toolFilter, adjacent field: an omitted
  603. // `agentOptions` config key materializes `{}` without the forced default,
  604. // which reads as present and puts a dishonest `agentOptions: {}` on every
  605. // start request.
  606. let seen: { agentOptions?: unknown } | undefined
  607. const ctx = new Context()
  608. await ctx.plugin(SystemPrompt)
  609. await ctx.plugin(ToolRegistry)
  610. await ctx.plugin(SubagentService)
  611. ctx.subagents.registerProvider({
  612. name: 'capture4',
  613. capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  614. inheritsParentContext: false,
  615. start: async (request) => {
  616. seen = request
  617. return {
  618. id: SessionId('capture4-child'),
  619. localAgent: undefined,
  620. result: Promise.resolve({ output: [{ type: 'text', text: 'ok' }], stopReason: 'completed' as const }),
  621. dispose: async () => {},
  622. }
  623. },
  624. })
  625. await ctx.plugin(tool, { provider: 'capture4', maxDepth: 'provider-managed' })
  626. await callSubagent(ctx, { description: 'd', prompt: 'p' })
  627. expect(seen).toBeDefined()
  628. expect(seen).not.toHaveProperty('agentOptions')
  629. })
  630. it('an explicit empty toolFilter fails at plugin load, not at first delegation', async () => {
  631. const ctx = new Context()
  632. await ctx.plugin(SystemPrompt)
  633. await ctx.plugin(ToolRegistry)
  634. await ctx.plugin(SubagentService)
  635. ctx.subagents.registerProvider({
  636. name: 'p',
  637. capabilities: { outputSchema: false, depthLimit: false, toolFilter: true, persona: false },
  638. inheritsParentContext: false,
  639. start: () => { throw new Error('unreachable') },
  640. })
  641. const fiber = ctx.plugin(tool, { provider: 'p', toolFilter: {} })
  642. await expect(fiber).rejects.toThrow(/names neither `allow` nor `deny`/)
  643. })
  644. })
  645. describe('dsh-tool-subagent background mode', () => {
  646. /** A live parent with a dedicated scope fiber for structural task cleanup. */
  647. function ownerAgent(ctx: Context, sessionId: string, inject: (...args: unknown[]) => void = () => {}): Agent {
  648. const scopeFiber = ctx.plugin(() => {})
  649. const id = SessionId(sessionId)
  650. const agent = {
  651. id,
  652. ctx: scopeFiber.ctx,
  653. inject,
  654. options: {},
  655. session: { id, header: { version: 0, id, createdAt: 0 } },
  656. } as unknown as Agent
  657. ctx.agents.register(agent)
  658. return agent
  659. }
  660. async function backgroundSetup(toolConfig: tool.Config, mockConfig: Partial<mock.Config> = {}) {
  661. const ctx = await setup(toolConfig, mockConfig)
  662. await ctx.plugin(AgentRegistry)
  663. await ctx.plugin(LocalTaskService)
  664. await ctx.plugin(ToolTasks, {})
  665. return ctx
  666. }
  667. it('keeps a continuable-capable provider one-shot when backgroundMode selects one-shot', async () => {
  668. const ctx = await backgroundSetup({ provider: 'mock' })
  669. const parent = ownerAgent(ctx, 'sess-parent')
  670. let prepareCalls = 0
  671. ctx.subagents.registerProvider({
  672. name: 'resumable',
  673. capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  674. inheritsParentContext: false,
  675. start: async request => ({
  676. id: SessionId('one-shot-child'),
  677. localAgent: undefined,
  678. result: Promise.resolve({
  679. output: [{ type: 'text', text: 'one-shot answer' }],
  680. stopReason: request.signal.aborted ? 'aborted' : 'completed',
  681. }),
  682. dispose: () => Promise.resolve(),
  683. }),
  684. prepareContinuable: async () => {
  685. prepareCalls += 1
  686. throw new Error('one-shot policy must not prepare a continuable child')
  687. },
  688. })
  689. tool.apply(ctx, {
  690. provider: 'resumable',
  691. toolName: 'subagent_resumable',
  692. backgroundMode: 'one-shot',
  693. maxDepth: 'provider-managed',
  694. })
  695. const started = await ctx.tools.execute({
  696. signal: testToolSignal,
  697. callId: CallId('resumable-one-shot'),
  698. name: 'subagent_resumable',
  699. arguments: { description: 'work', prompt: 'go', run_in_background: true },
  700. agent: parent,
  701. })
  702. expect(text(started)).toBe('started background subagent task subagent-1')
  703. expect(prepareCalls).toBe(0)
  704. })
  705. it('returns a task id immediately and the answer is collected through task_output', async () => {
  706. const ctx = await backgroundSetup({ provider: 'mock', agentOptions: { model: 'child-model' } }, { reply: 'background answer' })
  707. const parent = ownerAgent(ctx, 'sess-parent')
  708. const start = await callSubagent(ctx, { description: 'deep research', prompt: 'dig in', run_in_background: true }, { agent: parent })
  709. expect(start.isError).toBe(false)
  710. if (start.isError) throw new Error('expected background subagent success')
  711. expect(start.value).toEqual({ kind: 'background', taskId: 'subagent-1' })
  712. expect(text(start)).toBe('started background subagent task subagent-1')
  713. const collected = await ctx.tools.execute({
  714. signal: testToolSignal,
  715. callId: CallId('collect-1'),
  716. name: 'task_output',
  717. arguments: { task_id: 'subagent-1', wait: true },
  718. agent: parent,
  719. })
  720. expect(text(collected)).toBe('background answer\n[status: completed]')
  721. // Final-output reads are idempotent (not consumed).
  722. const again = await ctx.tools.execute({
  723. signal: testToolSignal,
  724. callId: CallId('collect-2'),
  725. name: 'task_output',
  726. arguments: { task_id: 'subagent-1' },
  727. agent: parent,
  728. })
  729. expect(text(again)).toBe('background answer\n[status: completed]')
  730. })
  731. it('fails loud when the tasks runtime is not loaded', async () => {
  732. const ctx = await setup({ provider: 'mock' })
  733. const result = await callSubagent(ctx, { description: 'd', prompt: 'p', run_in_background: true })
  734. expect(result.isError).toBe(true)
  735. expect(text(result)).toContain('background tasks unavailable: load @deepseek-ai/dsh-tasks')
  736. })
  737. it('skips background startup when the tool signal is already aborted', async () => {
  738. const ctx = await backgroundSetup({ provider: 'mock' })
  739. const parent = ownerAgent(ctx, 'sess-parent')
  740. const controller = new AbortController()
  741. controller.abort()
  742. const result = await callSubagent(ctx, { description: 'd', prompt: 'p', run_in_background: true }, { agent: parent, signal: controller.signal })
  743. expect(result.isError).toBe(true)
  744. expect(result.error).toEqual({
  745. message: 'tool call aborted before dispatch',
  746. info: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH },
  747. })
  748. expect(text(result)).toBe('Error: tool call aborted before dispatch')
  749. })
  750. it('settles an asynchronous provider-start failure as a failed task', async () => {
  751. const ctx = await backgroundSetup({ provider: 'mock' })
  752. const parent = ownerAgent(ctx, 'sess-parent')
  753. ctx.subagents.registerProvider({
  754. name: 'broken-start',
  755. capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  756. inheritsParentContext: false,
  757. start: async () => { throw new Error('setup failed') },
  758. })
  759. tool.apply(ctx, { provider: 'broken-start', toolName: 'subagent_broken' })
  760. const started = await ctx.tools.execute({
  761. signal: testToolSignal,
  762. callId: CallId('broken-start'),
  763. name: 'subagent_broken',
  764. arguments: { description: 'broken', prompt: 'p', run_in_background: true },
  765. agent: parent,
  766. })
  767. expect(text(started)).toBe('started background subagent task subagent-1')
  768. const output = await ctx.tools.execute({
  769. signal: testToolSignal,
  770. callId: CallId('broken-output'),
  771. name: 'task_output',
  772. arguments: { task_id: 'subagent-1', wait: true },
  773. agent: parent,
  774. })
  775. expect(text(output)).toContain('[status: failed, Error: setup failed]')
  776. })
  777. it('kills a subagent task while provider readiness is still pending', async () => {
  778. const ctx = await backgroundSetup({ provider: 'mock' })
  779. const parent = ownerAgent(ctx, 'sess-parent')
  780. ctx.subagents.registerProvider({
  781. name: 'pending-start',
  782. capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  783. inheritsParentContext: false,
  784. start: request => new Promise((_resolve, reject) => {
  785. request.signal.addEventListener('abort', () => { reject(new Error('startup aborted')) }, { once: true })
  786. }),
  787. })
  788. tool.apply(ctx, { provider: 'pending-start', toolName: 'subagent_pending' })
  789. await ctx.tools.execute({
  790. signal: testToolSignal,
  791. callId: CallId('pending-start'),
  792. name: 'subagent_pending',
  793. arguments: { description: 'pending', prompt: 'p', run_in_background: true },
  794. agent: parent,
  795. })
  796. await ctx.tools.execute({
  797. signal: testToolSignal,
  798. callId: CallId('pending-kill'),
  799. name: 'task_kill',
  800. arguments: { task_id: 'subagent-1', reason: 'no longer needed' },
  801. agent: parent,
  802. })
  803. const output = await ctx.tools.execute({
  804. signal: testToolSignal,
  805. callId: CallId('pending-output'),
  806. name: 'task_output',
  807. arguments: { task_id: 'subagent-1', wait: true },
  808. agent: parent,
  809. })
  810. expect(text(output)).toBe('(no new output)\n[status: killed]')
  811. })
  812. it('forwards task_kill reasons through the run signal (and defaults one when absent)', async () => {
  813. // Use a provider that remains live until its signal is aborted.
  814. const ctx = await backgroundSetup({ provider: 'mock', agentOptions: { model: 'child-model' } })
  815. const parent = ownerAgent(ctx, 'sess-parent')
  816. const cancels: (string | undefined)[] = []
  817. let starts = 0
  818. ctx.subagents.registerProvider({
  819. name: 'hanging',
  820. capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  821. inheritsParentContext: false,
  822. start: async (request) => {
  823. let settle!: (value: { output: { type: 'text'; text: string }[]; stopReason: 'aborted' }) => void
  824. const id = SessionId(`hang-${++starts}`)
  825. const result = new Promise<{ output: { type: 'text'; text: string }[]; stopReason: 'aborted' }>((res) => { settle = res })
  826. request.signal.addEventListener('abort', () => {
  827. cancels.push(typeof request.signal.reason === 'string' ? request.signal.reason : undefined)
  828. settle({ output: [], stopReason: 'aborted' })
  829. }, { once: true })
  830. return {
  831. id,
  832. localAgent: undefined,
  833. result,
  834. dispose: () => Promise.resolve(),
  835. }
  836. },
  837. })
  838. // Direct apply preserves omitted agentOptions instead of applying schema defaults.
  839. tool.apply(ctx, { provider: 'hanging', toolName: 'subagent_hang' })
  840. const startOne = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('h1'), name: 'subagent_hang', arguments: { description: 'one', prompt: 'p', run_in_background: true }, agent: parent })
  841. const startTwo = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('h2'), name: 'subagent_hang', arguments: { description: 'two', prompt: 'p', run_in_background: true }, agent: parent })
  842. expect(text(startOne)).toBe('started background subagent task subagent-1')
  843. expect(text(startTwo)).toBe('started background subagent task subagent-2')
  844. const withReason = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('k1'), name: 'task_kill', arguments: { task_id: 'subagent-1', reason: 'superseded' }, agent: parent })
  845. const withoutReason = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('k2'), name: 'task_kill', arguments: { task_id: 'subagent-2' }, agent: parent })
  846. expect(text(withReason)).toBe('requested cancellation of task subagent-1')
  847. expect(text(withoutReason)).toBe('requested cancellation of task subagent-2')
  848. expect(cancels).toEqual(['superseded', 'background subagent task killed'])
  849. // The aborted children settle as killed tasks.
  850. const killed = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('w1'), name: 'task_output', arguments: { task_id: 'subagent-1', wait: true }, agent: parent })
  851. expect(text(killed)).toBe('(no new output)\n[status: killed]')
  852. })
  853. })
  854. describe('dsh-tool-subagent continuable background mode', () => {
  855. const roots: string[] = []
  856. afterEach(() => {
  857. for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
  858. })
  859. /** Boot the real continuable stack without any model-facing follow-up adapter. */
  860. async function continuableSetup() {
  861. const ctx = new Context()
  862. await mountAgentLoopTestDependencies(ctx)
  863. const root = mkdtempSync(path.join(tmpdir(), 'dsh-tool-subagent-continuable-'))
  864. roots.push(root)
  865. await ctx.plugin(JsonlSessionPersistence, { root })
  866. await ctx.plugin(AgentLoop, { agents: [] })
  867. await ctx.plugin(SubagentService)
  868. await ctx.plugin(SubagentSpawn, { providerName: 'spawn' })
  869. await ctx.plugin(LocalTaskService)
  870. await ctx.plugin(ToolTasks, {})
  871. await ctx.plugin(tool, { provider: 'spawn', backgroundMode: 'continuable' })
  872. ctx.llm.registerAdapter(['mock'], new MockAdapter([
  873. textResponse('continuable answer'),
  874. ]))
  875. const parent = ctx.agentLoop.create(SessionId('parent'), { provider: 'mock', model: 'mock' })
  876. return { ctx, parent }
  877. }
  878. it('starts a continuable child and returns only its durable id, creating no Task', async () => {
  879. const { ctx, parent } = await continuableSetup()
  880. const schema = ctx.tools.schemas().find(s => s.name === 'subagent')!
  881. // Continuable delegation has no Task, so the schema promises no collection.
  882. expect(schema.description).not.toContain('task_output')
  883. expect(schema.description).not.toContain('task_kill')
  884. expect(schema.description).toContain('send_message')
  885. const started = await callSubagent(
  886. ctx,
  887. { description: 'continuable work', prompt: 'dig in', run_in_background: true },
  888. { agent: parent },
  889. )
  890. expect(started.isError).toBe(false)
  891. const match = /^started subagent (\S+)$/.exec(text(started))
  892. expect(match).not.toBeNull()
  893. const [, childId] = match!
  894. // No Task was created for the continuable child.
  895. expect(ctx.tasks.list(parent)).toEqual([])
  896. await vi.waitFor(() => {
  897. expect(ctx.agents.get(SessionId(childId!))).toBeUndefined()
  898. }, { timeout: 5_000 })
  899. // The child id names a durable session carrying its continuation descriptor.
  900. const loaded = await ctx.sessionPersistence.load(SessionId(childId!))
  901. expect(loaded.events.some(event => event.type === 'subagent/descriptor')).toBe(true)
  902. expect(loaded.events.some(event => event.type === 'assistant/message')).toBe(true)
  903. })
  904. })
  905. describe('background preflight failure (no orphaned child, by construction)', () => {
  906. it('never starts the child when tasks.start preflight throws', async () => {
  907. // With no control surface, task preflight fails before the provider can spawn.
  908. const ctx = await setup({ provider: 'mock' })
  909. await ctx.plugin(AgentRegistry)
  910. await ctx.plugin(LocalTaskService)
  911. const scopeFiber = ctx.plugin(() => {})
  912. const id = SessionId('sess-p')
  913. const parent = {
  914. id,
  915. ctx: scopeFiber.ctx,
  916. inject: () => {},
  917. options: {},
  918. session: { id, header: { version: 0, id, createdAt: 0 } },
  919. } as unknown as Agent
  920. ctx.agents.register(parent)
  921. let starts = 0
  922. ctx.subagents.registerProvider({
  923. name: 'probe',
  924. capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  925. inheritsParentContext: false,
  926. start: async () => {
  927. starts += 1
  928. return {
  929. id: SessionId('probe-child'),
  930. localAgent: undefined,
  931. result: Promise.resolve({ output: [], stopReason: 'completed' as const }),
  932. dispose: () => Promise.resolve(),
  933. }
  934. },
  935. })
  936. tool.apply(ctx, { provider: 'probe', toolName: 'subagent_probe' })
  937. const result = await ctx.tools.execute({
  938. signal: testToolSignal,
  939. callId: CallId('probe-1'),
  940. name: 'subagent_probe',
  941. arguments: { description: 'd', prompt: 'p', run_in_background: true },
  942. agent: parent,
  943. })
  944. expect(result.isError).toBe(true)
  945. expect(text(result)).toContain('no control surface is attached')
  946. // Declare-then-execute: the failed preflight means no child ever existed.
  947. expect(starts).toBe(0)
  948. })
  949. })
  950. describe('depth budget configuration', () => {
  951. /** Mount the tool over a request-capturing provider with full capabilities. */
  952. async function captureSetup(config: Omit<tool.Config, 'provider'> = {}) {
  953. const requests: SubagentStartRequest[] = []
  954. const ctx = new Context()
  955. await ctx.plugin(SystemPrompt)
  956. await ctx.plugin(ToolRegistry)
  957. await ctx.plugin(SubagentService)
  958. ctx.subagents.registerProvider({
  959. name: 'capture',
  960. capabilities: { outputSchema: true, depthLimit: true, toolFilter: true, persona: true },
  961. inheritsParentContext: false,
  962. start: async (request) => {
  963. requests.push(request)
  964. return {
  965. id: SessionId(`capture-child-${requests.length}`),
  966. localAgent: undefined,
  967. result: Promise.resolve({ output: [{ type: 'text', text: 'ok' }], stopReason: 'completed' as const }),
  968. dispose: async () => {},
  969. }
  970. },
  971. })
  972. await ctx.plugin(tool, { provider: 'capture', ...config })
  973. return { ctx, requests }
  974. }
  975. it('defaults maxDepth to 3 and forwards it in the start request', async () => {
  976. const { ctx, requests } = await captureSetup()
  977. await callSubagent(ctx, { description: 'd', prompt: 'p' })
  978. expect(requests[0]?.label).toBe('d')
  979. expect(requests[0]?.maxDepth).toBe(3)
  980. expect(requests[0]?.toolFilter).toBeUndefined()
  981. })
  982. it('forwards an explicit tool filter unchanged instead of encoding the depth policy into it', async () => {
  983. const { ctx, requests } = await captureSetup({ toolFilter: { deny: ['dangerous'] }, maxDepth: 0 })
  984. await callSubagent(ctx, { description: 'd', prompt: 'p' })
  985. expect(requests[0]?.maxDepth).toBe(0)
  986. expect(requests[0]?.toolFilter).toEqual({ deny: ['dangerous'] })
  987. })
  988. it('rejects a numeric maxDepth on a provider without the depthLimit capability at mount', async () => {
  989. const ctx = new Context()
  990. await ctx.plugin(SystemPrompt)
  991. await ctx.plugin(ToolRegistry)
  992. await ctx.plugin(SubagentService)
  993. ctx.subagents.registerProvider({
  994. name: 'no-depth',
  995. capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  996. inheritsParentContext: false,
  997. start: async () => { throw new Error('unreachable') },
  998. })
  999. await expect(ctx.plugin(tool, { provider: 'no-depth' }))
  1000. .rejects.toThrow(/provider-managed/)
  1001. })
  1002. it("'provider-managed' omits the cap so a capability-less provider mounts and starts", async () => {
  1003. const requests: SubagentStartRequest[] = []
  1004. const ctx = new Context()
  1005. await ctx.plugin(SystemPrompt)
  1006. await ctx.plugin(ToolRegistry)
  1007. await ctx.plugin(SubagentService)
  1008. ctx.subagents.registerProvider({
  1009. name: 'external',
  1010. capabilities: { outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  1011. inheritsParentContext: false,
  1012. start: async (request) => {
  1013. requests.push(request)
  1014. return {
  1015. id: SessionId('external-child'),
  1016. localAgent: undefined,
  1017. result: Promise.resolve({ output: [{ type: 'text', text: 'ok' }], stopReason: 'completed' as const }),
  1018. dispose: async () => {},
  1019. }
  1020. },
  1021. })
  1022. await ctx.plugin(tool, { provider: 'external', maxDepth: 'provider-managed' })
  1023. await callSubagent(ctx, { description: 'd', prompt: 'p' })
  1024. expect(requests[0]?.maxDepth).toBeUndefined()
  1025. expect(requests[0]?.toolFilter).toBeUndefined()
  1026. })
  1027. })