tool-subagent.spec.ts 44 KB

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