agent.spec.ts 12 KB

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