tool-calls.spec.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. /**
  2. * Exercises scheduler ordering and cancellation with deterministic gated tools.
  3. * ACP expected outputs own transcript-facing coverage.
  4. */
  5. import { describe, expect, it } from 'vitest'
  6. import { Context } from 'cordis'
  7. import { CallId, StreamChunk } from '@deepseek-ai/dsh-llm'
  8. import SessionStore, { SessionEvent, SessionId } from '@deepseek-ai/dsh-session'
  9. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  10. import LlmService from '@deepseek-ai/dsh-llm'
  11. import ToolRegistry, { defineContentToolFixture, TOOL_ABORTED_BEFORE_DISPATCH, type PostToolDecision, type PreToolDecision } from '@deepseek-ai/dsh-tools'
  12. import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent'
  13. import AgentLoop, { DEFAULT_MAX_PARALLEL_TOOL_CALLS } from '@deepseek-ai/dsh-agent-loop'
  14. import { MockAdapter, textResponse } from './mock-adapter.ts'
  15. async function harness(adapter: MockAdapter, maxParallelToolCalls?: number) {
  16. const ctx = new Context()
  17. await ctx.plugin(LlmService)
  18. await ctx.plugin(SessionStore)
  19. await ctx.plugin(SystemPrompt, { persona: '' })
  20. await ctx.plugin(ToolRegistry)
  21. await ctx.plugin(AgentRegistry)
  22. await ctx.plugin(AgentLoop, {
  23. agents: [],
  24. ...maxParallelToolCalls === undefined ? {} : { maxParallelToolCalls },
  25. })
  26. ctx.llm.registerAdapter(['mock'], adapter)
  27. return ctx
  28. }
  29. function waitForIdle(ctx: Context, agent: Agent): Promise<void> {
  30. return new Promise((resolve) => {
  31. const dispose = ctx.on('agent/status', (subject, status) => {
  32. if (subject === agent && status === 'idle') { dispose(); resolve() }
  33. })
  34. })
  35. }
  36. function events(agent: Agent): SessionEvent[] {
  37. return [...agent.session.events]
  38. }
  39. /** Build one assistant response containing the supplied tool calls. */
  40. function multiCall(calls: { id: string; name: string; args: object }[]): StreamChunk[] {
  41. const chunks: StreamChunk[] = []
  42. calls.forEach((call, index) => {
  43. chunks.push(
  44. { type: 'block-start', index, blockType: 'tool-call' },
  45. { type: 'block-end', index, block: { type: 'tool-call', id: CallId(call.id), name: call.name, arguments: JSON.stringify(call.args) } },
  46. )
  47. })
  48. chunks.push(
  49. { type: 'usage', usage: { inputTokens: 5, outputTokens: 5 } },
  50. { type: 'finish', reason: { kind: 'tool-calls' } },
  51. )
  52. return chunks
  53. }
  54. /** A tool whose calls block until the test releases them by callId. */
  55. function gatedTool(name: string, parallel: boolean) {
  56. const gates = new Map<string, () => void>()
  57. const started: string[] = []
  58. const tool = defineContentToolFixture({
  59. name,
  60. description: `gated ${name}`,
  61. parameters: { id: { type: 'string', required: true } },
  62. ...parallel ? { isConcurrencySafe: () => true } : {},
  63. async execute(args) {
  64. started.push(args.id)
  65. await new Promise<void>((resolve) => { gates.set(args.id, resolve) })
  66. return [{ type: 'text', text: `done-${args.id}` }]
  67. },
  68. })
  69. return {
  70. tool,
  71. started,
  72. release(id: string) { gates.get(id)?.(); gates.delete(id) },
  73. pending() { return [...gates.keys()] },
  74. }
  75. }
  76. function gatedParallelTool(name: string) {
  77. return gatedTool(name, true)
  78. }
  79. function gatedExclusiveTool(name: string) {
  80. return gatedTool(name, false)
  81. }
  82. /** Poll until `predicate` holds, letting microtasks/timers drain between checks. */
  83. async function until(predicate: () => boolean): Promise<void> {
  84. for (let i = 0; i < 1000 && !predicate(); i++) await new Promise(r => setTimeout(r, 0))
  85. if (!predicate()) throw new Error('until: condition never held')
  86. }
  87. describe('tool-call scheduler: grouping and barriers', () => {
  88. it('runs parallel-safe siblings concurrently (all start before any completes)', async () => {
  89. const adapter = new MockAdapter([
  90. multiCall([{ id: 'c1', name: 'p', args: { id: '1' } }, { id: 'c2', name: 'p', args: { id: '2' } }, { id: 'c3', name: 'p', args: { id: '3' } }]),
  91. textResponse('done'),
  92. ])
  93. const ctx = await harness(adapter)
  94. const gated = gatedParallelTool('p')
  95. ctx.tools.register(gated.tool)
  96. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  97. agent.followup({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } })
  98. await until(() => gated.started.length === 3)
  99. expect(gated.started).toEqual(['1', '2', '3'])
  100. gated.release('1'); gated.release('2'); gated.release('3')
  101. await waitForIdle(ctx, agent)
  102. })
  103. it('an exclusive call between two parallel-safe calls forms a barrier (3 groups)', async () => {
  104. const order: string[] = []
  105. const adapter = new MockAdapter([
  106. multiCall([
  107. { id: 'c1', name: 'r', args: { id: 'A1' } },
  108. { id: 'c2', name: 'w', args: { id: 'A2' } },
  109. { id: 'c3', name: 'r', args: { id: 'A3' } },
  110. ]),
  111. textResponse('done'),
  112. ])
  113. const ctx = await harness(adapter)
  114. ctx.tools.register(defineContentToolFixture({
  115. name: 'r', description: 'read', parameters: { id: { type: 'string', required: true } },
  116. isConcurrencySafe: () => true,
  117. async execute(args) { order.push(`r-start-${args.id}`); order.push(`r-end-${args.id}`); return [{ type: 'text', text: 'r' }] },
  118. }))
  119. ctx.tools.register(defineContentToolFixture({
  120. name: 'w', description: 'write', parameters: { id: { type: 'string', required: true } },
  121. async execute(args) { order.push(`w-${args.id}`); return [{ type: 'text', text: 'w' }] },
  122. }))
  123. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  124. agent.followup({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } })
  125. await waitForIdle(ctx, agent)
  126. expect(order).toEqual(['r-start-A1', 'r-end-A1', 'w-A2', 'r-start-A3', 'r-end-A3'])
  127. })
  128. it('reclassifies pending calls after an exclusive barrier replaces their tool', async () => {
  129. const adapter = new MockAdapter([
  130. multiCall([
  131. { id: 'c1', name: 'replace', args: { id: '0' } },
  132. { id: 'c2', name: 'x', args: { id: '1' } },
  133. { id: 'c3', name: 'x', args: { id: '2' } },
  134. ]),
  135. textResponse('done'),
  136. ])
  137. const ctx = await harness(adapter)
  138. const replacement = gatedExclusiveTool('x')
  139. const disposeSafe = ctx.tools.register(defineContentToolFixture({
  140. name: 'x',
  141. description: 'initially safe',
  142. parameters: { id: { type: 'string', required: true } },
  143. isConcurrencySafe: () => true,
  144. async execute(args) { return [{ type: 'text', text: `old-${args.id}` }] },
  145. }))
  146. ctx.tools.register(defineContentToolFixture({
  147. name: 'replace',
  148. description: 'replace x',
  149. parameters: { id: { type: 'string', required: true } },
  150. async execute() {
  151. disposeSafe()
  152. ctx.tools.register(replacement.tool)
  153. return [{ type: 'text', text: 'replaced' }]
  154. },
  155. }))
  156. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  157. agent.followup({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } })
  158. await until(() => replacement.started.length === 1)
  159. await new Promise(r => setTimeout(r, 5))
  160. expect(replacement.started).toEqual(['1'])
  161. replacement.release('1')
  162. await until(() => replacement.started.length === 2)
  163. expect(replacement.started).toEqual(['1', '2'])
  164. replacement.release('2')
  165. await waitForIdle(ctx, agent)
  166. })
  167. it('stops replenishing when a result observer makes the next call exclusive', async () => {
  168. const adapter = new MockAdapter([
  169. multiCall([
  170. { id: 'c1', name: 'x', args: { id: '1' } },
  171. { id: 'c2', name: 'x', args: { id: '2' } },
  172. { id: 'c3', name: 'x', args: { id: '3' } },
  173. ]),
  174. textResponse('done'),
  175. ])
  176. const ctx = await harness(adapter, 2)
  177. const initial = gatedParallelTool('x')
  178. const replacement = gatedExclusiveTool('x')
  179. const disposeInitial = ctx.tools.register(initial.tool)
  180. ctx.on('tools/result', (exec) => {
  181. if (exec.callId !== CallId('c1')) return
  182. disposeInitial()
  183. ctx.tools.register(replacement.tool)
  184. })
  185. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  186. agent.followup({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } })
  187. await until(() => initial.started.length === 2)
  188. initial.release('1')
  189. await until(() => events(agent).some(event =>
  190. event.type === 'tool/result' && event.data.callId === CallId('c1')))
  191. await new Promise(r => setTimeout(r, 5))
  192. expect(replacement.started).toEqual([])
  193. initial.release('2')
  194. await until(() => replacement.started.length === 1)
  195. expect(replacement.started).toEqual(['3'])
  196. replacement.release('3')
  197. await waitForIdle(ctx, agent)
  198. })
  199. })
  200. describe('tool-call scheduler: model-order results despite out-of-order settlement', () => {
  201. it('commits tool/result in model order even when a later call settles first', async () => {
  202. const adapter = new MockAdapter([
  203. multiCall([{ id: 'c1', name: 'p', args: { id: '1' } }, { id: 'c2', name: 'p', args: { id: '2' } }]),
  204. textResponse('done'),
  205. ])
  206. const ctx = await harness(adapter)
  207. const gated = gatedParallelTool('p')
  208. ctx.tools.register(gated.tool)
  209. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  210. agent.followup({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } })
  211. await until(() => gated.started.length === 2)
  212. gated.release('2')
  213. await new Promise(r => setTimeout(r, 5))
  214. const beforeFirst = events(agent).filter(e => e.type === 'tool/result')
  215. expect(beforeFirst).toEqual([])
  216. gated.release('1')
  217. await waitForIdle(ctx, agent)
  218. const results = events(agent).filter(e => e.type === 'tool/result')
  219. expect(results.map(e => e.data.callId)).toEqual([CallId('c1'), CallId('c2')])
  220. })
  221. it('derived history pairs calls in model order regardless of tool/call log interleaving', async () => {
  222. const adapter = new MockAdapter([
  223. multiCall([{ id: 'c1', name: 'p', args: { id: '1' } }, { id: 'c2', name: 'p', args: { id: '2' } }]),
  224. textResponse('done'),
  225. ])
  226. const ctx = await harness(adapter)
  227. const gated = gatedParallelTool('p')
  228. ctx.tools.register(gated.tool)
  229. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  230. agent.followup({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } })
  231. await until(() => gated.started.length === 2)
  232. gated.release('2'); gated.release('1')
  233. await waitForIdle(ctx, agent)
  234. const messages = agent.session.deriveMessages()
  235. const toolResults = messages.flatMap(m => m.content.filter(b => b.type === 'tool-result'))
  236. expect(toolResults.map(b => b.toolCallId)).toEqual([CallId('c1'), CallId('c2')])
  237. })
  238. })
  239. describe('tool-call scheduler: rolling pool honors maxParallelToolCalls', () => {
  240. it('rejects invalid global maxParallelToolCalls config at plugin load', async () => {
  241. await expect(harness(new MockAdapter([]), 0)).rejects.toThrow()
  242. await expect(harness(new MockAdapter([]), 1.5)).rejects.toThrow()
  243. })
  244. it('defensively rejects invalid caps when direct construction bypasses the config schema', () => {
  245. expect(() => new AgentLoop(new Context(), { agents: [], maxParallelToolCalls: 0 }))
  246. .toThrow('maxParallelToolCalls must be a positive integer')
  247. expect(() => new AgentLoop(new Context(), { agents: [], maxParallelToolCalls: 1.5 }))
  248. .toThrow('maxParallelToolCalls must be a positive integer')
  249. })
  250. it('defaults the cap when direct construction bypasses the config schema', async () => {
  251. const ctx = new Context()
  252. await ctx.plugin(LlmService)
  253. await ctx.plugin(SessionStore)
  254. await ctx.plugin(SystemPrompt, { persona: '' })
  255. await ctx.plugin(ToolRegistry)
  256. await ctx.plugin(AgentRegistry)
  257. const loop = new AgentLoop(ctx, { agents: [] })
  258. expect(loop.config.maxParallelToolCalls).toBe(DEFAULT_MAX_PARALLEL_TOOL_CALLS)
  259. await ctx.fiber.dispose()
  260. })
  261. it('starts at most the cap, replenishing as calls settle', async () => {
  262. const adapter = new MockAdapter([
  263. multiCall([1, 2, 3, 4].map(n => ({ id: `c${n}`, name: 'p', args: { id: String(n) } }))),
  264. textResponse('done'),
  265. ])
  266. const ctx = await harness(adapter, 2)
  267. const gated = gatedParallelTool('p')
  268. ctx.tools.register(gated.tool)
  269. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  270. agent.followup({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } })
  271. await until(() => gated.started.length === 2)
  272. await new Promise(r => setTimeout(r, 5))
  273. expect(gated.started).toEqual(['1', '2'])
  274. gated.release('1')
  275. await until(() => gated.started.length === 3)
  276. expect(gated.started).toEqual(['1', '2', '3'])
  277. expect(events(agent)
  278. .filter(e => e.type === 'tool/call' || e.type === 'tool/result')
  279. .map(e => `${e.type}:${String(e.data.callId)}`)
  280. .slice(0, 4))
  281. .toEqual(['tool/call:c1', 'tool/call:c2', 'tool/result:c1', 'tool/call:c3'])
  282. gated.release('2'); gated.release('3')
  283. await until(() => gated.started.length === 4)
  284. gated.release('4')
  285. await waitForIdle(ctx, agent)
  286. expect(events(agent).filter(e => e.type === 'tool/result').map(e => e.data.callId))
  287. .toEqual([CallId('c1'), CallId('c2'), CallId('c3'), CallId('c4')])
  288. })
  289. it('maxParallelToolCalls: 1 is fully serial (no second start before the first settles)', async () => {
  290. const adapter = new MockAdapter([
  291. multiCall([{ id: 'c1', name: 'p', args: { id: '1' } }, { id: 'c2', name: 'p', args: { id: '2' } }]),
  292. textResponse('done'),
  293. ])
  294. const ctx = await harness(adapter, 1)
  295. const gated = gatedParallelTool('p')
  296. ctx.tools.register(gated.tool)
  297. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  298. agent.followup({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } })
  299. await until(() => gated.started.length === 1)
  300. await new Promise(r => setTimeout(r, 5))
  301. expect(gated.started).toEqual(['1'])
  302. gated.release('1')
  303. await until(() => gated.started.length === 2)
  304. gated.release('2')
  305. await waitForIdle(ctx, agent)
  306. })
  307. it('applies the configured cap to every factory-created agent', async () => {
  308. const adapter = new MockAdapter([
  309. multiCall([{ id: 'c1', name: 'p', args: { id: '1' } }, { id: 'c2', name: 'p', args: { id: '2' } }]),
  310. textResponse('done'),
  311. ])
  312. const ctx = new Context()
  313. await ctx.plugin(LlmService)
  314. await ctx.plugin(SessionStore)
  315. await ctx.plugin(SystemPrompt, { persona: '' })
  316. await ctx.plugin(ToolRegistry)
  317. await ctx.plugin(AgentRegistry)
  318. await ctx.plugin(AgentLoop, { agents: [], maxParallelToolCalls: 1 })
  319. ctx.llm.registerAdapter(['mock'], adapter)
  320. const gated = gatedParallelTool('p')
  321. ctx.tools.register(gated.tool)
  322. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  323. agent.followup({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } })
  324. await until(() => gated.started.length === 1)
  325. await new Promise(r => setTimeout(r, 5))
  326. expect(gated.started).toEqual(['1'])
  327. gated.release('1')
  328. await until(() => gated.started.length === 2)
  329. gated.release('2')
  330. await waitForIdle(ctx, agent)
  331. })
  332. })
  333. describe('tool-call scheduler: ordered middleware and additional contexts', () => {
  334. it('tools/pre-execute and tools/post-execute observe model call order', async () => {
  335. const adapter = new MockAdapter([
  336. multiCall([{ id: 'c1', name: 'p', args: { id: '1' } }, { id: 'c2', name: 'p', args: { id: '2' } }, { id: 'c3', name: 'p', args: { id: '3' } }]),
  337. textResponse('done'),
  338. ])
  339. const ctx = await harness(adapter)
  340. const gated = gatedParallelTool('p')
  341. ctx.tools.register(gated.tool)
  342. const pre: string[] = []
  343. const post: string[] = []
  344. ctx.on('tools/pre-execute', async (exec, next): Promise<PreToolDecision> => { pre.push(String(exec.callId)); return next() })
  345. ctx.on('tools/post-execute', async (exec, _result, next): Promise<PostToolDecision> => { post.push(String(exec.callId)); return next() })
  346. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  347. agent.followup({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } })
  348. await until(() => gated.started.length === 3)
  349. gated.release('3'); gated.release('2'); gated.release('1')
  350. await waitForIdle(ctx, agent)
  351. expect(pre).toEqual([CallId('c1'), CallId('c2'), CallId('c3')].map(String))
  352. expect(post).toEqual([CallId('c1'), CallId('c2'), CallId('c3')].map(String))
  353. })
  354. it('injects additional contexts in model call order, not settlement order', async () => {
  355. const adapter = new MockAdapter([
  356. multiCall([{ id: 'c1', name: 'p', args: { id: '1' } }, { id: 'c2', name: 'p', args: { id: '2' } }]),
  357. textResponse('done'),
  358. ])
  359. const ctx = await harness(adapter, 2)
  360. const gated = gatedParallelTool('p')
  361. ctx.tools.register(gated.tool)
  362. ctx.on('tools/post-execute', async (exec, _result): Promise<PostToolDecision> =>
  363. ({ kind: 'accept', additionalContexts: [{ content: [{ type: 'text', text: `ctx-${exec.callId}` }], source: { kind: 'plugin', plugin: 'p' } }] }))
  364. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  365. agent.followup({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } })
  366. await until(() => gated.started.length === 2)
  367. gated.release('2'); gated.release('1')
  368. await waitForIdle(ctx, agent)
  369. const log = events(agent)
  370. const contextTexts = log.filter(e => e.type === 'user/message' && e.data.source.kind === 'plugin')
  371. .map(e => ((e.data as { content: { text: string }[] }).content[0]!).text)
  372. expect(contextTexts).toEqual(['ctx-c1', 'ctx-c2'])
  373. const lastResult = log.findLastIndex(e => e.type === 'tool/result')
  374. const firstContext = log.findIndex(e => e.type === 'user/message' && e.data.source.kind === 'plugin')
  375. expect(lastResult).toBeLessThan(firstContext)
  376. })
  377. it('orders pre-execute denials and errors without dispatching them', async () => {
  378. const adapter = new MockAdapter([
  379. multiCall([
  380. { id: 'c1', name: 'p', args: { id: '1' } },
  381. { id: 'c2', name: 'p', args: { id: '2' } },
  382. { id: 'c3', name: 'p', args: { id: '3' } },
  383. ]),
  384. textResponse('done'),
  385. ])
  386. const ctx = await harness(adapter)
  387. const gated = gatedParallelTool('p')
  388. ctx.tools.register(gated.tool)
  389. const post: string[] = []
  390. ctx.on('tools/pre-execute', async (exec, next): Promise<PreToolDecision> => {
  391. if (exec.callId === CallId('c2')) return { kind: 'deny', reason: 'blocked by policy' }
  392. if (exec.callId === CallId('c3')) throw new Error('pre exploded')
  393. return next()
  394. })
  395. ctx.on('tools/post-execute', async (exec, _result, next): Promise<PostToolDecision> => {
  396. post.push(String(exec.callId))
  397. return next()
  398. })
  399. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  400. agent.followup({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } })
  401. await until(() => gated.started.length === 1)
  402. gated.release('1')
  403. await waitForIdle(ctx, agent)
  404. expect(gated.started).toEqual(['1'])
  405. expect(post).toEqual(['c1', 'c2'])
  406. const results = events(agent).filter(e => e.type === 'tool/result')
  407. expect(results.map(e => e.data.callId)).toEqual([CallId('c1'), CallId('c2'), CallId('c3')])
  408. expect((results[1]!.data.content[0] as { text: string }).text).toContain('blocked by policy')
  409. expect((results[2]!.data.content[0] as { text: string }).text).toContain('pre exploded')
  410. })
  411. })
  412. describe('tool-call scheduler: abort handling', () => {
  413. it('starts no calls when the signal is already aborted before a parallel group', async () => {
  414. const adapter = new MockAdapter([
  415. multiCall([{ id: 'c1', name: 'p', args: { id: '1' } }, { id: 'c2', name: 'p', args: { id: '2' } }]),
  416. textResponse('should never be requested'),
  417. ])
  418. const ctx = await harness(adapter)
  419. const gated = gatedParallelTool('p')
  420. ctx.tools.register(gated.tool)
  421. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  422. ctx.on('session/event', (session, event) => {
  423. if (session === agent.session && event.type === 'assistant/message') {
  424. agent.cancel({ kind: 'user' })
  425. }
  426. })
  427. agent.followup({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } })
  428. await waitForIdle(ctx, agent)
  429. expect(gated.started).toEqual([])
  430. expect(events(agent).filter(e => e.type === 'tool/call').map(e => e.data.callId))
  431. .toEqual([CallId('c1'), CallId('c2')])
  432. expect(events(agent).filter(e => e.type === 'tool/result').map(e => ({
  433. callId: e.data.callId,
  434. isError: e.data.isError,
  435. error: e.data.error,
  436. }))).toEqual([
  437. { callId: CallId('c1'), isError: true, error: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH } },
  438. { callId: CallId('c2'), isError: true, error: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH } },
  439. ])
  440. })
  441. it('skips dispatch and stops starting siblings when abort fires during ordered pre-execute', async () => {
  442. const adapter = new MockAdapter([
  443. multiCall([{ id: 'c1', name: 'p', args: { id: '1' } }, { id: 'c2', name: 'p', args: { id: '2' } }]),
  444. textResponse('should never be requested'),
  445. ])
  446. const ctx = await harness(adapter)
  447. const gated = gatedParallelTool('p')
  448. ctx.tools.register(gated.tool)
  449. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  450. ctx.on('tools/pre-execute', async (exec, next): Promise<PreToolDecision> => {
  451. if (exec.callId === CallId('c1')) {
  452. agent.cancel({ kind: 'user' })
  453. }
  454. return next()
  455. })
  456. agent.followup({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } })
  457. await waitForIdle(ctx, agent)
  458. expect(gated.started).toEqual([])
  459. expect(events(agent).filter(e => e.type === 'tool/call').map(e => e.data.callId))
  460. .toEqual([CallId('c1'), CallId('c2')])
  461. expect(events(agent).filter(e => e.type === 'tool/result').map(e => ({
  462. callId: e.data.callId,
  463. isError: e.data.isError,
  464. error: e.data.error,
  465. }))).toEqual([
  466. { callId: CallId('c1'), isError: true, error: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH } },
  467. { callId: CallId('c2'), isError: true, error: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH } },
  468. ])
  469. })
  470. it('stops replenishing after abort, commits started results, and drains accepted additional contexts', async () => {
  471. const adapter = new MockAdapter([
  472. multiCall([1, 2, 3, 4].map(n => ({ id: `c${n}`, name: 'p', args: { id: String(n) } }))),
  473. textResponse('should never be requested'),
  474. ])
  475. const ctx = await harness(adapter, 2)
  476. const gated = gatedParallelTool('p')
  477. ctx.tools.register(gated.tool)
  478. ctx.on('tools/post-execute', async (exec, _result, next): Promise<PostToolDecision> => ({
  479. ...await next(),
  480. additionalContexts: [{ content: [{ type: 'text', text: `ctx-${exec.callId}` }], source: { kind: 'plugin', plugin: 'p' } }],
  481. }))
  482. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  483. agent.followup({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } })
  484. await until(() => gated.started.length === 2)
  485. agent.cancel({ kind: 'user' })
  486. gated.release('1')
  487. gated.release('2')
  488. await waitForIdle(ctx, agent)
  489. expect(gated.started).toEqual(['1', '2'])
  490. expect(events(agent).filter(e => e.type === 'tool/call').map(e => e.data.callId))
  491. .toEqual([CallId('c1'), CallId('c2'), CallId('c3'), CallId('c4')])
  492. expect(events(agent).filter(e => e.type === 'tool/result').map(e => e.data.callId))
  493. .toEqual([CallId('c1'), CallId('c2'), CallId('c3'), CallId('c4')])
  494. expect(events(agent).filter(e => e.type === 'tool/result').slice(-2).map(e => e.data))
  495. .toEqual([
  496. expect.objectContaining({ callId: CallId('c3'), isError: true, error: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH } }),
  497. expect.objectContaining({ callId: CallId('c4'), isError: true, error: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH } }),
  498. ])
  499. const settled = events(agent).filter(e => e.type === 'tool/result'
  500. || (e.type === 'user/message' && e.data.source.kind === 'plugin'))
  501. expect(settled.map(e => e.type))
  502. .toEqual(['tool/result', 'tool/result', 'tool/result', 'tool/result', 'user/message', 'user/message'])
  503. expect(settled.filter(e => e.type === 'user/message')
  504. .map(e => (e.data.content[0] as { text: string }).text))
  505. .toEqual(['ctx-c1', 'ctx-c2'])
  506. })
  507. it('does not run an exclusive barrier after a parallel group aborts', async () => {
  508. const adapter = new MockAdapter([
  509. multiCall([
  510. { id: 'c1', name: 'p', args: { id: '1' } },
  511. { id: 'c2', name: 'p', args: { id: '2' } },
  512. { id: 'c3', name: 'x', args: { id: '3' } },
  513. ]),
  514. textResponse('should never be requested'),
  515. ])
  516. const ctx = await harness(adapter, 2)
  517. const gated = gatedParallelTool('p')
  518. const exclusive: string[] = []
  519. ctx.tools.register(gated.tool)
  520. ctx.tools.register(defineContentToolFixture({
  521. name: 'x',
  522. description: 'exclusive',
  523. parameters: { id: { type: 'string', required: true } },
  524. async execute(args) { exclusive.push(args.id); return [{ type: 'text', text: 'x' }] },
  525. }))
  526. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  527. agent.followup({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } })
  528. await until(() => gated.started.length === 2)
  529. agent.cancel({ kind: 'user' })
  530. gated.release('1')
  531. gated.release('2')
  532. await waitForIdle(ctx, agent)
  533. expect(exclusive).toEqual([])
  534. expect(events(agent).filter(e => e.type === 'tool/call').map(e => e.data.callId))
  535. .toEqual([CallId('c1'), CallId('c2'), CallId('c3')])
  536. expect(events(agent).filter(e => e.type === 'tool/result').at(-1)?.data)
  537. .toMatchObject({ callId: CallId('c3'), isError: true, error: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH } })
  538. })
  539. })