agent.spec.ts 17 KB

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