agent-initiator.spec.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. import { describe, expect, it } from 'vitest'
  2. import { Context, type Fiber } from '@deepseek-ai/cordis'
  3. import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent'
  4. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  5. import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
  6. import LlmRuntime, { createUserMessage, ToolCallId, LlmAdapter } from '@deepseek-ai/dsh-llm'
  7. import type { GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm'
  8. import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
  9. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  10. import ToolRuntime, { defineContentToolFixture } from '@deepseek-ai/dsh-tools'
  11. import { MockAdapter, textResponse, toolCallResponse } from './mock-adapter.ts'
  12. const testToolSignal = new AbortController().signal
  13. interface Harness {
  14. ctx: Context
  15. agentsFiber: Fiber
  16. loopFiber: Fiber
  17. }
  18. async function harness(adapter: LlmAdapter): Promise<Harness> {
  19. const ctx = new Context()
  20. await ctx.plugin(LlmRuntime)
  21. await ctx.plugin(SessionStore)
  22. await ctx.plugin(SessionProjectionRegistry)
  23. await ctx.plugin(SystemPrompt)
  24. await ctx.plugin(ToolRuntime)
  25. const agentsFiber = await ctx.plugin(AgentRegistry)
  26. const loopFiber = await ctx.plugin(AgentLoop, { agents: [] })
  27. ctx.llm.registerAdapter(['mock'], adapter)
  28. return { ctx, agentsFiber, loopFiber }
  29. }
  30. function waitForIdle(ctx: Context, agent: Agent): Promise<void> {
  31. return new Promise((resolve) => {
  32. const dispose = ctx.on('agent/status', ({ agent: 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.followup(createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } }))
  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.agents.requireInitiator()
  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.agents.requireInitiator()
  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 agents: AgentRegistry) {}
  66. async request(path: string): Promise<Record<string, string>> {
  67. await Promise.resolve()
  68. const headers = {
  69. 'X-Harness-Session-Id': this.agents.requireInitiator().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. agents: AgentRegistry | undefined
  82. async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
  83. const agents = this.agents
  84. if (agents === undefined) throw new Error('agent 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 = agents.requireInitiator()
  97. throw error
  98. }
  99. return
  100. }
  101. await Promise.resolve()
  102. this.laterAgent = agents.requireInitiator()
  103. yield* textResponse('reloaded')
  104. }
  105. }
  106. describe('AgentLoop initiator scope', () => {
  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(LlmRuntime)
  111. await ctx.plugin(SessionStore)
  112. await ctx.plugin(SessionProjectionRegistry)
  113. await ctx.plugin(SystemPrompt)
  114. await ctx.plugin(ToolRuntime)
  115. await ctx.plugin(AgentRegistry)
  116. await ctx.plugin(AgentLoop, { agents: [] })
  117. ctx.llm.registerAdapter(['mock'], adapter)
  118. const a = await ctx.agentLoop.create(SessionId('a'), { provider: 'mock', model: 'mock' })
  119. const b = await ctx.agentLoop.create(SessionId('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.agents.currentInitiator()).toBeUndefined()
  131. await ctx.fiber.dispose()
  132. })
  133. it('keeps initiator identity minimal while one explicit signal spans each turn seam', async () => {
  134. const adapter = new MockAdapter([
  135. toolCallResponse('observe-call', 'observe', {}),
  136. textResponse('first done'),
  137. textResponse('second done'),
  138. ])
  139. const { ctx } = await harness(adapter)
  140. const agent = await ctx.agentLoop.create(SessionId('signal-owner'), { provider: 'mock', model: 'mock' })
  141. let signals: AbortSignal[] = []
  142. let preStepSignals: AbortSignal[] = []
  143. const capture = (signal: AbortSignal | undefined): void => {
  144. if (signal === undefined) throw new Error('turn seam omitted its explicit signal')
  145. expect(ctx.agents.requireInitiator()).toBe(agent)
  146. signals.push(signal)
  147. }
  148. ctx.on('system-prompt/assemble', async (_assembly, context, next) => {
  149. if (context.agent === agent) capture(context.signal)
  150. return next()
  151. })
  152. ctx.on('agent/pre-step', async ({ agent: subject, signal }, next) => {
  153. if (subject === agent) {
  154. expect(ctx.agents.requireInitiator()).toBe(agent)
  155. preStepSignals.push(signal)
  156. }
  157. return next()
  158. })
  159. ctx.on('agent/request', async ({ agent: subject, signal }, next) => {
  160. if (subject === agent) capture(signal)
  161. return next()
  162. })
  163. ctx.on('agent/turn-stopping', ({ agent: subject, 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(preStepSignals).toHaveLength(2)
  182. expect(new Set(preStepSignals)).toEqual(new Set([firstSignal]))
  183. signals = []
  184. preStepSignals = []
  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(preStepSignals).toHaveLength(1)
  192. expect(preStepSignals[0]).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. parentAgent: exec.agent,
  220. setup: (agentCtx, childAgent) => {
  221. parentDuringSetup = ctx.agents.requireInitiator()
  222. explicitChild = childAgent
  223. agentCtx.tools.register(defineContentToolFixture({
  224. name: 'observe-child',
  225. description: 'observe child execution identity',
  226. parameters: {},
  227. execute: async () => {
  228. await Promise.resolve()
  229. childDuringDriver = ctx.agents.requireInitiator()
  230. return [{ type: 'text', text: 'observed' }]
  231. },
  232. }))
  233. },
  234. })
  235. child = handle.agent
  236. parentWhileChildDriverActive = ctx.agents.requireInitiator()
  237. send(handle.agent, 'run child')
  238. await handle.agent.whenIdle()
  239. await handle.dispose()
  240. return [{ type: 'text', text: 'child completed' }]
  241. },
  242. }))
  243. const parentHandle = await ctx.agents.create({
  244. sessionId: SessionId('parent-session'),
  245. agentOptions: { provider: 'mock', model: 'mock' },
  246. })
  247. const idle = waitForIdle(ctx, parentHandle.agent)
  248. send(parentHandle.agent, 'spawn')
  249. await idle
  250. expect(parentDuringSetup).toBe(parentHandle.agent)
  251. expect(explicitChild).toBe(child)
  252. expect(childDuringDriver).toBe(child)
  253. expect(parentWhileChildDriverActive).toBe(parentHandle.agent)
  254. expect(ctx.agents.currentInitiator()).toBeUndefined()
  255. await parentHandle.dispose()
  256. await ctx.fiber.dispose()
  257. })
  258. it('keeps agentless direct tools ambient-free and builds trusted transport headers internally', async () => {
  259. const adapter = new MockAdapter([
  260. toolCallResponse('capability', 'capability-request', { path: '/v1/capability' }),
  261. textResponse('done'),
  262. ])
  263. const { ctx } = await harness(adapter)
  264. const transport = new TestCapabilityTransport(ctx.agents)
  265. let directAmbient: Agent | undefined
  266. let captured: Agent | undefined
  267. ctx.tools.register(defineContentToolFixture({
  268. name: 'agentless-probe',
  269. description: 'observe an agentless call',
  270. parameters: {},
  271. execute: async () => {
  272. await Promise.resolve()
  273. directAmbient = ctx.agents.currentInitiator()
  274. return [{ type: 'text', text: 'ok' }]
  275. },
  276. }))
  277. ctx.tools.register(defineContentToolFixture({
  278. name: 'capability-request',
  279. description: 'call the test capability transport',
  280. parameters: { path: { type: 'string' } },
  281. execute: async (args) => {
  282. captured = ctx.agents.requireInitiator()
  283. const path = (args as { path: string }).path
  284. const headers = await transport.request(path)
  285. return [{ type: 'text', text: JSON.stringify(headers) }]
  286. },
  287. }))
  288. const direct = await ctx.tools.execute({
  289. signal: testToolSignal,
  290. callId: ToolCallId('direct'),
  291. name: 'agentless-probe',
  292. arguments: {},
  293. })
  294. expect(direct.isError).toBe(false)
  295. expect(directAmbient).toBeUndefined()
  296. const handle = await ctx.agents.create({
  297. sessionId: SessionId('transport-session'),
  298. agentOptions: { provider: 'mock', model: 'mock' },
  299. })
  300. const idle = waitForIdle(ctx, handle.agent)
  301. send(handle.agent, 'call transport')
  302. await idle
  303. expect(transport.requests).toEqual([{
  304. path: '/v1/capability',
  305. headers: { 'X-Harness-Session-Id': 'transport-session' },
  306. }])
  307. const schema = adapter.requests[0]?.tools?.find(tool => tool.name === 'capability-request')
  308. expect(JSON.stringify(schema?.parameters)).not.toMatch(/session|harness/i)
  309. const call = handle.agent.session.snapshotEvents().find(event => event.type === 'tool/call')
  310. expect(call?.type === 'tool/call' ? call.data.arguments : undefined)
  311. .toBe(JSON.stringify({ path: '/v1/capability' }))
  312. expect(captured).toBe(handle.agent)
  313. await handle.dispose()
  314. expect(ctx.agents.currentInitiator()).toBeUndefined()
  315. await ctx.fiber.dispose()
  316. })
  317. it('drains the old driver before disabling ALS during agent-service restart', async () => {
  318. const adapter = new ReloadAdapter()
  319. const { ctx, agentsFiber, loopFiber } = await harness(adapter)
  320. const oldService = ctx.agents
  321. adapter.agents = oldService
  322. const oldHandle = await ctx.agents.create({
  323. sessionId: SessionId('before-restart-session'),
  324. agentOptions: { provider: 'mock', model: 'mock' },
  325. })
  326. const oldAgent = oldHandle.agent
  327. send(oldAgent, 'block')
  328. await adapter.firstStarted.promise
  329. await agentsFiber.restart()
  330. await loopFiber.await()
  331. expect(adapter.firstAgentDuringAbort?.id).toBe(oldAgent.id)
  332. expect(adapter.firstAgentDuringAbort?.session).toBe(oldAgent.session)
  333. expect(() => oldService.currentInitiator()).toThrow('agent initiator scope is disposed')
  334. expect(ctx.agents).not.toBe(oldService)
  335. adapter.agents = ctx.agents
  336. const newHandle = await ctx.agents.create({
  337. sessionId: SessionId('after-restart-session'),
  338. agentOptions: { provider: 'mock', model: 'mock' },
  339. })
  340. const newAgent = newHandle.agent
  341. const idle = waitForIdle(ctx, newAgent)
  342. send(newAgent, 'continue')
  343. await idle
  344. expect(adapter.laterAgent?.id).toBe(newAgent.id)
  345. expect(adapter.laterAgent?.session).toBe(newAgent.session)
  346. await ctx.fiber.dispose()
  347. })
  348. it('keeps ALS readable while root disposal drains sibling AgentLoop fibers', async () => {
  349. const ctx = new Context()
  350. const adapter = new ReloadAdapter()
  351. await ctx.plugin(LlmRuntime)
  352. await ctx.plugin(SessionStore)
  353. await ctx.plugin(SessionProjectionRegistry)
  354. await ctx.plugin(SystemPrompt)
  355. await ctx.plugin(ToolRuntime)
  356. await ctx.plugin(AgentRegistry)
  357. await ctx.plugin(AgentLoop, { agents: [] })
  358. ctx.llm.registerAdapter(['mock'], adapter)
  359. const service = ctx.agents
  360. adapter.agents = service
  361. const handle = await ctx.agents.create({
  362. sessionId: SessionId('root-dispose-session'),
  363. agentOptions: { provider: 'mock', model: 'mock' },
  364. })
  365. const agent = handle.agent
  366. send(agent, 'block')
  367. await adapter.firstStarted.promise
  368. await ctx.fiber.dispose()
  369. expect(adapter.firstAgentDuringAbort?.id).toBe(agent.id)
  370. expect(adapter.firstAgentDuringAbort?.session).toBe(agent.session)
  371. expect(() => service.currentInitiator()).toThrow('agent initiator scope is disposed')
  372. })
  373. })