tool-subagent.spec.ts 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471
  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 '@deepseek-ai/cordis'
  6. import Loader from '@deepseek-ai/cordis-plugin-loader'
  7. import { ToolCallId, ReasoningEffortId } from '@deepseek-ai/dsh-llm'
  8. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  9. import ToolRuntime, { TOOL_ABORTED_BEFORE_DISPATCH } from '@deepseek-ai/dsh-tools'
  10. import { assembleContextFor, 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 SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
  16. import SubagentRuntime from '@deepseek-ai/dsh-subagent'
  17. import type { SubagentStartRequest } from '@deepseek-ai/dsh-subagent'
  18. import LocalJobRegistry from '@deepseek-ai/dsh-jobs-local'
  19. import * as SubagentSpawn from '@deepseek-ai/dsh-subagent-spawn-in-process'
  20. import * as ToolJobs from '@deepseek-ai/dsh-tool-jobs'
  21. import { MockAdapter, textResponse } from '../../../core/agent-loop/tests/mock-adapter.ts'
  22. import { loadStoredSession } from '../../subagent/tests/persistence-helpers.ts'
  23. import * as mock from './scripted-provider.ts'
  24. import * as tool from '../src/index.ts'
  25. import { Session, SessionId } from '@deepseek-ai/dsh-session'
  26. import {
  27. callSubagent,
  28. disposeSetupProvider,
  29. fakeAgent,
  30. modelSelectionSetupAgent,
  31. setup,
  32. testToolSignal,
  33. text,
  34. } from './harness.ts'
  35. /** Create a package-test context with the tool's required projection seam. */
  36. async function projectedContext(): Promise<Context> {
  37. const ctx = new Context()
  38. await ctx.plugin(SessionProjectionRegistry)
  39. return ctx
  40. }
  41. /**
  42. * Drives the REAL plugin body: mounts `dsh-tool-subagent` on a real
  43. * `ToolRuntime` + `SubagentRuntime`, with a package-local scripted child
  44. * boundary, and invokes the registered `subagent` tool through
  45. * `ctx.tools.execute`. Everything downstream of the child boundary is the
  46. * shipping code path.
  47. */
  48. describe('dsh-tool-subagent', () => {
  49. it('rejects continuable background policy when the provider cannot prepare continuable children', async () => {
  50. let failure: unknown
  51. try {
  52. await setup({
  53. provider: 'mock',
  54. backgroundMode: 'continuable',
  55. })
  56. } catch (error: unknown) {
  57. failure = error
  58. }
  59. expect(String(failure)).toContain(
  60. 'provider "mock" does not support `backgroundMode: continuable`',
  61. )
  62. })
  63. it('rejects configured child agent options at mount when the provider cannot apply them', async () => {
  64. await expect(setup(
  65. { provider: 'mock', maxDepth: 'provider-managed', agentOptions: { model: 'configured-model' } },
  66. { capabilities: { agentOptions: false } },
  67. )).rejects.toThrow('does not support child agentOptions')
  68. })
  69. it('registers a `subagent` tool that delegates to the configured provider and returns its output', async () => {
  70. const ctx = await setup({ provider: 'mock' }, { reply: 'child says hi' })
  71. const result = await callSubagent(ctx, {
  72. description: 'do a thing',
  73. prompt: 'go research X',
  74. run_in_background: false,
  75. })
  76. expect(result.isError).toBe(false)
  77. if (result.isError) throw new Error('expected subagent success')
  78. expect(result.value).toEqual({
  79. kind: 'foreground',
  80. runId: 'scripted-subagent:mock:parent-1',
  81. output: [{ type: 'text', text: 'child says hi' }],
  82. })
  83. expect(text(result)).toBe('child says hi')
  84. })
  85. it('omits run_in_background entirely when the instance disables it (schema and capability never disagree)', async () => {
  86. const ctx = await setup({ provider: 'mock', enableRunInBackground: false })
  87. const schema = ctx.tools.schemas().find(s => s.name === 'subagent')
  88. const props = (schema!.parameters as { properties?: Record<string, unknown> }).properties ?? {}
  89. expect(Object.keys(props).sort()).toEqual([
  90. 'description',
  91. 'prompt',
  92. ])
  93. expect(schema!.description).not.toContain('job_output')
  94. })
  95. it('refuses a forced run_in_background at execution time when the instance disables it', async () => {
  96. // Schema omission is advertising, not enforcement: the arg validator
  97. // allows undeclared keys, so the opt-out must also hold in execute().
  98. const ctx = await setup({ provider: 'mock', enableRunInBackground: false })
  99. const parentId = SessionId('sess-off')
  100. const parent = {
  101. id: parentId,
  102. inject: () => {},
  103. options: {},
  104. session: Session.create(parentId),
  105. } as unknown as Agent
  106. const forced = await callSubagent(ctx, { description: 'd', prompt: 'p', run_in_background: true }, { agent: parent })
  107. expect(forced.isError).toBe(true)
  108. expect(text(forced)).toContain('run_in_background is disabled for this tool instance')
  109. // The provider was never asked to start a child.
  110. expect(ctx.subagents.getProvider('mock')).toBeDefined()
  111. const foreground = await callSubagent(ctx, { description: 'd', prompt: 'p' }, { agent: parent })
  112. expect(foreground.isError).toBe(false)
  113. })
  114. it('classifies foreground and background calls concurrency-safe (sibling delegations overlap)', async () => {
  115. const ctx = await setup({ provider: 'mock' })
  116. expect(ctx.tools.executionMode({
  117. signal: testToolSignal,
  118. callId: ToolCallId('subagent-foreground'),
  119. name: 'subagent',
  120. arguments: { description: 'do work', prompt: 'Reply OK' },
  121. })).toEqual({ kind: 'parallel' })
  122. expect(ctx.tools.executionMode({
  123. signal: testToolSignal,
  124. callId: ToolCallId('subagent-background'),
  125. name: 'subagent',
  126. arguments: { description: 'do work', prompt: 'Reply OK', run_in_background: true },
  127. })).toEqual({ kind: 'parallel' })
  128. })
  129. it('overlaps sibling foreground delegations dispatched concurrently', async () => {
  130. // Two children each block until both have started: hidden serialization
  131. // in the tool body, registry pipeline, or provider start path would
  132. // deadlock here instead of passing silently.
  133. const started: string[] = []
  134. let releaseBoth!: () => void
  135. const bothStarted = new Promise<void>((resolve) => { releaseBoth = resolve })
  136. const ctx = await setup({ provider: 'mock', enableRunInBackground: false }, {
  137. onStart: (request: SubagentStartRequest) => {
  138. started.push(request.label ?? '(unlabeled)')
  139. if (started.length === 2) releaseBoth()
  140. return bothStarted
  141. },
  142. })
  143. const results = await Promise.all([
  144. callSubagent(ctx, { description: 'first', prompt: 'p1' }),
  145. callSubagent(ctx, { description: 'second', prompt: 'p2' }),
  146. ])
  147. expect(started.sort()).toEqual(['first', 'second'])
  148. for (const result of results) expect(result.isError).toBe(false)
  149. })
  150. it.each([
  151. { stopReason: 'aborted' as const, fragment: 'cancelled' },
  152. { stopReason: 'error' as const, fragment: 'failed' },
  153. { stopReason: 'max-tokens' as const, fragment: 'token limit' },
  154. { stopReason: 'refusal' as const, fragment: 'declined' },
  155. ])('maps stop reason $stopReason to an isError result (not partial success)', async ({ stopReason, fragment }) => {
  156. const ctx = await setup({ provider: 'mock' }, { stopReason })
  157. const result = await callSubagent(ctx, { description: 'd', prompt: 'p' })
  158. expect(result.isError).toBe(true)
  159. expect(text(result)).toContain(fragment)
  160. // The failure is not partial success, but the child's preserved partial
  161. // answer still reaches the parent model inside the error result.
  162. expect(text(result)).toContain('scripted subagent reply')
  163. })
  164. it('renders provider diagnostics before preserved partial assistant output', async () => {
  165. const ctx = await setup({ provider: 'mock' }, {
  166. reply: 'partial assistant text',
  167. diagnostic: 'Claude Code denied a tool request',
  168. stopReason: 'error',
  169. })
  170. const result = await callSubagent(ctx, { description: 'd', prompt: 'p' })
  171. expect(result.isError).toBe(true)
  172. expect(text(result)).toBe(
  173. 'Error: subagent run failed\n'
  174. + 'Diagnostic: Claude Code denied a tool request\n'
  175. + 'Partial output before the run ended:\npartial assistant text',
  176. )
  177. })
  178. it('registers under a configurable toolName so multiple providers can coexist', async () => {
  179. // The defining multi-provider use case: two loads, two distinct tool names,
  180. // each bound to a different provider — the tool registry rejects duplicate
  181. // names, so a configurable name is what makes this work.
  182. const ctx = await projectedContext()
  183. await ctx.plugin(SystemPrompt)
  184. await ctx.plugin(ToolRuntime)
  185. await ctx.plugin(SubagentRuntime)
  186. await mock.mountScriptedProvider(ctx, { name: 'spawn', reply: 'from spawn' })
  187. await mock.mountScriptedProvider(ctx, { name: 'acp', reply: 'from acp' })
  188. await ctx.plugin(tool, { provider: 'spawn', toolName: 'subagent' })
  189. await ctx.plugin(tool, { provider: 'acp', toolName: 'subagent_acp' })
  190. const names = ctx.tools.schemas().map(s => s.name).filter(n => n.startsWith('subagent')).sort()
  191. expect(names).toEqual(['subagent', 'subagent_acp'])
  192. const viaSpawn = await ctx.tools.execute({ signal: testToolSignal, callId: ToolCallId('c-spawn'), name: 'subagent', arguments: { description: 'd', prompt: 'p' }, agent: fakeAgent() })
  193. const viaAcp = await ctx.tools.execute({ signal: testToolSignal, callId: ToolCallId('c-acp'), name: 'subagent_acp', arguments: { description: 'd', prompt: 'p' }, agent: fakeAgent() })
  194. expect(text(viaSpawn)).toBe('from spawn')
  195. expect(text(viaAcp)).toBe('from acp')
  196. })
  197. it('treats an unknown (plugin-added) stop reason as an isError result', async () => {
  198. // SubagentStopReason is merge-extensible; the tool's stopReasonError default
  199. // arm must treat an unrecognized terminal reason as a failure, not success.
  200. const ctx = await projectedContext()
  201. await ctx.plugin(SystemPrompt)
  202. await ctx.plugin(ToolRuntime)
  203. await ctx.plugin(SubagentRuntime)
  204. ctx.subagents.registerProvider({
  205. name: 'weird',
  206. capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  207. inheritsParentContext: false,
  208. start: async () => ({
  209. id: SessionId('weird-child'),
  210. localAgent: undefined,
  211. result: Promise.resolve({ output: [{ type: 'text', text: 'partial' }], stopReason: 'frobnicated' as never }),
  212. dispose: async () => {},
  213. }),
  214. })
  215. await ctx.plugin(tool, { provider: 'weird', maxDepth: 'provider-managed' })
  216. const result = await callSubagent(ctx, { description: 'd', prompt: 'p' })
  217. expect(result.isError).toBe(true)
  218. expect(text(result)).toContain('abnormally')
  219. })
  220. it('merges model overrides over provider-owned route defaults before preflight', async () => {
  221. let seen: SubagentStartRequest | undefined
  222. const ctx = await setup({
  223. provider: 'mock',
  224. withModelSelection: true,
  225. agentOptions: { reasoningEffort: ReasoningEffortId('high'), maxTokens: 321 },
  226. maxDepth: 'provider-managed',
  227. }, {
  228. agentRouteDefaults: { provider: 'alpha', model: 'child-model' },
  229. onStart: (request) => { seen = request },
  230. })
  231. ctx.llm.registerAdapter(['alpha'], new MockAdapter([], {
  232. efforts: [{ id: ReasoningEffortId('high'), name: 'High' }],
  233. }))
  234. await callSubagent(ctx, {
  235. description: 'd',
  236. prompt: 'p',
  237. provider: 'alpha',
  238. model: 'child-model',
  239. })
  240. expect(ctx.tools.schemas(modelSelectionSetupAgent(ctx)).find(schema => schema.name === 'subagent')?.description)
  241. .toContain('this provider\'s route defaults')
  242. expect(seen?.agentOptions).toEqual({
  243. provider: 'alpha',
  244. model: 'child-model',
  245. reasoningEffort: 'high',
  246. maxTokens: 321,
  247. })
  248. })
  249. it('does not inherit parent effort for a provider-owned route default', async () => {
  250. let seen: SubagentStartRequest | undefined
  251. const ctx = await setup({
  252. provider: 'mock',
  253. withModelSelection: true,
  254. parentAgentOptions: {
  255. provider: 'alpha',
  256. model: 'child-model',
  257. reasoningEffort: ReasoningEffortId('high'),
  258. },
  259. maxDepth: 'provider-managed',
  260. }, {
  261. agentRouteDefaults: { provider: 'alpha', model: 'child-model' },
  262. onStart: (request) => { seen = request },
  263. })
  264. ctx.llm.registerAdapter(['alpha'], new MockAdapter([]))
  265. const parent = modelSelectionSetupAgent(ctx)
  266. const result = await callSubagent(ctx, {
  267. description: 'd',
  268. prompt: 'p',
  269. provider: 'alpha',
  270. model: 'child-model',
  271. }, { agent: parent })
  272. if (result.isError) throw new Error(text(result))
  273. expect(result.isError).toBe(false)
  274. expect(seen?.agentOptions).toEqual({ provider: 'alpha', model: 'child-model' })
  275. })
  276. it('defaults toolName and omits agentOptions when apply() is called directly (schema bypass)', async () => {
  277. // `ctx.plugin` validates+defaults config first (toolName→'subagent', the
  278. // agentOptions object→{}), so the runtime `?? 'subagent'` fallback and the
  279. // no-agentOptions branch are only reachable via a direct apply() that
  280. // bypasses schemastery — the same pattern acp-agent uses for its defaults.
  281. let seen: { agentOptions?: unknown } | undefined
  282. const ctx = await projectedContext()
  283. await ctx.plugin(SystemPrompt)
  284. await ctx.plugin(ToolRuntime)
  285. await ctx.plugin(SubagentRuntime)
  286. ctx.subagents.registerProvider({
  287. name: 'bare',
  288. capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  289. inheritsParentContext: false,
  290. start: async (request) => {
  291. seen = request
  292. return {
  293. id: SessionId('bare-child'),
  294. localAgent: undefined,
  295. result: Promise.resolve({ output: [{ type: 'text', text: 'ok' }], stopReason: 'completed' as const }),
  296. dispose: async () => {},
  297. }
  298. },
  299. })
  300. // Direct apply with only `provider` — no toolName, no agentOptions.
  301. tool.apply(ctx, { maxDepth: 'provider-managed', provider: 'bare' })
  302. await new Promise(r => setTimeout(r, 10))
  303. expect(ctx.tools.schemas().some(s => s.name === 'subagent')).toBe(true)
  304. await callSubagent(ctx, { description: 'd', prompt: 'p' })
  305. expect(seen?.agentOptions).toBeUndefined()
  306. })
  307. it('fails loud when invoked without a calling agent', async () => {
  308. const ctx = await setup({ provider: 'mock' })
  309. const result = await callSubagent(ctx, { description: 'd', prompt: 'p' }, { agent: undefined })
  310. expect(result.isError).toBe(true)
  311. expect(text(result)).toContain('requires a calling agent')
  312. })
  313. it('registers when the provider appears LATER — no load-order requirement (Loader starts siblings concurrently)', async () => {
  314. const ctx = await projectedContext()
  315. await ctx.plugin(SystemPrompt)
  316. await ctx.plugin(ToolRuntime)
  317. await ctx.plugin(SubagentRuntime)
  318. // Tool first: no provider yet — the tool must be absent, not broken.
  319. // Direct apply (schema bypass): also covers the waiting-note's default
  320. // toolName fallback, which validated config pre-fills.
  321. tool.apply(ctx, { provider: 'mock' })
  322. expect(ctx.tools.schemas().some(s => s.name === 'subagent')).toBe(false)
  323. // Backend arrives (as a delayed sibling fiber would): the tool appears.
  324. await mock.mountScriptedProvider(ctx, { name: 'mock', reply: 'late but fine' })
  325. expect(ctx.tools.schemas().some(s => s.name === 'subagent')).toBe(true)
  326. const result = await callSubagent(ctx, { description: 'd', prompt: 'p' })
  327. expect(text(result)).toBe('late but fine')
  328. })
  329. it('keeps continuable guidance empty while its provider is absent', async () => {
  330. const ctx = await projectedContext()
  331. await ctx.plugin(SystemPrompt)
  332. await ctx.plugin(ToolRuntime)
  333. await ctx.plugin(SubagentRuntime)
  334. tool.apply(ctx, {
  335. provider: 'later-continuable',
  336. backgroundMode: 'continuable',
  337. maxDepth: 'provider-managed',
  338. })
  339. const assembly = await ctx.systemPrompt.assemble()
  340. expect(assembly.sections.find(section => section.name === 'tool:subagent')?.text).toBe('')
  341. expect(ctx.tools.schemas().some(schema => schema.name === 'subagent')).toBe(false)
  342. })
  343. it('mirrors the provider lifecycle: gone on backend dispose, re-derived wording on re-registration', async () => {
  344. const ctx = await projectedContext()
  345. await ctx.plugin(SystemPrompt)
  346. await ctx.plugin(ToolRuntime)
  347. await ctx.plugin(SubagentRuntime)
  348. const backend = await mock.mountScriptedProvider(ctx, { name: 'mock' }) // fresh conversation (descriptor: false)
  349. await ctx.plugin(tool, { provider: 'mock' })
  350. expect(ctx.tools.schemas().find(s => s.name === 'subagent')!.description).toContain('does not see this conversation')
  351. // Backend unloads (HMR shape): the tool must not outlive its provider.
  352. await backend.dispose()
  353. expect(ctx.tools.schemas().some(s => s.name === 'subagent')).toBe(false)
  354. // Backend reloads with a DIFFERENT conversation-history descriptor: the wording is re-derived
  355. // from the fresh provider, not served stale from the first mount.
  356. await mock.mountScriptedProvider(ctx, { name: 'mock', inheritsParentContext: true })
  357. expect(ctx.tools.schemas().find(s => s.name === 'subagent')!.description).toContain('inherits this conversation')
  358. })
  359. it('the tool PLUGIN fiber owns its lifecycle listeners: disposal unmounts, and a disposed fiber never zombie-mounts', async () => {
  360. const ctx = await projectedContext()
  361. await ctx.plugin(SystemPrompt)
  362. await ctx.plugin(ToolRuntime)
  363. await ctx.plugin(SubagentRuntime)
  364. // Arm 1: a mounted tool and its prompt section die with the plugin fiber;
  365. // the provider survives.
  366. ctx.subagents.registerProvider({
  367. name: 'continuable',
  368. capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  369. inheritsParentContext: false,
  370. start: async () => { throw new Error('lifecycle test does not start a child') },
  371. prepareContinuable: async () => ({}),
  372. })
  373. const mounted = await ctx.plugin(tool, {
  374. provider: 'continuable',
  375. backgroundMode: 'continuable',
  376. maxDepth: 'provider-managed',
  377. })
  378. expect(ctx.tools.schemas().some(s => s.name === 'subagent')).toBe(true)
  379. expect((await ctx.systemPrompt.assemble()).sections.some(s => s.name === 'tool:subagent')).toBe(true)
  380. await mounted.dispose()
  381. expect(ctx.tools.schemas().some(s => s.name === 'subagent')).toBe(false)
  382. expect((await ctx.systemPrompt.assemble()).sections.some(s => s.name === 'tool:subagent')).toBe(false)
  383. expect(ctx.subagents.getProvider('continuable')).toBeDefined()
  384. // Arm 2: a fiber disposed while WAITING must not react to the provider
  385. // arriving later — a surviving listener would re-register a tool that no
  386. // live plugin owns (the zombie mount).
  387. const waiting = await ctx.plugin(tool, { provider: 'later', toolName: 'subagent_later' })
  388. await waiting.dispose()
  389. await mock.mountScriptedProvider(ctx, { name: 'later' })
  390. expect(ctx.tools.schemas().some(s => s.name === 'subagent_later')).toBe(false)
  391. })
  392. it('ignores lifecycle events for OTHER providers', async () => {
  393. const ctx = await projectedContext()
  394. await ctx.plugin(SystemPrompt)
  395. await ctx.plugin(ToolRuntime)
  396. await ctx.plugin(SubagentRuntime)
  397. await mock.mountScriptedProvider(ctx, { name: 'mock' })
  398. await ctx.plugin(tool, { provider: 'mock' })
  399. // An unrelated provider registering (added-event with another name) and
  400. // unregistering (removed-event with another name) must not touch the tool.
  401. const other = await mock.mountScriptedProvider(ctx, { name: 'other', inheritsParentContext: true })
  402. expect(ctx.tools.schemas().filter(s => s.name === 'subagent')).toHaveLength(1)
  403. expect(ctx.tools.schemas().find(s => s.name === 'subagent')!.description).toContain('does not see this conversation')
  404. await other.dispose()
  405. expect(ctx.tools.schemas().some(s => s.name === 'subagent')).toBe(true)
  406. })
  407. it('derives spawn-shaped wording from a fresh-conversation provider (default mock)', async () => {
  408. const ctx = await setup({ provider: 'mock' })
  409. const schema = ctx.tools.schemas().find(s => s.name === 'subagent')!
  410. expect(schema.description).toContain('does not see this conversation')
  411. const props = (schema.parameters as { properties: Record<string, { description: string }> }).properties
  412. expect(props['prompt']!.description).toContain('include everything it needs')
  413. })
  414. it('derives inherited-context wording from a seeded-conversation provider', async () => {
  415. const ctx = await setup({
  416. provider: 'mock',
  417. toolName: 'subagent',
  418. }, { inheritsParentContext: true })
  419. const schema = ctx.tools.schemas().find(s => s.name === 'subagent')!
  420. expect(schema.description).toContain('inherits this conversation')
  421. expect(schema.description).not.toContain('does not see this conversation')
  422. expect(schema.description).not.toContain('can prevent provider-side reuse of the inherited conversation prefix')
  423. const props = (schema.parameters as { properties: Record<string, { description: string }> }).properties
  424. expect(props['prompt']!.description).toContain('completed turns')
  425. })
  426. it('disposes the run on the success path (no leaked child)', async () => {
  427. // Spy on the provider's run.dispose via a wrapping provider registered
  428. // directly on the service, then point the tool at it.
  429. const disposed = vi.fn()
  430. const ctx = await projectedContext()
  431. await ctx.plugin(SystemPrompt)
  432. await ctx.plugin(ToolRuntime)
  433. await ctx.plugin(SubagentRuntime)
  434. ctx.subagents.registerProvider({
  435. name: 'spy',
  436. capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  437. inheritsParentContext: false,
  438. start: async () => ({
  439. id: SessionId('spy-child'),
  440. localAgent: undefined,
  441. result: Promise.resolve({ output: [{ type: 'text', text: 'ok' }], stopReason: 'completed' as const }),
  442. dispose: async () => void disposed(),
  443. }),
  444. })
  445. await ctx.plugin(tool, { provider: 'spy', maxDepth: 'provider-managed' })
  446. await callSubagent(ctx, { description: 'd', prompt: 'p' })
  447. expect(disposed).toHaveBeenCalledTimes(1)
  448. })
  449. it('disposes the run on the error path too', async () => {
  450. const disposed = vi.fn()
  451. const ctx = await projectedContext()
  452. await ctx.plugin(SystemPrompt)
  453. await ctx.plugin(ToolRuntime)
  454. await ctx.plugin(SubagentRuntime)
  455. ctx.subagents.registerProvider({
  456. name: 'spy',
  457. capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  458. inheritsParentContext: false,
  459. start: async () => ({
  460. id: SessionId('spy-child'),
  461. localAgent: undefined,
  462. result: Promise.resolve({ output: [], stopReason: 'error' as const }),
  463. dispose: async () => void disposed(),
  464. }),
  465. })
  466. await ctx.plugin(tool, { provider: 'spy', maxDepth: 'provider-managed' })
  467. const result = await callSubagent(ctx, { description: 'd', prompt: 'p' })
  468. expect(result.isError).toBe(true)
  469. expect(disposed).toHaveBeenCalledTimes(1)
  470. })
  471. it('preserves independent foreground result and disposal failures', async () => {
  472. const disposed = vi.fn()
  473. const ctx = await projectedContext()
  474. await ctx.plugin(SystemPrompt)
  475. await ctx.plugin(ToolRuntime)
  476. await ctx.plugin(SubagentRuntime)
  477. ctx.subagents.registerProvider({
  478. name: 'spy',
  479. capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  480. inheritsParentContext: false,
  481. start: async () => ({
  482. id: SessionId('spy-child'),
  483. localAgent: undefined,
  484. result: Promise.reject(new Error('published run failed')),
  485. dispose: async () => {
  486. disposed()
  487. throw new Error('published handle disposal failed')
  488. },
  489. }),
  490. })
  491. await ctx.plugin(tool, { provider: 'spy', maxDepth: 'provider-managed' })
  492. const result = await callSubagent(ctx, { description: 'd', prompt: 'p' })
  493. expect(result.isError).toBe(true)
  494. expect(text(result)).toContain('published run failed')
  495. expect(text(result)).toContain('published handle disposal failed')
  496. expect(disposed).toHaveBeenCalledTimes(1)
  497. })
  498. it('reports a foreground disposal failure after a completed result', async () => {
  499. const ctx = await projectedContext()
  500. await ctx.plugin(SystemPrompt)
  501. await ctx.plugin(ToolRuntime)
  502. await ctx.plugin(SubagentRuntime)
  503. ctx.subagents.registerProvider({
  504. name: 'spy',
  505. capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  506. inheritsParentContext: false,
  507. start: async () => ({
  508. id: SessionId('spy-child'),
  509. localAgent: undefined,
  510. result: Promise.resolve({
  511. output: [{ type: 'text', text: 'completed before disposal' }],
  512. stopReason: 'completed',
  513. }),
  514. dispose: () => Promise.reject(new Error('published handle disposal failed')),
  515. }),
  516. })
  517. await ctx.plugin(tool, { provider: 'spy', maxDepth: 'provider-managed' })
  518. const result = await callSubagent(ctx, { description: 'd', prompt: 'p' })
  519. expect(result.isError).toBe(true)
  520. expect(text(result)).toContain('published handle disposal failed')
  521. })
  522. it('passes the tool abort signal as the provider cancellation channel', async () => {
  523. const cancelled = vi.fn()
  524. const ctx = await projectedContext()
  525. await ctx.plugin(SystemPrompt)
  526. await ctx.plugin(ToolRuntime)
  527. await ctx.plugin(SubagentRuntime)
  528. ctx.subagents.registerProvider({
  529. name: 'spy',
  530. capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  531. inheritsParentContext: false,
  532. start: async (request) => {
  533. if (request.signal.aborted) throw new Error('start aborted')
  534. let resolveResult: (r: { output: never[]; stopReason: 'aborted' }) => void
  535. const result = new Promise<{ output: never[]; stopReason: 'aborted' }>((res) => { resolveResult = res })
  536. request.signal.addEventListener('abort', () => {
  537. cancelled()
  538. resolveResult({ output: [], stopReason: 'aborted' })
  539. }, { once: true })
  540. return {
  541. id: SessionId('spy-child'),
  542. localAgent: undefined,
  543. result,
  544. dispose: async () => {},
  545. }
  546. },
  547. })
  548. await ctx.plugin(tool, { provider: 'spy', maxDepth: 'provider-managed' })
  549. const controller = new AbortController()
  550. const pending = callSubagent(ctx, { description: 'd', prompt: 'p' }, { signal: controller.signal })
  551. // Let provider.start install its listener before aborting.
  552. await Promise.resolve()
  553. await Promise.resolve()
  554. controller.abort()
  555. const result = await pending
  556. expect(cancelled).toHaveBeenCalledTimes(1)
  557. expect(result.isError).toBe(true)
  558. })
  559. it('skips provider startup for an already-aborted signal', async () => {
  560. const sawAborted = vi.fn()
  561. const ctx = await projectedContext()
  562. await ctx.plugin(SystemPrompt)
  563. await ctx.plugin(ToolRuntime)
  564. await ctx.plugin(SubagentRuntime)
  565. ctx.subagents.registerProvider({
  566. name: 'spy',
  567. capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  568. inheritsParentContext: false,
  569. start: async (request) => {
  570. if (request.signal.aborted) sawAborted()
  571. throw new Error('start aborted')
  572. },
  573. })
  574. await ctx.plugin(tool, { provider: 'spy', maxDepth: 'provider-managed' })
  575. const controller = new AbortController()
  576. controller.abort() // already aborted BEFORE the tool runs
  577. const result = await callSubagent(ctx, { description: 'd', prompt: 'p' }, { signal: controller.signal })
  578. expect(sawAborted).not.toHaveBeenCalled()
  579. expect(result.isError).toBe(true)
  580. expect(result.error).toEqual({
  581. message: 'tool call aborted before dispatch',
  582. info: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH },
  583. })
  584. })
  585. it('tools depend on the service: no `subagent` tool without ctx.subagents', async () => {
  586. const ctx = await projectedContext()
  587. await ctx.plugin(SystemPrompt)
  588. await ctx.plugin(ToolRuntime)
  589. // No SubagentRuntime mounted. The tool injects its required services so its
  590. // apply never runs; the tool is absent rather than half-registered.
  591. let booted = true
  592. try {
  593. await ctx.plugin(tool, { provider: 'mock' })
  594. await new Promise(r => setTimeout(r, 20))
  595. } catch {
  596. booted = false
  597. }
  598. // Either it never booted, or it booted but registered no tool.
  599. const present = ctx.get('tools')?.schemas().some(s => s.name === 'subagent') ?? false
  600. expect(booted && present).toBe(false)
  601. })
  602. it('has the namespace-plugin export shape (no stray default) so the Loader keeps name/inject/Config/apply', () => {
  603. // Postmortem 0001 guard: this plugin HAS an explicit `inject`, so
  604. // a stray `export default apply` would collapse the module via
  605. // `unwrapExports` (`exports.default ?? exports`), DROP `inject`, and crash at
  606. // load with "cannot get property … without inject". Guard the shape directly.
  607. expect('default' in tool).toBe(false)
  608. expect(tool.name).toBe('tool-subagent')
  609. expect(tool.inject).toEqual(['tools', 'subagents', 'systemPrompt', 'sessionProjections'])
  610. const loader = Object.create(Loader.prototype) as Loader
  611. const unwrapped = loader.unwrapExports(tool) as Record<string, unknown>
  612. expect(unwrapped).toBe(tool)
  613. expect(unwrapped.name).toBe('tool-subagent')
  614. expect(unwrapped.inject).toEqual(['tools', 'subagents', 'systemPrompt', 'sessionProjections'])
  615. expect(typeof unwrapped.apply).toBe('function')
  616. expect(unwrapped.Config).toBeDefined()
  617. })
  618. it('passes persona/toolFilter/maxDepth config through to the start request', async () => {
  619. let seen: { persona?: string; toolFilter?: unknown; maxDepth?: number } | undefined
  620. const ctx = await projectedContext()
  621. await ctx.plugin(SystemPrompt)
  622. await ctx.plugin(ToolRuntime)
  623. await ctx.plugin(SubagentRuntime)
  624. ctx.subagents.registerProvider({
  625. name: 'capture2',
  626. capabilities: { agentOptions: false, outputSchema: false, depthLimit: true, toolFilter: true, persona: true },
  627. inheritsParentContext: false,
  628. start: async (request) => {
  629. seen = request
  630. return {
  631. id: SessionId('capture2-child'),
  632. localAgent: undefined,
  633. result: Promise.resolve({ output: [{ type: 'text', text: 'ok' }], stopReason: 'completed' as const }),
  634. dispose: async () => {},
  635. }
  636. },
  637. })
  638. await ctx.plugin(tool, {
  639. provider: 'capture2',
  640. persona: 'You are the child.',
  641. toolFilter: { deny: ['subagent'] },
  642. maxDepth: 2,
  643. })
  644. await callSubagent(ctx, { description: 'd', prompt: 'p' })
  645. expect(seen?.persona).toBe('You are the child.')
  646. expect(seen?.toolFilter).toMatchObject({ deny: ['subagent'] })
  647. expect(seen?.maxDepth).toBe(2)
  648. })
  649. it.each([
  650. { label: 'a string', value: '1' as unknown as number },
  651. { label: 'NaN', value: Number.NaN },
  652. { label: 'positive infinity', value: Number.POSITIVE_INFINITY },
  653. { label: 'negative infinity', value: Number.NEGATIVE_INFINITY },
  654. { label: 'a negative integer', value: -1 },
  655. { label: 'a fractional number', value: 1.5 },
  656. { label: 'negative zero', value: -0 },
  657. { label: 'an unsafe integer', value: Number.MAX_SAFE_INTEGER + 1 },
  658. ])('rejects maxDepth=$label when the plugin loads', async ({ value }) => {
  659. await expect(setup({ provider: 'mock', maxDepth: value }))
  660. .rejects.toThrow()
  661. })
  662. it('validates maxDepth when apply() is invoked directly without Schemastery', async () => {
  663. const ctx = await projectedContext()
  664. expect(() => {
  665. tool.apply(ctx, {
  666. provider: 'unused',
  667. maxDepth: Number.NaN,
  668. })
  669. }).toThrow('subagent maxDepth must be a non-negative safe integer')
  670. })
  671. it('a partial toolFilter (deny only) does not materialize an empty allow-list (deny-all trap)', async () => {
  672. let seen: { toolFilter?: { readonly allow?: readonly string[]; readonly deny?: readonly string[] } } | undefined
  673. const ctx = await projectedContext()
  674. await ctx.plugin(SystemPrompt)
  675. await ctx.plugin(ToolRuntime)
  676. await ctx.plugin(SubagentRuntime)
  677. ctx.subagents.registerProvider({
  678. name: 'capture3',
  679. capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: true, persona: false },
  680. inheritsParentContext: false,
  681. start: async (request) => {
  682. seen = request
  683. return {
  684. id: SessionId('capture3-child'),
  685. localAgent: undefined,
  686. result: Promise.resolve({ output: [{ type: 'text', text: 'ok' }], stopReason: 'completed' as const }),
  687. dispose: async () => {},
  688. }
  689. },
  690. })
  691. await ctx.plugin(tool, { provider: 'capture3', toolFilter: { deny: ['subagent'] }, maxDepth: 'provider-managed' })
  692. await callSubagent(ctx, { description: 'd', prompt: 'p' })
  693. expect(seen?.toolFilter).toEqual({ deny: ['subagent'] })
  694. expect(seen?.toolFilter).not.toHaveProperty('allow')
  695. })
  696. it('an omitted agentOptions does not materialize an empty object onto the request', async () => {
  697. // Same schemastery trap as toolFilter, adjacent field: an omitted
  698. // `agentOptions` config key materializes `{}` without the forced default,
  699. // which reads as present and puts a dishonest `agentOptions: {}` on every
  700. // start request.
  701. let seen: { agentOptions?: unknown } | undefined
  702. const ctx = await projectedContext()
  703. await ctx.plugin(SystemPrompt)
  704. await ctx.plugin(ToolRuntime)
  705. await ctx.plugin(SubagentRuntime)
  706. ctx.subagents.registerProvider({
  707. name: 'capture4',
  708. capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  709. inheritsParentContext: false,
  710. start: async (request) => {
  711. seen = request
  712. return {
  713. id: SessionId('capture4-child'),
  714. localAgent: undefined,
  715. result: Promise.resolve({ output: [{ type: 'text', text: 'ok' }], stopReason: 'completed' as const }),
  716. dispose: async () => {},
  717. }
  718. },
  719. })
  720. await ctx.plugin(tool, { provider: 'capture4', maxDepth: 'provider-managed' })
  721. await callSubagent(ctx, { description: 'd', prompt: 'p' })
  722. expect(seen).toBeDefined()
  723. expect(seen).not.toHaveProperty('agentOptions')
  724. })
  725. it('an explicit empty toolFilter fails at plugin load, not at first delegation', async () => {
  726. const ctx = await projectedContext()
  727. await ctx.plugin(SystemPrompt)
  728. await ctx.plugin(ToolRuntime)
  729. await ctx.plugin(SubagentRuntime)
  730. ctx.subagents.registerProvider({
  731. name: 'p',
  732. capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: true, persona: false },
  733. inheritsParentContext: false,
  734. start: () => { throw new Error('unreachable') },
  735. })
  736. const fiber = ctx.plugin(tool, { provider: 'p', toolFilter: {} })
  737. await expect(fiber).rejects.toThrow(/names neither `allow` nor `deny`/)
  738. })
  739. })
  740. describe('dsh-tool-subagent background mode', () => {
  741. /** A live parent with a dedicated scope fiber for structural task cleanup. */
  742. async function ownerAgent(ctx: Context, sessionId: string, inject: (...args: unknown[]) => void = () => {}): Promise<Agent> {
  743. const scopeFiber = ctx.plugin(() => {})
  744. const id = SessionId(sessionId)
  745. const agent = {
  746. id,
  747. ctx: scopeFiber.ctx,
  748. inject,
  749. options: {},
  750. session: Session.create(id),
  751. } as unknown as Agent
  752. await ctx.agents.register(agent)
  753. return agent
  754. }
  755. async function backgroundSetup(toolConfig: tool.Config, mockConfig: Partial<mock.Config> = {}) {
  756. const ctx = await setup(toolConfig, mockConfig)
  757. await ctx.plugin(AgentRegistry)
  758. await ctx.plugin(LocalJobRegistry)
  759. await ctx.plugin(ToolJobs, {})
  760. return ctx
  761. }
  762. it('keeps a continuable-capable provider one-shot when backgroundMode selects one-shot', async () => {
  763. const ctx = await backgroundSetup({ provider: 'mock' })
  764. const parent = await ownerAgent(ctx, 'sess-parent')
  765. let prepareCalls = 0
  766. ctx.subagents.registerProvider({
  767. name: 'resumable',
  768. capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  769. inheritsParentContext: false,
  770. start: async request => ({
  771. id: SessionId('one-shot-child'),
  772. localAgent: undefined,
  773. result: Promise.resolve({
  774. output: [{ type: 'text', text: 'one-shot answer' }],
  775. stopReason: request.signal.aborted ? 'aborted' : 'completed',
  776. }),
  777. dispose: () => Promise.resolve(),
  778. }),
  779. prepareContinuable: async () => {
  780. prepareCalls += 1
  781. throw new Error('one-shot policy must not prepare a continuable child')
  782. },
  783. })
  784. tool.apply(ctx, {
  785. provider: 'resumable',
  786. toolName: 'subagent_resumable',
  787. backgroundMode: 'one-shot',
  788. maxDepth: 'provider-managed',
  789. })
  790. const started = await ctx.tools.execute({
  791. signal: testToolSignal,
  792. callId: ToolCallId('resumable-one-shot'),
  793. name: 'subagent_resumable',
  794. arguments: { description: 'work', prompt: 'go', run_in_background: true },
  795. agent: parent,
  796. })
  797. expect(text(started)).toBe('started background subagent job subagent-1')
  798. expect(prepareCalls).toBe(0)
  799. })
  800. it('returns a job id immediately and the answer is collected through job_output', async () => {
  801. const ctx = await backgroundSetup({ provider: 'mock' }, { reply: 'background answer' })
  802. const parent = await ownerAgent(ctx, 'sess-parent')
  803. const start = await callSubagent(ctx, { description: 'deep research', prompt: 'dig in', run_in_background: true }, { agent: parent })
  804. expect(start.isError).toBe(false)
  805. if (start.isError) throw new Error('expected background subagent success')
  806. expect(start.value).toEqual({ kind: 'background', jobId: 'subagent-1' })
  807. expect(text(start)).toBe('started background subagent job subagent-1')
  808. const collected = await ctx.tools.execute({
  809. signal: testToolSignal,
  810. callId: ToolCallId('collect-1'),
  811. name: 'job_output',
  812. arguments: { job_id: 'subagent-1', wait: true },
  813. agent: parent,
  814. })
  815. expect(text(collected)).toBe('background answer\n[status: completed]')
  816. // Final-output reads are idempotent (not consumed).
  817. const again = await ctx.tools.execute({
  818. signal: testToolSignal,
  819. callId: ToolCallId('collect-2'),
  820. name: 'job_output',
  821. arguments: { job_id: 'subagent-1' },
  822. agent: parent,
  823. })
  824. expect(text(again)).toBe('background answer\n[status: completed]')
  825. })
  826. it('preserves provider diagnostics in one-shot background failure detail', async () => {
  827. const ctx = await backgroundSetup({ provider: 'mock' }, {
  828. reply: 'not background output',
  829. diagnostic: 'Claude Code cancelled an unattended dialog',
  830. stopReason: 'error',
  831. })
  832. const parent = await ownerAgent(ctx, 'sess-parent')
  833. const started = await ctx.tools.execute({
  834. signal: testToolSignal,
  835. callId: ToolCallId('diagnostic-background-start'),
  836. name: 'subagent',
  837. arguments: { description: 'd', prompt: 'p', run_in_background: true },
  838. agent: parent,
  839. })
  840. expect(text(started)).toBe('started background subagent job subagent-1')
  841. const output = await ctx.tools.execute({
  842. signal: testToolSignal,
  843. callId: ToolCallId('diagnostic-background-output'),
  844. name: 'job_output',
  845. arguments: { job_id: 'subagent-1', wait: true },
  846. agent: parent,
  847. })
  848. expect(text(output)).toBe(
  849. '(no new output)\n'
  850. + '[status: failed, error; diagnostic: Claude Code cancelled an unattended dialog]',
  851. )
  852. })
  853. it('fails loud when the tasks runtime is not loaded', async () => {
  854. const ctx = await setup({ provider: 'mock' })
  855. const result = await callSubagent(ctx, { description: 'd', prompt: 'p', run_in_background: true })
  856. expect(result.isError).toBe(true)
  857. expect(text(result)).toContain('background jobs unavailable: load @deepseek-ai/dsh-jobs')
  858. })
  859. it('skips background startup when the tool signal is already aborted', async () => {
  860. const ctx = await backgroundSetup({ provider: 'mock' })
  861. const parent = await ownerAgent(ctx, 'sess-parent')
  862. const controller = new AbortController()
  863. controller.abort()
  864. const result = await callSubagent(ctx, { description: 'd', prompt: 'p', run_in_background: true }, { agent: parent, signal: controller.signal })
  865. expect(result.isError).toBe(true)
  866. expect(result.error).toEqual({
  867. message: 'tool call aborted before dispatch',
  868. info: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH },
  869. })
  870. expect(text(result)).toBe('Error: tool call aborted before dispatch')
  871. })
  872. it('skips background startup when cancellation wins asynchronous route preflight', async () => {
  873. const ctx = await backgroundSetup({
  874. provider: 'mock',
  875. agentOptions: { provider: 'alpha', model: 'selected-model' },
  876. })
  877. const parent = await ownerAgent(ctx, 'sess-parent')
  878. const adapter = new MockAdapter([])
  879. let releasePreflight!: () => void
  880. const preflightGate = new Promise<void>((resolve) => { releasePreflight = resolve })
  881. const resolveModel = vi.spyOn(adapter, 'resolveModel').mockImplementation(async (provider, model) => {
  882. await preflightGate
  883. return { provider, id: model, name: model }
  884. })
  885. ctx.llm.registerAdapter(['alpha'], adapter)
  886. const controller = new AbortController()
  887. const resultPromise = callSubagent(ctx, {
  888. description: 'cancelled selection',
  889. prompt: 'do it',
  890. run_in_background: true,
  891. }, { agent: parent, signal: controller.signal })
  892. await vi.waitFor(() => { expect(resolveModel).toHaveBeenCalledOnce() })
  893. controller.abort()
  894. releasePreflight()
  895. const result = await resultPromise
  896. expect(result.isError).toBe(true)
  897. expect(ctx.jobs.list(parent)).toEqual([])
  898. })
  899. it('rejects startup when the provider changes during asynchronous route preflight', async () => {
  900. const oldStart = vi.fn()
  901. const replacementStart = vi.fn(async (): Promise<never> => { throw new Error('replacement provider must not start') })
  902. const ctx = await setup({
  903. provider: 'mock',
  904. withModelSelection: true,
  905. maxDepth: 'provider-managed',
  906. }, {
  907. agentRouteDefaults: { provider: 'alpha', model: 'selected-model' },
  908. onStart: oldStart,
  909. })
  910. const adapter = new MockAdapter([])
  911. let releasePreflight!: () => void
  912. const preflightGate = new Promise<void>((resolve) => { releasePreflight = resolve })
  913. const resolveModel = vi.spyOn(adapter, 'resolveModel').mockImplementation(async (provider, model) => {
  914. await preflightGate
  915. return { provider, id: model, name: model }
  916. })
  917. ctx.llm.registerAdapter(['alpha'], adapter)
  918. const pending = callSubagent(ctx, {
  919. description: 'swapped provider',
  920. prompt: 'do it',
  921. provider: 'alpha',
  922. model: 'selected-model',
  923. })
  924. await vi.waitFor(() => { expect(resolveModel).toHaveBeenCalledOnce() })
  925. await disposeSetupProvider(ctx)
  926. ctx.subagents.registerProvider({
  927. name: 'mock',
  928. capabilities: { agentOptions: true, outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  929. inheritsParentContext: false,
  930. agentRouteDefaults: { provider: 'beta', model: 'replacement-model' },
  931. start: replacementStart,
  932. })
  933. releasePreflight()
  934. const result = await pending
  935. expect(result.isError).toBe(true)
  936. expect(text(result)).toContain('changed while resolving the child LLM route')
  937. expect(oldStart).not.toHaveBeenCalled()
  938. expect(replacementStart).not.toHaveBeenCalled()
  939. })
  940. it('settles an asynchronous provider-start failure as a failed task', async () => {
  941. const ctx = await backgroundSetup({ provider: 'mock' })
  942. const parent = await ownerAgent(ctx, 'sess-parent')
  943. ctx.subagents.registerProvider({
  944. name: 'broken-start',
  945. capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  946. inheritsParentContext: false,
  947. start: async () => { throw new Error('setup failed') },
  948. })
  949. tool.apply(ctx, { maxDepth: 'provider-managed', provider: 'broken-start', toolName: 'subagent_broken' })
  950. const started = await ctx.tools.execute({
  951. signal: testToolSignal,
  952. callId: ToolCallId('broken-start'),
  953. name: 'subagent_broken',
  954. arguments: { description: 'broken', prompt: 'p', run_in_background: true },
  955. agent: parent,
  956. })
  957. expect(text(started)).toBe('started background subagent job subagent-1')
  958. const output = await ctx.tools.execute({
  959. signal: testToolSignal,
  960. callId: ToolCallId('broken-output'),
  961. name: 'job_output',
  962. arguments: { job_id: 'subagent-1', wait: true },
  963. agent: parent,
  964. })
  965. expect(text(output)).toContain('[status: failed, Error: setup failed]')
  966. })
  967. it('kills a subagent task while provider readiness is still pending', async () => {
  968. const ctx = await backgroundSetup({ provider: 'mock' })
  969. const parent = await ownerAgent(ctx, 'sess-parent')
  970. ctx.subagents.registerProvider({
  971. name: 'pending-start',
  972. capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  973. inheritsParentContext: false,
  974. start: request => new Promise((_resolve, reject) => {
  975. request.signal.addEventListener('abort', () => { reject(new Error('startup aborted')) }, { once: true })
  976. }),
  977. })
  978. tool.apply(ctx, { maxDepth: 'provider-managed', provider: 'pending-start', toolName: 'subagent_pending' })
  979. await ctx.tools.execute({
  980. signal: testToolSignal,
  981. callId: ToolCallId('pending-start'),
  982. name: 'subagent_pending',
  983. arguments: { description: 'pending', prompt: 'p', run_in_background: true },
  984. agent: parent,
  985. })
  986. await ctx.tools.execute({
  987. signal: testToolSignal,
  988. callId: ToolCallId('pending-kill'),
  989. name: 'job_kill',
  990. arguments: { job_id: 'subagent-1', reason: 'no longer needed' },
  991. agent: parent,
  992. })
  993. const output = await ctx.tools.execute({
  994. signal: testToolSignal,
  995. callId: ToolCallId('pending-output'),
  996. name: 'job_output',
  997. arguments: { job_id: 'subagent-1', wait: true },
  998. agent: parent,
  999. })
  1000. expect(text(output)).toBe('(no new output)\n[status: killed]')
  1001. })
  1002. it('reports startup rollback failure after cancellation as a failed job', async () => {
  1003. const ctx = await backgroundSetup({ provider: 'mock' })
  1004. const parent = await ownerAgent(ctx, 'sess-parent')
  1005. ctx.subagents.registerProvider({
  1006. name: 'broken-start-rollback',
  1007. capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  1008. inheritsParentContext: false,
  1009. start: request => new Promise((_resolve, reject) => {
  1010. request.signal.addEventListener('abort', () => {
  1011. reject(new AggregateError(
  1012. [new Error('startup aborted'), new Error('cleanup failed')],
  1013. 'startup failed and cleanup also failed',
  1014. ))
  1015. }, { once: true })
  1016. }),
  1017. })
  1018. tool.apply(ctx, { maxDepth: 'provider-managed', provider: 'broken-start-rollback', toolName: 'subagent_broken_rollback' })
  1019. await ctx.tools.execute({
  1020. signal: testToolSignal,
  1021. callId: ToolCallId('broken-rollback-start'),
  1022. name: 'subagent_broken_rollback',
  1023. arguments: { description: 'broken rollback', prompt: 'p', run_in_background: true },
  1024. agent: parent,
  1025. })
  1026. await ctx.tools.execute({
  1027. signal: testToolSignal,
  1028. callId: ToolCallId('broken-rollback-kill'),
  1029. name: 'job_kill',
  1030. arguments: { job_id: 'subagent-1' },
  1031. agent: parent,
  1032. })
  1033. const output = await ctx.tools.execute({
  1034. signal: testToolSignal,
  1035. callId: ToolCallId('broken-rollback-output'),
  1036. name: 'job_output',
  1037. arguments: { job_id: 'subagent-1', wait: true },
  1038. agent: parent,
  1039. })
  1040. expect(text(output)).toContain('[status: failed, AggregateError: startup failed and cleanup also failed]')
  1041. })
  1042. it('forwards job_kill reasons through the run signal (and defaults one when absent)', async () => {
  1043. // Use a provider that remains live until its signal is aborted.
  1044. const ctx = await backgroundSetup({ provider: 'mock', agentOptions: { model: 'child-model' } })
  1045. const parent = await ownerAgent(ctx, 'sess-parent')
  1046. const cancels: (string | undefined)[] = []
  1047. let starts = 0
  1048. ctx.subagents.registerProvider({
  1049. name: 'hanging',
  1050. capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  1051. inheritsParentContext: false,
  1052. start: async (request) => {
  1053. let settle!: (value: { output: { type: 'text'; text: string }[]; stopReason: 'aborted' }) => void
  1054. const id = SessionId(`hang-${++starts}`)
  1055. const result = new Promise<{ output: { type: 'text'; text: string }[]; stopReason: 'aborted' }>((res) => { settle = res })
  1056. request.signal.addEventListener('abort', () => {
  1057. cancels.push(typeof request.signal.reason === 'string' ? request.signal.reason : undefined)
  1058. settle({ output: [], stopReason: 'aborted' })
  1059. }, { once: true })
  1060. return {
  1061. id,
  1062. localAgent: undefined,
  1063. result,
  1064. dispose: () => Promise.resolve(),
  1065. }
  1066. },
  1067. })
  1068. // Direct apply preserves omitted agentOptions instead of applying schema defaults.
  1069. tool.apply(ctx, { maxDepth: 'provider-managed', provider: 'hanging', toolName: 'subagent_hang' })
  1070. const startOne = await ctx.tools.execute({ signal: testToolSignal, callId: ToolCallId('h1'), name: 'subagent_hang', arguments: { description: 'one', prompt: 'p', run_in_background: true }, agent: parent })
  1071. const startTwo = await ctx.tools.execute({ signal: testToolSignal, callId: ToolCallId('h2'), name: 'subagent_hang', arguments: { description: 'two', prompt: 'p', run_in_background: true }, agent: parent })
  1072. expect(text(startOne)).toBe('started background subagent job subagent-1')
  1073. expect(text(startTwo)).toBe('started background subagent job subagent-2')
  1074. const withReason = await ctx.tools.execute({ signal: testToolSignal, callId: ToolCallId('k1'), name: 'job_kill', arguments: { job_id: 'subagent-1', reason: 'superseded' }, agent: parent })
  1075. const withoutReason = await ctx.tools.execute({ signal: testToolSignal, callId: ToolCallId('k2'), name: 'job_kill', arguments: { job_id: 'subagent-2' }, agent: parent })
  1076. expect(text(withReason)).toBe('requested cancellation of job subagent-1')
  1077. expect(text(withoutReason)).toBe('requested cancellation of job subagent-2')
  1078. expect(cancels).toEqual(['superseded', 'background subagent task killed'])
  1079. // The aborted children settle as killed tasks.
  1080. const killed = await ctx.tools.execute({ signal: testToolSignal, callId: ToolCallId('w1'), name: 'job_output', arguments: { job_id: 'subagent-1', wait: true }, agent: parent })
  1081. expect(text(killed)).toBe('(no new output)\n[status: killed]')
  1082. })
  1083. })
  1084. describe('dsh-tool-subagent continuable background mode', () => {
  1085. const roots: string[] = []
  1086. afterEach(() => {
  1087. for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
  1088. })
  1089. /** Boot the real continuable stack without any model-facing follow-up adapter. */
  1090. async function continuableSetup() {
  1091. const ctx = new Context()
  1092. await mountAgentLoopTestDependencies(ctx)
  1093. const root = mkdtempSync(path.join(tmpdir(), 'dsh-tool-subagent-continuable-'))
  1094. roots.push(root)
  1095. await ctx.plugin(JsonlSessionPersistence, { root })
  1096. await ctx.plugin(AgentLoop, { agents: [] })
  1097. await ctx.plugin(SubagentRuntime)
  1098. await ctx.plugin(SubagentSpawn, { providerName: 'spawn' })
  1099. await ctx.plugin(LocalJobRegistry)
  1100. await ctx.plugin(ToolJobs, {})
  1101. await ctx.plugin(tool, { provider: 'spawn', backgroundMode: 'continuable' })
  1102. ctx.llm.registerAdapter(['mock'], new MockAdapter([
  1103. textResponse('continuable answer'),
  1104. ]))
  1105. const parent = await ctx.agentLoop.create(SessionId('parent'), { provider: 'mock', model: 'mock' })
  1106. return { ctx, parent }
  1107. }
  1108. it('classifies continuable background calls concurrency-safe', async () => {
  1109. const { ctx } = await continuableSetup()
  1110. expect(ctx.tools.executionMode({
  1111. signal: testToolSignal,
  1112. callId: ToolCallId('subagent-continuable'),
  1113. name: 'subagent',
  1114. arguments: { description: 'do work', prompt: 'Reply OK' },
  1115. })).toEqual({ kind: 'parallel' })
  1116. })
  1117. it('defaults continuable delegation to background and returns only its durable id', async () => {
  1118. const { ctx, parent } = await continuableSetup()
  1119. const schema = ctx.tools.schemas().find(s => s.name === 'subagent')!
  1120. // Continuable delegation has no Task, so the schema promises no collection.
  1121. expect(schema.description).not.toContain('job_output')
  1122. expect(schema.description).not.toContain('job_kill')
  1123. expect(schema.description).toContain('send_message')
  1124. expect(schema.description).toContain('steers the child\'s nearest step while it is running')
  1125. expect(schema.description).not.toContain('send_message` starts a later turn')
  1126. expect(schema.description).toContain('runs in the background by default')
  1127. expect(schema.description).not.toContain('never poll or wait on it')
  1128. const properties = (schema.parameters as {
  1129. properties: Record<string, { description?: string }>
  1130. }).properties
  1131. expect(properties.run_in_background?.description).toContain('Defaults to true')
  1132. const assembly = await ctx.systemPrompt.assemble(assembleContextFor(parent))
  1133. const guidance = assembly.sections.find(section => section.name === 'tool:subagent')
  1134. expect(guidance?.text).toContain('Use subagent in the background by default')
  1135. expect(guidance?.text).toContain('runtime sends you a notice containing its outcome')
  1136. const started = await callSubagent(
  1137. ctx,
  1138. { description: 'continuable work', prompt: 'dig in' },
  1139. { agent: parent },
  1140. )
  1141. expect(started.isError).toBe(false)
  1142. const match = /^started subagent (\S+)$/.exec(text(started))
  1143. expect(match).not.toBeNull()
  1144. const [, childId] = match!
  1145. // No Task was created for the continuable child.
  1146. expect(ctx.jobs.list(parent)).toEqual([])
  1147. await vi.waitFor(() => {
  1148. expect(ctx.agents.get(SessionId(childId!))).toBeUndefined()
  1149. }, { timeout: 5_000 })
  1150. // The child id names a durable session carrying its continuation descriptor.
  1151. const loaded = await loadStoredSession(ctx.sessionPersistence, SessionId(childId!))
  1152. expect(loaded.events.some(event => event.type === 'subagent/descriptor')).toBe(true)
  1153. expect(loaded.events.some(event => event.type === 'assistant/message')).toBe(true)
  1154. })
  1155. it('hides continuable guidance when the current agent cannot see the tool', async () => {
  1156. const { ctx, parent } = await continuableSetup()
  1157. parent.ctx.tools.restrict({ deny: ['subagent'] })
  1158. expect(ctx.tools.get('subagent', parent)).toBeUndefined()
  1159. const assembly = await ctx.systemPrompt.assemble(assembleContextFor(parent))
  1160. expect(assembly.sections.find(section => section.name === 'tool:subagent')?.text).toBe('')
  1161. })
  1162. it('waits for a continuable provider only when run_in_background is explicitly false', async () => {
  1163. const { ctx, parent } = await continuableSetup()
  1164. const result = await callSubagent(
  1165. ctx,
  1166. { description: 'blocking work', prompt: 'dig in', run_in_background: false },
  1167. { agent: parent },
  1168. )
  1169. expect(result.isError).toBe(false)
  1170. if (result.isError) throw new Error('expected foreground subagent success')
  1171. expect(result.value).toMatchObject({ kind: 'foreground' })
  1172. expect(text(result)).toBe('continuable answer')
  1173. expect(ctx.jobs.list(parent)).toEqual([])
  1174. })
  1175. it('isolates a cancelled continuable preparation from a concurrent sibling', async () => {
  1176. const { ctx, parent } = await continuableSetup()
  1177. const bothPreparing = Promise.withResolvers<undefined>()
  1178. const releasePreparations = Promise.withResolvers<undefined>()
  1179. const cancelled = new AbortController()
  1180. let preparationCount = 0
  1181. let cancelledChildId: ReturnType<typeof SessionId> | undefined
  1182. let survivingChildId: ReturnType<typeof SessionId> | undefined
  1183. ctx.subagents.registerProvider({
  1184. name: 'gated',
  1185. capabilities: { agentOptions: false, outputSchema: true, depthLimit: true, toolFilter: true, persona: true },
  1186. inheritsParentContext: false,
  1187. start: async () => { throw new Error('continuable policy must not start a one-shot child') },
  1188. prepareContinuable: async (request) => {
  1189. preparationCount += 1
  1190. if (request.signal === cancelled.signal) cancelledChildId = request.sessionId
  1191. else survivingChildId = request.sessionId
  1192. if (preparationCount === 2) bothPreparing.resolve(undefined)
  1193. await releasePreparations.promise
  1194. return {}
  1195. },
  1196. })
  1197. tool.apply(ctx, {
  1198. provider: 'gated',
  1199. toolName: 'subagent_gated',
  1200. backgroundMode: 'continuable',
  1201. maxDepth: 3,
  1202. })
  1203. const execute = (callId: string, description: string, signal: AbortSignal) => ctx.tools.execute({
  1204. signal,
  1205. callId: ToolCallId(callId),
  1206. name: 'subagent_gated',
  1207. arguments: { description, prompt: 'work', run_in_background: true },
  1208. agent: parent,
  1209. })
  1210. const cancelledResult = execute('continuable-cancelled', 'cancelled sibling', cancelled.signal)
  1211. const survivingResult = execute('continuable-surviving', 'surviving sibling', testToolSignal)
  1212. await bothPreparing.promise
  1213. cancelled.abort()
  1214. releasePreparations.resolve(undefined)
  1215. const [failed, succeeded] = await Promise.all([cancelledResult, survivingResult])
  1216. expect(preparationCount).toBe(2)
  1217. expect(failed.isError).toBe(true)
  1218. expect(succeeded.isError).toBe(false)
  1219. expect(cancelledChildId).toBeDefined()
  1220. expect(survivingChildId).toBeDefined()
  1221. expect(ctx.agents.get(cancelledChildId!)).toBeUndefined()
  1222. await expect(loadStoredSession(ctx.sessionPersistence, cancelledChildId!)).rejects.toThrow(/not found/)
  1223. expect(succeeded.isError ? undefined : succeeded.value).toEqual({
  1224. kind: 'continuable',
  1225. subagentId: survivingChildId,
  1226. })
  1227. await vi.waitFor(() => {
  1228. expect(ctx.agents.get(survivingChildId!)).toBeUndefined()
  1229. }, { timeout: 5_000 })
  1230. const loaded = await loadStoredSession(ctx.sessionPersistence, survivingChildId!)
  1231. expect(loaded.events.some(event => event.type === 'subagent/descriptor')).toBe(true)
  1232. expect(loaded.events.some(event => event.type === 'assistant/message')).toBe(true)
  1233. })
  1234. })
  1235. describe('background preflight failure (no orphaned child, by construction)', () => {
  1236. it('never starts the child when tasks.start preflight throws', async () => {
  1237. // With no job controller, preflight fails before the provider can spawn.
  1238. const ctx = await setup({ provider: 'mock' })
  1239. await ctx.plugin(AgentRegistry)
  1240. await ctx.plugin(LocalJobRegistry)
  1241. const scopeFiber = ctx.plugin(() => {})
  1242. const id = SessionId('sess-p')
  1243. const parent = {
  1244. id,
  1245. ctx: scopeFiber.ctx,
  1246. inject: () => {},
  1247. options: {},
  1248. session: Session.create(id),
  1249. } as unknown as Agent
  1250. await ctx.agents.register(parent)
  1251. let starts = 0
  1252. ctx.subagents.registerProvider({
  1253. name: 'probe',
  1254. capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  1255. inheritsParentContext: false,
  1256. start: async () => {
  1257. starts += 1
  1258. return {
  1259. id: SessionId('probe-child'),
  1260. localAgent: undefined,
  1261. result: Promise.resolve({ output: [], stopReason: 'completed' as const }),
  1262. dispose: () => Promise.resolve(),
  1263. }
  1264. },
  1265. })
  1266. tool.apply(ctx, { maxDepth: 'provider-managed', provider: 'probe', toolName: 'subagent_probe' })
  1267. const result = await ctx.tools.execute({
  1268. signal: testToolSignal,
  1269. callId: ToolCallId('probe-1'),
  1270. name: 'subagent_probe',
  1271. arguments: { description: 'd', prompt: 'p', run_in_background: true },
  1272. agent: parent,
  1273. })
  1274. expect(result.isError).toBe(true)
  1275. expect(text(result)).toContain('no job controller serves this agent')
  1276. // Declare-then-execute: the failed preflight means no child ever existed.
  1277. expect(starts).toBe(0)
  1278. })
  1279. })
  1280. describe('depth budget configuration', () => {
  1281. /** Mount the tool over a request-capturing provider with full capabilities. */
  1282. async function captureSetup(config: Omit<tool.Config, 'provider'> = {}) {
  1283. const requests: SubagentStartRequest[] = []
  1284. const ctx = await projectedContext()
  1285. await ctx.plugin(SystemPrompt)
  1286. await ctx.plugin(ToolRuntime)
  1287. await ctx.plugin(SubagentRuntime)
  1288. ctx.subagents.registerProvider({
  1289. name: 'capture',
  1290. capabilities: { agentOptions: false, outputSchema: true, depthLimit: true, toolFilter: true, persona: true },
  1291. inheritsParentContext: false,
  1292. start: async (request) => {
  1293. requests.push(request)
  1294. return {
  1295. id: SessionId(`capture-child-${requests.length}`),
  1296. localAgent: undefined,
  1297. result: Promise.resolve({ output: [{ type: 'text', text: 'ok' }], stopReason: 'completed' as const }),
  1298. dispose: async () => {},
  1299. }
  1300. },
  1301. })
  1302. await ctx.plugin(tool, { provider: 'capture', ...config })
  1303. return { ctx, requests }
  1304. }
  1305. it('defaults maxDepth to 1 and forwards it in the start request', async () => {
  1306. const { ctx, requests } = await captureSetup()
  1307. await callSubagent(ctx, { description: 'd', prompt: 'p' })
  1308. expect(requests[0]?.label).toBe('d')
  1309. expect(requests[0]?.maxDepth).toBe(1)
  1310. expect(requests[0]?.toolFilter).toBeUndefined()
  1311. })
  1312. it('forwards an explicit tool filter unchanged instead of encoding the depth policy into it', async () => {
  1313. const { ctx, requests } = await captureSetup({ toolFilter: { deny: ['dangerous'] }, maxDepth: 0 })
  1314. await callSubagent(ctx, { description: 'd', prompt: 'p' })
  1315. expect(requests[0]?.maxDepth).toBe(0)
  1316. expect(requests[0]?.toolFilter).toEqual({ deny: ['dangerous'] })
  1317. })
  1318. it('rejects a numeric maxDepth on a provider without the depthLimit capability at mount', async () => {
  1319. const ctx = await projectedContext()
  1320. await ctx.plugin(SystemPrompt)
  1321. await ctx.plugin(ToolRuntime)
  1322. await ctx.plugin(SubagentRuntime)
  1323. ctx.subagents.registerProvider({
  1324. name: 'no-depth',
  1325. capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  1326. inheritsParentContext: false,
  1327. start: async () => { throw new Error('unreachable') },
  1328. })
  1329. await expect(ctx.plugin(tool, { provider: 'no-depth' }))
  1330. .rejects.toThrow(/provider-managed/)
  1331. })
  1332. it("'provider-managed' omits the cap so a capability-less provider mounts and starts", async () => {
  1333. const requests: SubagentStartRequest[] = []
  1334. const ctx = await projectedContext()
  1335. await ctx.plugin(SystemPrompt)
  1336. await ctx.plugin(ToolRuntime)
  1337. await ctx.plugin(SubagentRuntime)
  1338. ctx.subagents.registerProvider({
  1339. name: 'external',
  1340. capabilities: { agentOptions: false, outputSchema: false, depthLimit: false, toolFilter: false, persona: false },
  1341. inheritsParentContext: false,
  1342. start: async (request) => {
  1343. requests.push(request)
  1344. return {
  1345. id: SessionId('external-child'),
  1346. localAgent: undefined,
  1347. result: Promise.resolve({ output: [{ type: 'text', text: 'ok' }], stopReason: 'completed' as const }),
  1348. dispose: async () => {},
  1349. }
  1350. },
  1351. })
  1352. await ctx.plugin(tool, { provider: 'external', maxDepth: 'provider-managed' })
  1353. await callSubagent(ctx, { description: 'd', prompt: 'p' })
  1354. expect(requests[0]?.maxDepth).toBeUndefined()
  1355. expect(requests[0]?.toolFilter).toBeUndefined()
  1356. })
  1357. })