agent-initiator.spec.ts 15 KB

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