agent-execution.spec.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. import { describe, expect, it } from 'vitest'
  2. import { Context, FiberState, type Fiber } from 'cordis'
  3. import AgentRegistry, { AgentId, type Agent } from '@deepseek-ai/dsh-agent'
  4. import AgentExecutionProvider from '@deepseek-ai/dsh-agent-execution'
  5. import type { AgentExecutionService } from '@deepseek-ai/dsh-agent-execution'
  6. import AgentLoop, { type ReactLoopAgent } from '@deepseek-ai/dsh-agent-loop'
  7. import LlmService, { CallId, LlmAdapter } from '@deepseek-ai/dsh-llm'
  8. import type { GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm'
  9. import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
  10. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  11. import ToolRegistry, { defineTool } from '@deepseek-ai/dsh-tools'
  12. import { MockAdapter, textResponse, toolCallResponse } from './mock-adapter.ts'
  13. interface Harness {
  14. ctx: Context
  15. providerFiber: Fiber
  16. loopFiber: Fiber
  17. }
  18. async function harness(adapter: LlmAdapter): Promise<Harness> {
  19. const ctx = new Context()
  20. await ctx.plugin(LlmService)
  21. await ctx.plugin(SessionStore)
  22. await ctx.plugin(SystemPrompt)
  23. await ctx.plugin(ToolRegistry)
  24. await ctx.plugin(AgentRegistry)
  25. const providerFiber = await ctx.plugin(AgentExecutionProvider)
  26. const loopFiber = await ctx.plugin(AgentLoop, { agents: [] })
  27. ctx.llm.registerAdapter(['mock'], adapter)
  28. return { ctx, providerFiber, loopFiber }
  29. }
  30. function waitForIdle(ctx: Context, agent: ReactLoopAgent | Agent): Promise<void> {
  31. return new Promise((resolve) => {
  32. const dispose = ctx.on('agent/status', (subject, status) => {
  33. if (subject === agent && status === 'idle') {
  34. dispose()
  35. resolve()
  36. }
  37. })
  38. })
  39. }
  40. function send(agent: Agent, text: string): void {
  41. agent.send([{ type: 'text', text }])
  42. }
  43. /** Adapter that holds both drivers at the same awaited continuation. */
  44. class OverlapAdapter extends LlmAdapter {
  45. private readonly bothStarted = Promise.withResolvers<boolean>()
  46. private starts = 0
  47. readonly observations: { sessionId: SessionId | undefined; before: Agent; after: Agent }[] = []
  48. constructor(private readonly ctx: Context) {
  49. super()
  50. }
  51. async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
  52. const before = this.ctx.agentExecution.require().agent
  53. this.starts += 1
  54. if (this.starts === 2) this.bothStarted.resolve(true)
  55. await this.bothStarted.promise
  56. await Promise.resolve()
  57. const after = this.ctx.agentExecution.require().agent
  58. this.observations.push({ sessionId: options.sessionId, before, after })
  59. yield* textResponse('done')
  60. }
  61. }
  62. /** Test-only transport that materializes ambient identity at its request boundary. */
  63. class TestCapabilityTransport {
  64. readonly requests: { path: string; headers: Record<string, string> }[] = []
  65. constructor(private readonly execution: AgentExecutionService) {}
  66. async request(path: string): Promise<Record<string, string>> {
  67. await Promise.resolve()
  68. const headers = {
  69. 'X-Harness-Session-Id': this.execution.require().agent.session.id,
  70. }
  71. this.requests.push({ path, headers })
  72. return headers
  73. }
  74. }
  75. /** Adapter whose first call waits for cancellation and whose later calls complete. */
  76. class ReloadAdapter extends LlmAdapter {
  77. readonly firstStarted = Promise.withResolvers<boolean>()
  78. firstAgentDuringAbort: Agent | undefined
  79. laterAgent: Agent | undefined
  80. calls = 0
  81. execution: AgentExecutionService | undefined
  82. async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
  83. const execution = this.execution
  84. if (execution === undefined) throw new Error('execution service missing')
  85. this.calls += 1
  86. if (this.calls === 1) {
  87. this.firstStarted.resolve(true)
  88. try {
  89. await new Promise<void>((_resolve, reject) => {
  90. const abort = (): void => { reject(new Error('aborted')) }
  91. if (options.signal?.aborted === true) abort()
  92. else options.signal?.addEventListener('abort', abort, { once: true })
  93. })
  94. } catch (error: unknown) {
  95. await Promise.resolve()
  96. this.firstAgentDuringAbort = execution.require().agent
  97. throw error
  98. }
  99. return
  100. }
  101. await Promise.resolve()
  102. this.laterAgent = execution.require().agent
  103. yield* textResponse('reloaded')
  104. }
  105. }
  106. describe('AgentLoop execution context', () => {
  107. it('keeps overlapping driver continuations bound to their exact Agents', async () => {
  108. const ctx = new Context()
  109. const adapter = new OverlapAdapter(ctx)
  110. await ctx.plugin(LlmService)
  111. await ctx.plugin(SessionStore)
  112. await ctx.plugin(SystemPrompt)
  113. await ctx.plugin(ToolRegistry)
  114. await ctx.plugin(AgentRegistry)
  115. await ctx.plugin(AgentExecutionProvider)
  116. await ctx.plugin(AgentLoop, { agents: [] })
  117. ctx.llm.registerAdapter(['mock'], adapter)
  118. const a = ctx.agentLoop.create(AgentId('a'), { provider: 'mock', model: 'mock' })
  119. const b = ctx.agentLoop.create(AgentId('b'), { provider: 'mock', model: 'mock' })
  120. const idleA = waitForIdle(ctx, a)
  121. const idleB = waitForIdle(ctx, b)
  122. send(a, 'a')
  123. send(b, 'b')
  124. await Promise.all([idleA, idleB])
  125. expect(adapter.observations).toHaveLength(2)
  126. expect(adapter.observations).toEqual(expect.arrayContaining([
  127. { sessionId: a.session.id, before: a, after: a },
  128. { sessionId: b.session.id, before: b, after: b },
  129. ]))
  130. expect(ctx.agentExecution.current()).toBeUndefined()
  131. await ctx.fiber.dispose()
  132. })
  133. it('keeps child setup under the parent boundary, switches for the child driver, then restores the parent', async () => {
  134. const adapter = new MockAdapter([
  135. toolCallResponse('spawn', 'spawn-child', {}),
  136. toolCallResponse('observe', 'observe-child', {}),
  137. textResponse('child done'),
  138. textResponse('parent done'),
  139. ])
  140. const { ctx } = await harness(adapter)
  141. let parentDuringSetup: Agent | undefined
  142. let explicitChild: Agent | undefined
  143. let childDuringDriver: Agent | undefined
  144. let parentAfterChild: Agent | undefined
  145. let child: Agent | undefined
  146. ctx.tools.register(defineTool({
  147. name: 'spawn-child',
  148. description: 'create one child agent',
  149. parameters: {},
  150. execute: async (_args, exec) => {
  151. if (exec.agent === undefined) throw new Error('parent agent missing')
  152. const handle = await exec.agent.ctx.agents.create({
  153. agentId: AgentId('child'),
  154. sessionId: SessionId('child-session'),
  155. agentOptions: { provider: 'mock', model: 'mock' },
  156. setup: (agentCtx) => {
  157. parentDuringSetup = ctx.agentExecution.require().agent
  158. explicitChild = agentCtx.agent
  159. agentCtx.tools.register(defineTool({
  160. name: 'observe-child',
  161. description: 'observe child execution identity',
  162. parameters: {},
  163. execute: async () => {
  164. await Promise.resolve()
  165. childDuringDriver = ctx.agentExecution.require().agent
  166. return [{ type: 'text', text: 'observed' }]
  167. },
  168. }))
  169. },
  170. })
  171. child = handle.agent
  172. send(handle.agent, 'run child')
  173. await handle.agent.whenIdle()
  174. parentAfterChild = ctx.agentExecution.require().agent
  175. await handle.dispose()
  176. return [{ type: 'text', text: 'child completed' }]
  177. },
  178. }))
  179. const parentHandle = await ctx.agents.create({
  180. agentId: AgentId('parent'),
  181. sessionId: SessionId('parent-session'),
  182. agentOptions: { provider: 'mock', model: 'mock' },
  183. })
  184. const idle = waitForIdle(ctx, parentHandle.agent)
  185. send(parentHandle.agent, 'spawn')
  186. await idle
  187. expect(parentDuringSetup).toBe(parentHandle.agent)
  188. expect(explicitChild).toBe(child)
  189. expect(childDuringDriver).toBe(child)
  190. expect(parentAfterChild).toBe(parentHandle.agent)
  191. expect(ctx.agentExecution.current()).toBeUndefined()
  192. await parentHandle.dispose()
  193. await ctx.fiber.dispose()
  194. })
  195. it('keeps agentless direct tools ambient-free and builds trusted transport headers internally', async () => {
  196. const adapter = new MockAdapter([
  197. toolCallResponse('capability', 'capability-request', { path: '/v1/capability' }),
  198. textResponse('done'),
  199. ])
  200. const { ctx } = await harness(adapter)
  201. const transport = new TestCapabilityTransport(ctx.agentExecution)
  202. let directAmbient: Agent | undefined
  203. let captured: Agent | undefined
  204. ctx.tools.register(defineTool({
  205. name: 'agentless-probe',
  206. description: 'observe an agentless call',
  207. parameters: {},
  208. execute: async () => {
  209. await Promise.resolve()
  210. directAmbient = ctx.agentExecution.current()?.agent
  211. return [{ type: 'text', text: 'ok' }]
  212. },
  213. }))
  214. ctx.tools.register(defineTool({
  215. name: 'capability-request',
  216. description: 'call the test capability transport',
  217. parameters: { path: { type: 'string' } },
  218. execute: async (args) => {
  219. captured = ctx.agentExecution.require().agent
  220. const path = (args as { path: string }).path
  221. const headers = await transport.request(path)
  222. return [{ type: 'text', text: JSON.stringify(headers) }]
  223. },
  224. }))
  225. const direct = await ctx.tools.execute({
  226. callId: CallId('direct'),
  227. name: 'agentless-probe',
  228. arguments: {},
  229. })
  230. expect(direct.isError).toBe(false)
  231. expect(directAmbient).toBeUndefined()
  232. const handle = await ctx.agents.create({
  233. agentId: AgentId('transport'),
  234. sessionId: SessionId('transport-session'),
  235. agentOptions: { provider: 'mock', model: 'mock' },
  236. })
  237. const idle = waitForIdle(ctx, handle.agent)
  238. send(handle.agent, 'call transport')
  239. await idle
  240. expect(transport.requests).toEqual([{
  241. path: '/v1/capability',
  242. headers: { 'X-Harness-Session-Id': 'transport-session' },
  243. }])
  244. const schema = adapter.requests[0]?.tools?.find(tool => tool.name === 'capability-request')
  245. expect(JSON.stringify(schema?.parameters)).not.toMatch(/session|harness/i)
  246. const call = handle.agent.session.events.find(event => event.type === 'tool/call')
  247. expect(call?.type === 'tool/call' ? call.data.arguments : undefined)
  248. .toBe(JSON.stringify({ path: '/v1/capability' }))
  249. expect(captured).toBe(handle.agent)
  250. await handle.dispose()
  251. expect(captured?.status).toBe('disposed')
  252. expect(ctx.agentExecution.current()).toBeUndefined()
  253. await ctx.fiber.dispose()
  254. })
  255. it('keeps AgentLoop inactive until the mandatory provider appears', async () => {
  256. const ctx = new Context()
  257. await ctx.plugin(LlmService)
  258. await ctx.plugin(SessionStore)
  259. await ctx.plugin(SystemPrompt)
  260. await ctx.plugin(ToolRegistry)
  261. await ctx.plugin(AgentRegistry)
  262. const loopFiber = ctx.plugin(AgentLoop, { agents: [] })
  263. await Promise.resolve()
  264. expect(loopFiber.state).toBe(FiberState.PENDING)
  265. await ctx.plugin(AgentExecutionProvider)
  266. await loopFiber
  267. expect(loopFiber.state).toBe(FiberState.ACTIVE)
  268. await ctx.fiber.dispose()
  269. })
  270. it('drains the old driver before disabling ALS during provider restart', async () => {
  271. const ctx = new Context()
  272. const adapter = new ReloadAdapter()
  273. const { providerFiber, loopFiber } = await (async (): Promise<Harness> => {
  274. await ctx.plugin(LlmService)
  275. await ctx.plugin(SessionStore)
  276. await ctx.plugin(SystemPrompt)
  277. await ctx.plugin(ToolRegistry)
  278. await ctx.plugin(AgentRegistry)
  279. const mountedProvider = await ctx.plugin(AgentExecutionProvider)
  280. const mountedLoop = await ctx.plugin(AgentLoop, { agents: [] })
  281. ctx.llm.registerAdapter(['mock'], adapter)
  282. return { ctx, providerFiber: mountedProvider, loopFiber: mountedLoop }
  283. })()
  284. const oldService = ctx.agentExecution
  285. adapter.execution = oldService
  286. const oldHandle = await ctx.agents.create({
  287. agentId: AgentId('before-restart'),
  288. sessionId: SessionId('before-restart-session'),
  289. agentOptions: { provider: 'mock', model: 'mock' },
  290. })
  291. const oldAgent = oldHandle.agent
  292. send(oldAgent, 'block')
  293. await adapter.firstStarted.promise
  294. await providerFiber.restart()
  295. await loopFiber.await()
  296. expect(adapter.firstAgentDuringAbort?.id).toBe(oldAgent.id)
  297. expect(adapter.firstAgentDuringAbort?.session).toBe(oldAgent.session)
  298. expect(oldAgent.status).toBe('disposed')
  299. expect(() => oldService.current()).toThrow('agent execution service is disposed')
  300. expect(ctx.agentExecution).not.toBe(oldService)
  301. adapter.execution = ctx.agentExecution
  302. const newHandle = await ctx.agents.create({
  303. agentId: AgentId('after-restart'),
  304. sessionId: SessionId('after-restart-session'),
  305. agentOptions: { provider: 'mock', model: 'mock' },
  306. })
  307. const newAgent = newHandle.agent
  308. const idle = waitForIdle(ctx, newAgent)
  309. send(newAgent, 'continue')
  310. await idle
  311. expect(adapter.laterAgent?.id).toBe(newAgent.id)
  312. expect(adapter.laterAgent?.session).toBe(newAgent.session)
  313. await ctx.fiber.dispose()
  314. })
  315. it('keeps ALS readable while root disposal drains sibling AgentLoop fibers', async () => {
  316. const ctx = new Context()
  317. const adapter = new ReloadAdapter()
  318. await ctx.plugin(LlmService)
  319. await ctx.plugin(SessionStore)
  320. await ctx.plugin(SystemPrompt)
  321. await ctx.plugin(ToolRegistry)
  322. await ctx.plugin(AgentRegistry)
  323. await ctx.plugin(AgentExecutionProvider)
  324. await ctx.plugin(AgentLoop, { agents: [] })
  325. ctx.llm.registerAdapter(['mock'], adapter)
  326. const service = ctx.agentExecution
  327. adapter.execution = service
  328. const handle = await ctx.agents.create({
  329. agentId: AgentId('root-dispose'),
  330. sessionId: SessionId('root-dispose-session'),
  331. agentOptions: { provider: 'mock', model: 'mock' },
  332. })
  333. const agent = handle.agent
  334. send(agent, 'block')
  335. await adapter.firstStarted.promise
  336. await ctx.fiber.dispose()
  337. expect(adapter.firstAgentDuringAbort?.id).toBe(agent.id)
  338. expect(adapter.firstAgentDuringAbort?.session).toBe(agent.session)
  339. expect(agent.status).toBe('disposed')
  340. expect(() => service.current()).toThrow('agent execution service is disposed')
  341. })
  342. })