import { describe, expect, expectTypeOf, it } from 'vitest' import { Context, Service, symbols } from 'cordis' import type { Events } from 'cordis' import { Session, SessionId } from '@deepseek-ai/dsh-session' import AgentRegistry, { AgentMessageId, agentEvents, agentInterruptReasonOf, } from '@deepseek-ai/dsh-agent' import type { Agent, AgentCancelCause, AgentFactory, ContinuationStop, CreateAgentOptions, InjectOptions, ResolvedAgentInput, ResumeAgentOptions, SendOptions, } from '@deepseek-ai/dsh-agent' function stubAgent(rawId: string, overrides: Partial = {}): Agent { const id = SessionId(rawId) return { id, options: {}, session: new Session(id), status: 'idle', ctx: new Context(), followup: () => AgentMessageId('stub'), queue: () => AgentMessageId('stub'), steer: () => AgentMessageId('stub'), inject: () => AgentMessageId('stub'), send: () => AgentMessageId('stub'), cancel() {}, whenIdle() { return Promise.resolve() }, ...overrides, } } describe('AgentRegistry', () => { it('keeps helper options semantic and makes advanced input fully specified', () => { type OptionalInputKey = { [Key in keyof ResolvedAgentInput]-?: Record extends Pick ? Key : never }[keyof ResolvedAgentInput] expectTypeOf<'target' extends keyof SendOptions ? true : false>().toEqualTypeOf() expectTypeOf<'wakeup' extends keyof SendOptions ? true : false>().toEqualTypeOf() expectTypeOf<'contexts' extends keyof InjectOptions ? true : false>().toEqualTypeOf() expectTypeOf[0]>().toEqualTypeOf() expectTypeOf().toEqualTypeOf() expectTypeOf['contexts']>() .toEqualTypeOf<[]>() }) it('allows terminal stop policy to cooperate asynchronously with turn cancellation', () => { type TurnStopListener = Events['agent/turn-stop'] type AsyncTurnStopListener = () => Promise expectTypeOf().toExtend() expectTypeOf>>().toEqualTypeOf() }) it('registers exact entries, emits lifecycle events, and unregisters on owner disposal', async () => { const ctx = new Context() await ctx.plugin(AgentRegistry) const lifecycle: string[] = [] ctx.on('agent/created', agent => void lifecycle.push(`created:${agent.id}`)) ctx.on('agent/disposed', agent => void lifecycle.push(`disposed:${agent.id}`)) const agent = stubAgent('a1') const dispose = ctx.agents.register(agent) expect(ctx.agents.get(agent.id)).toBe(agent) expect(ctx.agents.list()).toEqual([agent]) expect(ctx.agents.roots()).toEqual([agent]) expect(() => ctx.agents.register(stubAgent('a1'))).toThrow(/already registered/) dispose() expect(ctx.agents.get(agent.id)).toBeUndefined() expect(lifecycle).toEqual(['created:a1', 'disposed:a1']) }) it('rejects an agent whose registry and session identities differ', async () => { const ctx = new Context() await ctx.plugin(AgentRegistry) const agent = stubAgent('agent-id', { session: new Session(SessionId('session-id')) }) expect(() => ctx.agents.enter(agent, undefined)) .toThrow('agent id "agent-id" does not match session id "session-id"') expect(ctx.agents.list()).toEqual([]) }) it('tracks runtime creator ownership separately from registry order', async () => { const ctx = new Context() await ctx.plugin(AgentRegistry) const root = stubAgent('root') const child = stubAgent('child') const detachRoot = ctx.agents.enter(root, undefined) ctx.agents.announce(root) const detachChild = ctx.agents.enter(child, root) ctx.agents.announce(child) expect(ctx.agents.list()).toEqual([root, child]) expect(ctx.agents.roots()).toEqual([root]) expect(ctx.agents.isOwnedBy(child.id, root)).toBe(true) expect(ctx.agents.isOwnedBy(root.id, root)).toBe(false) expect(ctx.agents.isOwnedBy(SessionId('missing'), root)).toBe(false) detachChild() expect(ctx.agents.isOwnedBy(child.id, root)).toBe(false) detachRoot() }) it('rolls an entry back and pairs a partially delivered creation when a listener throws', async () => { const ctx = new Context() await ctx.plugin(AgentRegistry) const lifecycle: string[] = [] ctx.on('agent/created', agent => void lifecycle.push(`created:${agent.id}`)) ctx.on('agent/created', () => { throw new Error('creation veto') }) ctx.on('agent/disposed', agent => void lifecycle.push(`disposed:${agent.id}`)) expect(() => ctx.agents.register(stubAgent('vetoed'))).toThrow('creation veto') expect(ctx.agents.get(SessionId('vetoed'))).toBeUndefined() expect(lifecycle).toEqual(['created:vetoed', 'disposed:vetoed']) }) it('contains asynchronous creation rejection and every disposal-listener failure', async () => { const ctx = new Context() await ctx.plugin(AgentRegistry) const warnings: string[] = [] const heard: string[] = [] ctx.logger.warn = ((message: unknown) => { warnings.push(String(message)) }) as typeof ctx.logger.warn ctx.on('agent/created', () => Promise.reject(new Error('created async')) as never) ctx.on('agent/disposed', () => { throw new Error('disposed sync') }) ctx.on('agent/disposed', () => Promise.reject(new Error('disposed async')) as never) ctx.on('agent/disposed', agent => void heard.push(agent.id)) const dispose = ctx.agents.register(stubAgent('contained')) await Promise.resolve() dispose() await Promise.resolve() expect(heard).toEqual(['contained']) expect(warnings).toEqual([ 'agent "contained": agent/created listener rejected: Error: created async', 'agent "contained": agent/disposed listener threw: Error: disposed sync', 'agent "contained": agent/disposed listener rejected: Error: disposed async', ]) }) it('separates entry from announcement and stale/idempotent detach cannot remove a replacement', async () => { const ctx = new Context() await ctx.plugin(AgentRegistry) const lifecycle: string[] = [] ctx.on('agent/created', agent => void lifecycle.push(`created:${agent.id}`)) ctx.on('agent/disposed', agent => void lifecycle.push(`disposed:${agent.id}`)) const first = stubAgent('split') const detachFirst = ctx.agents.enter(first, undefined) expect(lifecycle).toEqual([]) ctx.agents.announce(first) expect(() => { ctx.agents.announce(first) }).toThrow(/already announced/) detachFirst() detachFirst() const replacement = stubAgent('split') const detachReplacement = ctx.agents.enter(replacement, undefined) detachFirst() expect(ctx.agents.get(replacement.id)).toBe(replacement) expect(() => { ctx.agents.announce(first) }).toThrow(/not live/) detachReplacement() expect(lifecycle).toEqual(['created:split', 'disposed:split']) }) it('defers detach requested by a creation listener until that dispatch unwinds', async () => { const ctx = new Context() await ctx.plugin(AgentRegistry) const order: string[] = [] const agent = stubAgent('reentrant') ctx.on('agent/created', () => { order.push(`first:${ctx.agents.get(agent.id) === agent}`) detach() order.push(`after-detach:${ctx.agents.get(agent.id) === agent}`) }) ctx.on('agent/created', () => void order.push(`second:${ctx.agents.get(agent.id) === agent}`)) ctx.on('agent/disposed', () => void order.push('disposed')) const detach = ctx.agents.enter(agent, undefined) ctx.agents.announce(agent) expect(order).toEqual(['first:true', 'after-detach:true', 'second:true', 'disposed']) expect(ctx.agents.get(agent.id)).toBeUndefined() }) }) describe('agentEvents()', () => { it('contains each synchronous throw and returned-promise rejection', async () => { const ctx = new Context() const warnings: string[] = [] const heard: string[] = [] ctx.logger.warn = ((message: unknown) => { warnings.push(String(message)) }) as typeof ctx.logger.warn const agent = stubAgent('event') ctx.on('agent/status', () => { throw new Error('sync listener') }) ctx.on('agent/status', () => Promise.reject(new Error('async listener')) as never) ctx.on('agent/status', (_agent, status) => void heard.push(status)) agentEvents(ctx, agent).emit('agent/status', 'running') await Promise.resolve() expect(heard).toEqual(['running']) expect(warnings).toEqual([ 'agent event "agent/status" listener threw: Error: sync listener', 'agent event "agent/status" listener rejected: Error: async listener', ]) }) }) describe('explicit cancellation helpers', () => { it('exposes the closed typed cancellation cause at the Agent seam', () => { expectTypeOf[0]>().toEqualTypeOf() expectTypeOf[1]>().toEqualTypeOf() }) it('reads only supported reasons from an explicit signal', () => { const read = (reason: unknown) => { const controller = new AbortController() controller.abort(reason) return agentInterruptReasonOf(controller.signal) } const live = new AbortController() expect(agentInterruptReasonOf(live.signal)).toBeUndefined() expect(read({ kind: 'user' })).toEqual({ kind: 'user' }) expect(read({ kind: 'parent' })).toEqual({ kind: 'parent' }) const disposed = new AbortController() disposed.abort(Object.assign(Object.create(null) as object, { kind: 'disposed' })) const disposedReason = agentInterruptReasonOf(disposed.signal) expect(disposedReason).toEqual({ kind: 'disposed' }) expect(Object.isFrozen(disposedReason)).toBe(true) expect(read(null)).toBeUndefined() expect(read([])).toBeUndefined() expect(read('private runtime reason')).toBeUndefined() expect(read(new Error('private runtime reason'))).toBeUndefined() expect(read({ kind: 'user', detail: true })).toBeUndefined() expect(read({ other: 'user' })).toBeUndefined() expect(read({ kind: 'timeout' })).toBeUndefined() }) }) describe('AgentRegistry factory seam', () => { function stubFactory() { const calls: { create: Array<{ ownerCtx: Context; options: CreateAgentOptions }> resume: Array<{ ownerCtx: Context; options: ResumeAgentOptions }> } = { create: [], resume: [] } const factory: AgentFactory = { async createAgent(ownerCtx, options) { calls.create.push({ ownerCtx, options }) return { agent: stubAgent(options.sessionId), dispose: () => Promise.resolve() } }, async resume(ownerCtx, options) { calls.resume.push({ ownerCtx, options }) return { agent: stubAgent(options.resumeSessionId), dispose: () => Promise.resolve() } }, } return { factory, calls } } it('requires a factory and delegates through the calling context', async () => { const ctx = new Context() await ctx.plugin(AgentRegistry) await expect(ctx.agents.create({ sessionId: SessionId('s') })).rejects.toThrow(/no agent factory/) const { factory, calls } = stubFactory() ctx.agents.setFactory(factory) let callerFiber: Context['fiber'] | undefined await ctx.plugin(Object.assign(async (inner: Context) => { callerFiber = inner.fiber await inner.agents.create({ sessionId: SessionId('create-s') }) await inner.agents.resume({ resumeSessionId: SessionId('resume-s') }) }, { inject: ['agents'] })) expect(calls.create[0]?.ownerCtx.fiber).toBe(callerFiber) expect(calls.resume[0]?.ownerCtx.fiber).toBe(callerFiber) }) it('rejects a second factory and clears the slot with its owner (HMR)', async () => { const ctx = new Context() await ctx.plugin(AgentRegistry) const owner = await ctx.plugin(Object.assign((inner: Context) => { inner.agents.setFactory(stubFactory().factory) expect(() => inner.agents.setFactory(stubFactory().factory)).toThrow(/already registered/) }, { inject: ['agents'] })) await expect(ctx.agents.create({ sessionId: SessionId('before-s') })).resolves.toBeDefined() await owner.dispose() await expect(ctx.agents.create({ sessionId: SessionId('after-s') })).rejects.toThrow(/no agent factory/) }) it('canonicalizes an already traced Service before tracing it for the caller', async () => { const ctx = new Context() await ctx.plugin(AgentRegistry) const states = new WeakMap() class TracedFactory extends Service implements AgentFactory { constructor(inner: Context) { super(inner, 'tracedFactory') states.set(this, []) } private calls(): string[] { const original = (this as unknown as { [symbols.original]?: TracedFactory })[symbols.original] ?? this const calls = states.get(original) if (calls === undefined) throw new Error('factory receiver was not canonicalized') return calls } async createAgent(_ownerCtx: Context, options: CreateAgentOptions) { this.calls().push('create') return { agent: stubAgent(options.sessionId), dispose: () => Promise.resolve() } } async resume(_ownerCtx: Context, options: ResumeAgentOptions) { this.calls().push('resume') return { agent: stubAgent(options.resumeSessionId), dispose: () => Promise.resolve() } } } await ctx.plugin(TracedFactory) const traced = (ctx as Context & { tracedFactory: TracedFactory }).tracedFactory ctx.agents.setFactory(traced) await ctx.agents.create({ sessionId: SessionId('create-s') }) await ctx.agents.resume({ resumeSessionId: SessionId('resume-s') }) const raw = (traced as unknown as { [symbols.original]?: TracedFactory })[symbols.original] expect(states.get(raw!)).toEqual(['create', 'resume']) }) })