agent.spec.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. import { describe, expect, expectTypeOf, it } from 'vitest'
  2. import { Context, Service, symbols } from 'cordis'
  3. import type { Events } from 'cordis'
  4. import { Session, SessionId } from '@deepseek-ai/dsh-session'
  5. import AgentRegistry, {
  6. AgentMessageId,
  7. agentEvents,
  8. } from '@deepseek-ai/dsh-agent'
  9. import type {
  10. Agent,
  11. AgentCancelCause,
  12. AgentFactory,
  13. CreateAgentOptions,
  14. ResumeAgentOptions,
  15. } from '@deepseek-ai/dsh-agent'
  16. function stubAgent(rawId: string, overrides: Partial<Agent> = {}): Agent {
  17. const id = SessionId(rawId)
  18. const agent: Agent = {
  19. id,
  20. options: {},
  21. session: new Session(id),
  22. status: 'idle',
  23. acceptsNextStep: false,
  24. ctx: new Context(),
  25. send: () => AgentMessageId('stub'),
  26. followup: () => AgentMessageId('stub'),
  27. steer: () => AgentMessageId('stub'),
  28. inject: () => AgentMessageId('stub'),
  29. cancel() {},
  30. whenIdle() { return Promise.resolve() },
  31. }
  32. return Object.assign(agent, overrides)
  33. }
  34. describe('AgentRegistry', () => {
  35. it('registers exact entries, emits lifecycle events, and unregisters on owner disposal', async () => {
  36. const ctx = new Context()
  37. await ctx.plugin(AgentRegistry)
  38. const lifecycle: string[] = []
  39. ctx.on('agent/created', agent => void lifecycle.push(`created:${agent.id}`))
  40. ctx.on('agent/disposed', agent => void lifecycle.push(`disposed:${agent.id}`))
  41. const agent = stubAgent('a1')
  42. const dispose = ctx.agents.register(agent)
  43. expect(ctx.agents.get(agent.id)).toBe(agent)
  44. expect(ctx.agents.list()).toEqual([agent])
  45. expect(ctx.agents.roots()).toEqual([agent])
  46. expect(() => ctx.agents.register(stubAgent('a1'))).toThrow(/already registered/)
  47. dispose()
  48. expect(ctx.agents.get(agent.id)).toBeUndefined()
  49. expect(lifecycle).toEqual(['created:a1', 'disposed:a1'])
  50. })
  51. it('rejects an agent whose registry and session identities differ', async () => {
  52. const ctx = new Context()
  53. await ctx.plugin(AgentRegistry)
  54. const agent = stubAgent('agent-id', { session: new Session(SessionId('session-id')) })
  55. expect(() => ctx.agents.enter(agent, undefined))
  56. .toThrow('agent id "agent-id" does not match session id "session-id"')
  57. expect(ctx.agents.list()).toEqual([])
  58. })
  59. it('tracks runtime creator ownership separately from registry order', async () => {
  60. const ctx = new Context()
  61. await ctx.plugin(AgentRegistry)
  62. const root = stubAgent('root')
  63. const child = stubAgent('child')
  64. const detachRoot = ctx.agents.enter(root, undefined)
  65. ctx.agents.announce(root)
  66. const detachChild = ctx.agents.enter(child, root)
  67. ctx.agents.announce(child)
  68. expect(ctx.agents.list()).toEqual([root, child])
  69. expect(ctx.agents.roots()).toEqual([root])
  70. expect(ctx.agents.isOwnedBy(child.id, root)).toBe(true)
  71. expect(ctx.agents.isOwnedBy(root.id, root)).toBe(false)
  72. expect(ctx.agents.isOwnedBy(SessionId('missing'), root)).toBe(false)
  73. detachChild()
  74. expect(ctx.agents.isOwnedBy(child.id, root)).toBe(false)
  75. detachRoot()
  76. })
  77. it('rolls an entry back and pairs a partially delivered creation when a listener throws', async () => {
  78. const ctx = new Context()
  79. await ctx.plugin(AgentRegistry)
  80. const lifecycle: string[] = []
  81. ctx.on('agent/created', agent => void lifecycle.push(`created:${agent.id}`))
  82. ctx.on('agent/created', () => { throw new Error('creation veto') })
  83. ctx.on('agent/disposed', agent => void lifecycle.push(`disposed:${agent.id}`))
  84. expect(() => ctx.agents.register(stubAgent('vetoed'))).toThrow('creation veto')
  85. expect(ctx.agents.get(SessionId('vetoed'))).toBeUndefined()
  86. expect(lifecycle).toEqual(['created:vetoed', 'disposed:vetoed'])
  87. })
  88. it('contains asynchronous creation rejection and every disposal-listener failure', async () => {
  89. const ctx = new Context()
  90. await ctx.plugin(AgentRegistry)
  91. const warnings: string[] = []
  92. const heard: string[] = []
  93. ctx.logger.warn = ((message: unknown) => { warnings.push(String(message)) }) as typeof ctx.logger.warn
  94. ctx.on('agent/created', () => Promise.reject(new Error('created async')) as never)
  95. ctx.on('agent/disposed', () => { throw new Error('disposed sync') })
  96. ctx.on('agent/disposed', () => Promise.reject(new Error('disposed async')) as never)
  97. ctx.on('agent/disposed', agent => void heard.push(agent.id))
  98. const dispose = ctx.agents.register(stubAgent('contained'))
  99. await Promise.resolve()
  100. dispose()
  101. await Promise.resolve()
  102. expect(heard).toEqual(['contained'])
  103. expect(warnings).toEqual([
  104. 'agent "contained": agent/created listener rejected: Error: created async',
  105. 'agent "contained": agent/disposed listener threw: Error: disposed sync',
  106. 'agent "contained": agent/disposed listener rejected: Error: disposed async',
  107. ])
  108. })
  109. it('separates entry from announcement and stale/idempotent detach cannot remove a replacement', async () => {
  110. const ctx = new Context()
  111. await ctx.plugin(AgentRegistry)
  112. const lifecycle: string[] = []
  113. ctx.on('agent/created', agent => void lifecycle.push(`created:${agent.id}`))
  114. ctx.on('agent/disposed', agent => void lifecycle.push(`disposed:${agent.id}`))
  115. const first = stubAgent('split')
  116. const detachFirst = ctx.agents.enter(first, undefined)
  117. expect(lifecycle).toEqual([])
  118. ctx.agents.announce(first)
  119. expect(() => { ctx.agents.announce(first) }).toThrow(/already announced/)
  120. detachFirst()
  121. detachFirst()
  122. const replacement = stubAgent('split')
  123. const detachReplacement = ctx.agents.enter(replacement, undefined)
  124. detachFirst()
  125. expect(ctx.agents.get(replacement.id)).toBe(replacement)
  126. expect(() => { ctx.agents.announce(first) }).toThrow(/not live/)
  127. detachReplacement()
  128. expect(lifecycle).toEqual(['created:split', 'disposed:split'])
  129. })
  130. it('defers detach requested by a creation listener until that dispatch unwinds', async () => {
  131. const ctx = new Context()
  132. await ctx.plugin(AgentRegistry)
  133. const order: string[] = []
  134. const agent = stubAgent('reentrant')
  135. ctx.on('agent/created', () => {
  136. order.push(`first:${ctx.agents.get(agent.id) === agent}`)
  137. detach()
  138. order.push(`after-detach:${ctx.agents.get(agent.id) === agent}`)
  139. })
  140. ctx.on('agent/created', () => void order.push(`second:${ctx.agents.get(agent.id) === agent}`))
  141. ctx.on('agent/disposed', () => void order.push('disposed'))
  142. const detach = ctx.agents.enter(agent, undefined)
  143. ctx.agents.announce(agent)
  144. expect(order).toEqual(['first:true', 'after-detach:true', 'second:true', 'disposed'])
  145. expect(ctx.agents.get(agent.id)).toBeUndefined()
  146. })
  147. })
  148. describe('agentEvents()', () => {
  149. it('contains each synchronous throw and returned-promise rejection', async () => {
  150. const ctx = new Context()
  151. const warnings: string[] = []
  152. const heard: string[] = []
  153. ctx.logger.warn = ((message: unknown) => { warnings.push(String(message)) }) as typeof ctx.logger.warn
  154. const agent = stubAgent('event')
  155. ctx.on('agent/status', () => { throw new Error('sync listener') })
  156. ctx.on('agent/status', () => Promise.reject(new Error('async listener')) as never)
  157. ctx.on('agent/status', (_agent, status) => void heard.push(status))
  158. agentEvents(ctx, agent).emit('agent/status', 'running')
  159. await Promise.resolve()
  160. expect(heard).toEqual(['running'])
  161. expect(warnings).toEqual([
  162. 'agent event "agent/status" listener threw: Error: sync listener',
  163. 'agent event "agent/status" listener rejected: Error: async listener',
  164. ])
  165. })
  166. })
  167. describe('explicit cancellation contract', () => {
  168. it('exposes the closed typed cancellation cause at the Agent seam', () => {
  169. expectTypeOf<Parameters<Agent['cancel']>[0]>().toEqualTypeOf<AgentCancelCause>()
  170. expectTypeOf<Parameters<Events['agent/cancel-requested']>[1]>().toEqualTypeOf<AgentCancelCause>()
  171. })
  172. })
  173. describe('AgentRegistry factory seam', () => {
  174. function stubFactory() {
  175. const calls: {
  176. create: Array<{ ownerCtx: Context; options: CreateAgentOptions }>
  177. resume: Array<{ ownerCtx: Context; options: ResumeAgentOptions }>
  178. } = { create: [], resume: [] }
  179. const factory: AgentFactory = {
  180. async createAgent(ownerCtx, options) {
  181. calls.create.push({ ownerCtx, options })
  182. return { agent: stubAgent(options.sessionId), dispose: () => Promise.resolve() }
  183. },
  184. async resume(ownerCtx, options) {
  185. calls.resume.push({ ownerCtx, options })
  186. return { agent: stubAgent(options.resumeSessionId), dispose: () => Promise.resolve() }
  187. },
  188. }
  189. return { factory, calls }
  190. }
  191. it('requires a factory and delegates through the calling context', async () => {
  192. const ctx = new Context()
  193. await ctx.plugin(AgentRegistry)
  194. await expect(ctx.agents.create({ sessionId: SessionId('s') })).rejects.toThrow(/no agent factory/)
  195. const { factory, calls } = stubFactory()
  196. ctx.agents.setFactory(factory)
  197. let callerFiber: Context['fiber'] | undefined
  198. await ctx.plugin(Object.assign(async (inner: Context) => {
  199. callerFiber = inner.fiber
  200. await inner.agents.create({ sessionId: SessionId('create-s') })
  201. await inner.agents.resume({ resumeSessionId: SessionId('resume-s') })
  202. }, { inject: ['agents'] }))
  203. expect(calls.create[0]?.ownerCtx.fiber).toBe(callerFiber)
  204. expect(calls.resume[0]?.ownerCtx.fiber).toBe(callerFiber)
  205. })
  206. it('rejects a second factory and clears the slot with its owner (HMR)', async () => {
  207. const ctx = new Context()
  208. await ctx.plugin(AgentRegistry)
  209. const owner = await ctx.plugin(Object.assign((inner: Context) => {
  210. inner.agents.setFactory(stubFactory().factory)
  211. expect(() => inner.agents.setFactory(stubFactory().factory)).toThrow(/already registered/)
  212. }, { inject: ['agents'] }))
  213. await expect(ctx.agents.create({ sessionId: SessionId('before-s') })).resolves.toBeDefined()
  214. await owner.dispose()
  215. await expect(ctx.agents.create({ sessionId: SessionId('after-s') })).rejects.toThrow(/no agent factory/)
  216. })
  217. it('canonicalizes an already traced Service before tracing it for the caller', async () => {
  218. const ctx = new Context()
  219. await ctx.plugin(AgentRegistry)
  220. const states = new WeakMap<object, string[]>()
  221. class TracedFactory extends Service implements AgentFactory {
  222. constructor(inner: Context) {
  223. super(inner, 'tracedFactory')
  224. states.set(this, [])
  225. }
  226. private calls(): string[] {
  227. const original = (this as unknown as { [symbols.original]?: TracedFactory })[symbols.original] ?? this
  228. const calls = states.get(original)
  229. if (calls === undefined) throw new Error('factory receiver was not canonicalized')
  230. return calls
  231. }
  232. async createAgent(_ownerCtx: Context, options: CreateAgentOptions) {
  233. this.calls().push('create')
  234. return { agent: stubAgent(options.sessionId), dispose: () => Promise.resolve() }
  235. }
  236. async resume(_ownerCtx: Context, options: ResumeAgentOptions) {
  237. this.calls().push('resume')
  238. return { agent: stubAgent(options.resumeSessionId), dispose: () => Promise.resolve() }
  239. }
  240. }
  241. await ctx.plugin(TracedFactory)
  242. const traced = (ctx as Context & { tracedFactory: TracedFactory }).tracedFactory
  243. ctx.agents.setFactory(traced)
  244. await ctx.agents.create({ sessionId: SessionId('create-s') })
  245. await ctx.agents.resume({ resumeSessionId: SessionId('resume-s') })
  246. const raw = (traced as unknown as { [symbols.original]?: TracedFactory })[symbols.original]
  247. expect(states.get(raw!)).toEqual(['create', 'resume'])
  248. })
  249. })