agent.spec.ts 11 KB

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