agent.spec.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. import { describe, expect, expectTypeOf, it } from 'vitest'
  2. import { Context, Service, symbols } from '@deepseek-ai/cordis'
  3. import { createUserMessage, freezeMessage } from '@deepseek-ai/dsh-llm'
  4. import { Session, SessionId, type UserMessage } from '@deepseek-ai/dsh-session'
  5. import AgentRegistry, {
  6. agentEvents,
  7. Inbox,
  8. } from '@deepseek-ai/dsh-agent'
  9. import TypertRegistry from '@deepseek-ai/dsh-typert-registry'
  10. import type {
  11. Agent,
  12. AgentCancelCause,
  13. AgentFactory,
  14. AgentStatus,
  15. CreateAgentOptions,
  16. ResumeAgentOptions,
  17. } from '@deepseek-ai/dsh-agent'
  18. function stubAgent(rawId: string, overrides: Partial<Agent> = {}): Agent {
  19. const id = SessionId(rawId)
  20. const session = Session.create(id)
  21. const agent: Agent = {
  22. id,
  23. options: {},
  24. session,
  25. inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }),
  26. status: 'idle',
  27. ctx: new Context(),
  28. send: () => {},
  29. followup: () => {},
  30. steer: () => ({ outcome: Promise.resolve({ status: 'rejected' as const }) }),
  31. inject: () => {},
  32. cancel() {},
  33. runMaintenance: task => task(new AbortController().signal),
  34. whenIdle: () => Promise.resolve(),
  35. }
  36. return Object.assign(agent, overrides)
  37. }
  38. describe('Inbox', () => {
  39. it('rejects an invalid durable splice during reconstruction', () => {
  40. const session = Session.create(SessionId('invalid-inbox-replay'))
  41. session.append('agent/inbox/spliced', {
  42. target: 'next-turn',
  43. start: 1,
  44. inserted: [],
  45. })
  46. expect(() => new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }))
  47. .toThrow('invalid persisted inbox splice at session seq 0')
  48. })
  49. it('replaces a pending message by identity across both lists', () => {
  50. const session = Session.create(SessionId('replace-inbox'))
  51. const inserted: UserMessage[] = []
  52. const discarded: UserMessage[] = []
  53. const inbox = new Inbox(session, {
  54. claimed: () => {},
  55. inserted: message => void inserted.push(message),
  56. discarded: message => void discarded.push(message),
  57. })
  58. const original = createUserMessage({
  59. content: [{ type: 'text', text: 'original' }],
  60. source: { kind: 'user' },
  61. })
  62. const nextStep = createUserMessage({
  63. content: [{ type: 'text', text: 'step' }],
  64. source: { kind: 'user' },
  65. })
  66. const replacement = createUserMessage({
  67. content: [{ type: 'text', text: 'replacement' }],
  68. source: { kind: 'user' },
  69. })
  70. const editedStep = freezeMessage({
  71. ...nextStep,
  72. content: [{ type: 'text', text: 'edited step' }],
  73. })
  74. inbox.append('next-turn', original)
  75. inbox.append('next-step', nextStep)
  76. expect(inbox.replace(createUserMessage({
  77. content: [{ type: 'text', text: 'missing' }],
  78. source: { kind: 'user' },
  79. }).id, replacement)).toBe(false)
  80. expect(inbox.replace(original.id, replacement)).toBe(true)
  81. expect(inbox.replace(nextStep.id, editedStep)).toBe(true)
  82. expect(inbox.nextTurn).toEqual([replacement])
  83. expect(inbox.nextStep).toEqual([editedStep])
  84. expect(discarded).toEqual([original, nextStep])
  85. expect(inserted).toEqual([original, nextStep, replacement, editedStep])
  86. expect(() => { inbox.replace(editedStep.id, replacement) })
  87. .toThrow(`message "${replacement.id}" is already pending`)
  88. })
  89. it('normalizes splice coordinates, rejects duplicate identities, and reports missing removals', () => {
  90. const session = Session.create(SessionId('splice-inbox'))
  91. const inbox = new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} })
  92. const first = createUserMessage({
  93. content: [{ type: 'text', text: 'first' }],
  94. source: { kind: 'user' },
  95. })
  96. const second = createUserMessage({
  97. content: [{ type: 'text', text: 'second' }],
  98. source: { kind: 'user' },
  99. })
  100. inbox.splice('next-turn', Number.NaN, Number.NaN, [first, second])
  101. expect(inbox.nextTurn).toEqual([first, second])
  102. expect(inbox.splice('next-turn', -1, 1, [])).toEqual([second])
  103. expect(inbox.remove(second.id)).toBe(false)
  104. expect(() => { inbox.append('next-step', first) }).toThrow(`message "${first.id}" is already pending`)
  105. })
  106. it('clears both pending lists as durable cancellations', () => {
  107. const session = Session.create(SessionId('clear-inbox'))
  108. const discarded: UserMessage[] = []
  109. const inbox = new Inbox(session, {
  110. claimed: () => {},
  111. inserted: () => {},
  112. discarded: message => void discarded.push(message),
  113. })
  114. const nextTurn = createUserMessage({ content: [{ type: 'text', text: 'turn' }], source: { kind: 'user' } })
  115. const nextStep = createUserMessage({ content: [{ type: 'text', text: 'step' }], source: { kind: 'user' } })
  116. inbox.append('next-turn', nextTurn)
  117. inbox.append('next-step', nextStep)
  118. const beforeClear = session.events.length
  119. inbox.clear()
  120. expect(inbox.hasPending).toBe(false)
  121. expect(discarded).toEqual([nextStep, nextTurn])
  122. expect(session.events.slice(beforeClear).map(event => event.type === 'agent/inbox/spliced'
  123. ? event.data
  124. : event.type)).toEqual([
  125. { target: 'next-step', start: 0, removedCount: 1, inserted: [], outcome: 'canceled' },
  126. { target: 'next-turn', start: 0, removedCount: 1, inserted: [], outcome: 'canceled' },
  127. ])
  128. inbox.clear()
  129. expect(session.events).toHaveLength(beforeClear + 2)
  130. })
  131. })
  132. describe('AgentRegistry', () => {
  133. it('contributes Agent lookup and scoped Context providers while Typert is live', async () => {
  134. const ctx = new Context()
  135. const agentFiber = ctx.plugin(AgentRegistry)
  136. await agentFiber
  137. await ctx.plugin(TypertRegistry)
  138. const agent = stubAgent('remote-agent')
  139. Object.defineProperty(agent, 'ctx', { value: agent.ctx.extend({ agent }) })
  140. const disposeAgent = ctx.agents.register(agent)
  141. const lookup = ctx.typert.lookups.get('agent')
  142. expect(lookup).toMatchObject({
  143. parameter: 'agent',
  144. wire: 'agentId',
  145. hostTypeSymbol: '@deepseek-ai/dsh-agent#Agent',
  146. wireTypeSymbol: '@deepseek-ai/dsh-session/types#SessionId',
  147. })
  148. expect(lookup?.resolve(agent.id)).toBe(agent)
  149. const context = ctx.typert.contexts.getHost('agent')
  150. expect(context?.identity(agent.ctx)).toBe(agent.id)
  151. expect(context?.identity(ctx)).toBeUndefined()
  152. expect(context?.resolve(agent.id)).toBe(agent.ctx)
  153. disposeAgent()
  154. expect(lookup?.resolve(agent.id)).toBeUndefined()
  155. await agentFiber.dispose()
  156. expect(ctx.typert.lookups.get('agent')).toBeUndefined()
  157. expect(ctx.typert.contexts.getHost('agent')).toBeUndefined()
  158. })
  159. it('registers exact entries, emits lifecycle events, and unregisters on owner disposal', async () => {
  160. const ctx = new Context()
  161. await ctx.plugin(AgentRegistry)
  162. const lifecycle: string[] = []
  163. ctx.on('agent/created', ({ agent }) => void lifecycle.push(`created:${agent.id}`))
  164. ctx.on('agent/disposed', ({ agent }) => void lifecycle.push(`disposed:${agent.id}`))
  165. const agent = stubAgent('a1')
  166. const dispose = ctx.agents.register(agent)
  167. expect(ctx.agents.get(agent.id)).toBe(agent)
  168. expect(ctx.agents.list()).toEqual([agent])
  169. expect(ctx.agents.roots()).toEqual([agent])
  170. expect(() => ctx.agents.register(stubAgent('a1'))).toThrow(/already registered/)
  171. dispose()
  172. expect(ctx.agents.get(agent.id)).toBeUndefined()
  173. expect(lifecycle).toEqual(['created:a1', 'disposed:a1'])
  174. })
  175. it('rejects an agent whose registry and session identities differ', async () => {
  176. const ctx = new Context()
  177. await ctx.plugin(AgentRegistry)
  178. const agent = stubAgent('agent-id', { session: Session.create(SessionId('session-id')) })
  179. expect(() => ctx.agents.enter(agent, undefined))
  180. .toThrow('agent id "agent-id" does not match session id "session-id"')
  181. expect(ctx.agents.list()).toEqual([])
  182. })
  183. it('tracks runtime creator ownership separately from registry order', async () => {
  184. const ctx = new Context()
  185. await ctx.plugin(AgentRegistry)
  186. const root = stubAgent('root')
  187. const child = stubAgent('child')
  188. const detachRoot = ctx.agents.enter(root, undefined)
  189. ctx.agents.announce(root)
  190. const detachChild = ctx.agents.enter(child, root)
  191. ctx.agents.announce(child)
  192. expect(ctx.agents.list()).toEqual([root, child])
  193. expect(ctx.agents.roots()).toEqual([root])
  194. expect(ctx.agents.isOwnedBy(child.id, root)).toBe(true)
  195. expect(ctx.agents.isOwnedBy(root.id, root)).toBe(false)
  196. expect(ctx.agents.isOwnedBy(SessionId('missing'), root)).toBe(false)
  197. detachChild()
  198. expect(ctx.agents.isOwnedBy(child.id, root)).toBe(false)
  199. detachRoot()
  200. })
  201. it('rolls an entry back and pairs a partially delivered creation when a listener throws', async () => {
  202. const ctx = new Context()
  203. await ctx.plugin(AgentRegistry)
  204. const lifecycle: string[] = []
  205. ctx.on('agent/created', ({ agent }) => void lifecycle.push(`created:${agent.id}`))
  206. ctx.on('agent/created', () => { throw new Error('creation veto') })
  207. ctx.on('agent/disposed', ({ agent }) => void lifecycle.push(`disposed:${agent.id}`))
  208. expect(() => ctx.agents.register(stubAgent('vetoed'))).toThrow('creation veto')
  209. expect(ctx.agents.get(SessionId('vetoed'))).toBeUndefined()
  210. expect(lifecycle).toEqual(['created:vetoed', 'disposed:vetoed'])
  211. })
  212. it('contains asynchronous creation rejection and every disposal-listener failure', async () => {
  213. const ctx = new Context()
  214. await ctx.plugin(AgentRegistry)
  215. const warnings: string[] = []
  216. const heard: string[] = []
  217. ctx.logger.warn = ((message: unknown) => { warnings.push(String(message)) }) as typeof ctx.logger.warn
  218. ctx.on('agent/created', () => Promise.reject(new Error('created async')) as never)
  219. ctx.on('agent/disposed', () => { throw new Error('disposed sync') })
  220. ctx.on('agent/disposed', () => Promise.reject(new Error('disposed async')) as never)
  221. ctx.on('agent/disposed', ({ agent }) => void heard.push(agent.id))
  222. const dispose = ctx.agents.register(stubAgent('contained'))
  223. await Promise.resolve()
  224. dispose()
  225. await Promise.resolve()
  226. expect(heard).toEqual(['contained'])
  227. expect(warnings).toEqual([
  228. 'agent "contained": agent/created listener rejected: Error: created async',
  229. 'agent "contained": agent/disposed listener threw: Error: disposed sync',
  230. 'agent "contained": agent/disposed listener rejected: Error: disposed async',
  231. ])
  232. })
  233. it('separates entry from announcement and stale/idempotent detach cannot remove a replacement', async () => {
  234. const ctx = new Context()
  235. await ctx.plugin(AgentRegistry)
  236. const lifecycle: string[] = []
  237. ctx.on('agent/created', ({ agent }) => void lifecycle.push(`created:${agent.id}`))
  238. ctx.on('agent/disposed', ({ agent }) => void lifecycle.push(`disposed:${agent.id}`))
  239. const first = stubAgent('split')
  240. const detachFirst = ctx.agents.enter(first, undefined)
  241. expect(lifecycle).toEqual([])
  242. ctx.agents.announce(first)
  243. expect(() => { ctx.agents.announce(first) }).toThrow(/already announced/)
  244. detachFirst()
  245. detachFirst()
  246. const replacement = stubAgent('split')
  247. const detachReplacement = ctx.agents.enter(replacement, undefined)
  248. detachFirst()
  249. expect(ctx.agents.get(replacement.id)).toBe(replacement)
  250. expect(() => { ctx.agents.announce(first) }).toThrow(/not live/)
  251. detachReplacement()
  252. expect(lifecycle).toEqual(['created:split', 'disposed:split'])
  253. })
  254. it('defers detach requested by a creation listener until that dispatch unwinds', async () => {
  255. const ctx = new Context()
  256. await ctx.plugin(AgentRegistry)
  257. const order: string[] = []
  258. const agent = stubAgent('reentrant')
  259. ctx.on('agent/created', () => {
  260. order.push(`first:${ctx.agents.get(agent.id) === agent}`)
  261. detach()
  262. order.push(`after-detach:${ctx.agents.get(agent.id) === agent}`)
  263. })
  264. ctx.on('agent/created', () => void order.push(`second:${ctx.agents.get(agent.id) === agent}`))
  265. ctx.on('agent/disposed', () => void order.push('disposed'))
  266. const detach = ctx.agents.enter(agent, undefined)
  267. ctx.agents.announce(agent)
  268. expect(order).toEqual(['first:true', 'after-detach:true', 'second:true', 'disposed'])
  269. expect(ctx.agents.get(agent.id)).toBeUndefined()
  270. })
  271. })
  272. describe('agentEvents()', () => {
  273. it('contains each synchronous throw and returned-promise rejection', async () => {
  274. const ctx = new Context()
  275. const warnings: string[] = []
  276. const heard: string[] = []
  277. ctx.logger.warn = ((message: unknown) => { warnings.push(String(message)) }) as typeof ctx.logger.warn
  278. const agent = stubAgent('event')
  279. ctx.on('agent/status', () => { throw new Error('sync listener') })
  280. ctx.on('agent/status', () => Promise.reject(new Error('async listener')) as never)
  281. ctx.on('agent/status', ({ status }) => void heard.push(status))
  282. agentEvents(ctx, agent).emit('agent/status', { status: 'running' })
  283. await Promise.resolve()
  284. expect(heard).toEqual(['running'])
  285. expect(warnings).toEqual([
  286. 'agent event "agent/status" listener threw: Error: sync listener',
  287. 'agent event "agent/status" listener rejected: Error: async listener',
  288. ])
  289. })
  290. it('dispatches serial listeners with the fused agent subject', async () => {
  291. const ctx = new Context()
  292. const agent = stubAgent('serial-event')
  293. const signal = new AbortController().signal
  294. const heard: Array<{ agent: Agent; turn: number; signal: AbortSignal }> = []
  295. ctx.on('agent/turn-stopping', async ({ agent: subject, turn, signal: receivedSignal }) => {
  296. await Promise.resolve()
  297. heard.push({ agent: subject, turn, signal: receivedSignal })
  298. })
  299. await agentEvents(ctx, agent).serial('agent/turn-stopping', { turn: 3, signal })
  300. expect(heard).toEqual([{ agent, turn: 3, signal }])
  301. })
  302. it('injects the fused subject even when the payload carries a conflicting agent field', async () => {
  303. const ctx = new Context()
  304. const agent = stubAgent('fused-subject')
  305. const other = stubAgent('payload-agent')
  306. const heard: Agent[] = []
  307. ctx.on('agent/status', ({ agent: subject }) => void heard.push(subject))
  308. // A structurally acceptable payload may carry an extra `agent` field; the
  309. // dispatcher's injected subject must win over it.
  310. const payload: { status: AgentStatus; agent: Agent } = { status: 'running', agent: other }
  311. agentEvents(ctx, agent).emit('agent/status', payload)
  312. expect(heard).toEqual([agent])
  313. })
  314. })
  315. describe('explicit cancellation contract', () => {
  316. it('exposes the closed typed cancellation cause at the Agent seam', () => {
  317. expectTypeOf<Parameters<Agent['cancel']>[0]>().toEqualTypeOf<AgentCancelCause>()
  318. })
  319. })
  320. describe('AgentRegistry factory seam', () => {
  321. function stubFactory() {
  322. const calls: {
  323. create: Array<{ ownerCtx: Context; options: CreateAgentOptions }>
  324. resume: Array<{ ownerCtx: Context; options: ResumeAgentOptions }>
  325. } = { create: [], resume: [] }
  326. const factory: AgentFactory = {
  327. async createAgent(ownerCtx, options) {
  328. calls.create.push({ ownerCtx, options })
  329. return { agent: stubAgent(options.sessionId), dispose: () => Promise.resolve() }
  330. },
  331. async resume(ownerCtx, options) {
  332. calls.resume.push({ ownerCtx, options })
  333. return { agent: stubAgent(options.resumeSessionId), dispose: () => Promise.resolve() }
  334. },
  335. }
  336. return { factory, calls }
  337. }
  338. it('requires a factory and delegates through the calling context', async () => {
  339. const ctx = new Context()
  340. await ctx.plugin(AgentRegistry)
  341. await expect(ctx.agents.create({ sessionId: SessionId('s') })).rejects.toThrow(/no agent factory/)
  342. const { factory, calls } = stubFactory()
  343. ctx.agents.setFactory(factory)
  344. let callerFiber: Context['fiber'] | undefined
  345. await ctx.plugin(Object.assign(async (inner: Context) => {
  346. callerFiber = inner.fiber
  347. await inner.agents.create({ sessionId: SessionId('create-s') })
  348. await inner.agents.resume({ resumeSessionId: SessionId('resume-s') })
  349. }, { inject: ['agents'] }))
  350. expect(calls.create[0]?.ownerCtx.fiber).toBe(callerFiber)
  351. expect(calls.resume[0]?.ownerCtx.fiber).toBe(callerFiber)
  352. })
  353. it('rejects a second factory and clears the slot with its owner (HMR)', async () => {
  354. const ctx = new Context()
  355. await ctx.plugin(AgentRegistry)
  356. const owner = await ctx.plugin(Object.assign((inner: Context) => {
  357. inner.agents.setFactory(stubFactory().factory)
  358. expect(() => inner.agents.setFactory(stubFactory().factory)).toThrow(/already registered/)
  359. }, { inject: ['agents'] }))
  360. await expect(ctx.agents.create({ sessionId: SessionId('before-s') })).resolves.toBeDefined()
  361. await owner.dispose()
  362. await expect(ctx.agents.create({ sessionId: SessionId('after-s') })).rejects.toThrow(/no agent factory/)
  363. })
  364. it('canonicalizes an already traced Service before tracing it for the caller', async () => {
  365. const ctx = new Context()
  366. await ctx.plugin(AgentRegistry)
  367. const states = new WeakMap<object, string[]>()
  368. class TracedFactory extends Service implements AgentFactory {
  369. constructor(inner: Context) {
  370. super(inner, 'tracedFactory')
  371. states.set(this, [])
  372. }
  373. private calls(): string[] {
  374. const original = (this as unknown as { [symbols.original]?: TracedFactory })[symbols.original] ?? this
  375. const calls = states.get(original)
  376. if (calls === undefined) throw new Error('factory receiver was not canonicalized')
  377. return calls
  378. }
  379. async createAgent(_ownerCtx: Context, options: CreateAgentOptions) {
  380. this.calls().push('create')
  381. return { agent: stubAgent(options.sessionId), dispose: () => Promise.resolve() }
  382. }
  383. async resume(_ownerCtx: Context, options: ResumeAgentOptions) {
  384. this.calls().push('resume')
  385. return { agent: stubAgent(options.resumeSessionId), dispose: () => Promise.resolve() }
  386. }
  387. }
  388. await ctx.plugin(TracedFactory)
  389. const traced = (ctx as Context & { tracedFactory: TracedFactory }).tracedFactory
  390. ctx.agents.setFactory(traced)
  391. await ctx.agents.create({ sessionId: SessionId('create-s') })
  392. await ctx.agents.resume({ resumeSessionId: SessionId('resume-s') })
  393. const raw = (traced as unknown as { [symbols.original]?: TracedFactory })[symbols.original]
  394. expect(states.get(raw!)).toEqual(['create', 'resume'])
  395. })
  396. })