# Conflicts: # .agents/notes/implemented/architecture/2026-06-21-bounded-llm-request-recovery.i18n.yaml # .agents/notes/implemented/feature/2026-06-18-compaction-capability-seam.i18n.yaml # .agents/notes/implemented/feature/2026-06-18-compaction-capability-seam.md # .agents/notes/implemented/feature/2026-06-18-compaction-capability-seam.zh.md # .agents/notes/implemented/feature/2026-07-06-sandbox.i18n.yaml # .agents/notes/implemented/feature/2026-07-06-sandbox.md # .agents/notes/implemented/feature/2026-07-06-sandbox.zh.md # .agents/notes/implemented/feature/2026-07-27-tmux-location-context.i18n.yaml # .agents/notes/implemented/simplification/2026-06-20-public-agent-stop-surface.i18n.yaml # .agents/notes/implemented/simplification/2026-07-28-remove-synthetic-log-only-turns.i18n.yaml # .agents/notes/implemented/simplification/2026-07-30-private-agent-send.i18n.yaml # docs/architecture.i18n.yaml # docs/architecture.md # docs/architecture.zh.md # docs/config-catalog.md # docs/cordis-catalog/events.md # docs/cordis-catalog/services.md # docs/core-data-structures/compaction.i18n.yaml # docs/core-data-structures/core.i18n.yaml # docs/core-data-structures/core.md # docs/core-data-structures/core.zh.md # docs/core-data-structures/llm-streaming.i18n.yaml # docs/core-data-structures/llm-streaming.md # docs/core-data-structures/llm-streaming.zh.md # docs/core-data-structures/session.i18n.yaml # docs/event-producer-consumer.md # docs/module-graph.md # docs/persistence-catalog.md # examples/acp-agent/tests/goal-snapshots/goal-session/session.expected.jsonl # examples/acp-agent/tests/snapshots/advanced-toolchain/session.1.jsonl # examples/acp-agent/tests/snapshots/advanced-toolchain/session.2.jsonl # examples/acp-agent/tests/snapshots/advanced-toolchain/session.jsonl # examples/acp-agent/tests/snapshots/bash-spill/session.jsonl # examples/acp-agent/tests/snapshots/bash-tool-turn/session.jsonl # examples/acp-agent/tests/snapshots/both-mode-turn/session.jsonl # examples/acp-agent/tests/snapshots/cancel-tool-calls/session.jsonl # examples/acp-agent/tests/snapshots/cancel/session.jsonl # examples/acp-agent/tests/snapshots/code-mode-turn/session.jsonl # examples/acp-agent/tests/snapshots/code-mode-workspace-context/session.jsonl # examples/acp-agent/tests/snapshots/cordis-inspect-jsdoc/session.jsonl # examples/acp-agent/tests/snapshots/empty-response-retry/session.jsonl # examples/acp-agent/tests/snapshots/error-finish/session.jsonl # examples/acp-agent/tests/snapshots/escalation-approved/session.jsonl # examples/acp-agent/tests/snapshots/escalation-rejected/session.jsonl # examples/acp-agent/tests/snapshots/fs-edit/session.jsonl # examples/acp-agent/tests/snapshots/fs-escalation-approved/session.jsonl # examples/acp-agent/tests/snapshots/fs-glob-sampling/session.jsonl # examples/acp-agent/tests/snapshots/fs-policy-reject/session.jsonl # examples/acp-agent/tests/snapshots/fs-read-window/session.jsonl # examples/acp-agent/tests/snapshots/fs-read/session.jsonl # examples/acp-agent/tests/snapshots/fs-write-overwrite/session.jsonl # examples/acp-agent/tests/snapshots/fs-write/session.jsonl # examples/acp-agent/tests/snapshots/hook-cc-invalid-matcher/session.jsonl # examples/acp-agent/tests/snapshots/hook-cc-posttool-block/session.jsonl # examples/acp-agent/tests/snapshots/hook-cc-posttool-context/session.jsonl # examples/acp-agent/tests/snapshots/hook-cc-pretool-ask/session.jsonl # examples/acp-agent/tests/snapshots/hook-cc-pretool-deny/session.jsonl # examples/acp-agent/tests/snapshots/hook-cc-promptsubmit-context/session.jsonl # examples/acp-agent/tests/snapshots/hook-cc-stop-continue/session.jsonl # examples/acp-agent/tests/snapshots/hook-codex-invalid-matcher/session.jsonl # examples/acp-agent/tests/snapshots/hook-codex-posttool-block/session.jsonl # examples/acp-agent/tests/snapshots/hook-codex-posttool-context/session.jsonl # examples/acp-agent/tests/snapshots/hook-codex-pretool-block/session.jsonl # examples/acp-agent/tests/snapshots/hook-codex-promptsubmit-context/session.jsonl # examples/acp-agent/tests/snapshots/hook-codex-stop-continue/session.jsonl # examples/acp-agent/tests/snapshots/lsp-definition/session.jsonl # examples/acp-agent/tests/snapshots/multi-turn/session.jsonl # examples/acp-agent/tests/snapshots/packed-chunks/session.jsonl # examples/acp-agent/tests/snapshots/parallel-tool-calls/session.jsonl # examples/acp-agent/tests/snapshots/pty-tools/session.jsonl # examples/acp-agent/tests/snapshots/repeat-tool-guard/session.jsonl # examples/acp-agent/tests/snapshots/session-query-spill/session.jsonl # examples/acp-agent/tests/snapshots/session-sandbox-root/session.jsonl # examples/acp-agent/tests/snapshots/session-title-after-turn/session.jsonl # examples/acp-agent/tests/snapshots/skill-load/session.jsonl # examples/acp-agent/tests/snapshots/subagent-depth-two-rejection/session.1.jsonl # examples/acp-agent/tests/snapshots/subagent-depth-two-rejection/session.2.jsonl # examples/acp-agent/tests/snapshots/subagent-depth-two-rejection/session.jsonl # examples/acp-agent/tests/snapshots/subagent-fork/session.1.jsonl # examples/acp-agent/tests/snapshots/subagent-fork/session.jsonl # examples/acp-agent/tests/snapshots/subagent-mixed/session.1.jsonl # examples/acp-agent/tests/snapshots/subagent-mixed/session.2.jsonl # examples/acp-agent/tests/snapshots/subagent-mixed/session.jsonl # examples/acp-agent/tests/snapshots/subagent-multi/session.1.jsonl # examples/acp-agent/tests/snapshots/subagent-multi/session.2.jsonl # examples/acp-agent/tests/snapshots/subagent-multi/session.jsonl # examples/acp-agent/tests/snapshots/subagent-spawn/session.1.jsonl # examples/acp-agent/tests/snapshots/subagent-spawn/session.jsonl # examples/acp-agent/tests/snapshots/text-turn/session.jsonl # examples/acp-agent/tests/snapshots/todo-write/session.jsonl # examples/acp-agent/tests/snapshots/tool-call-turn/session.jsonl # examples/acp-agent/tests/snapshots/web-fetch/session.jsonl # examples/acp-agent/tests/snapshots/workflow-run/session.1.jsonl # examples/acp-agent/tests/snapshots/workflow-run/session.jsonl # examples/acp-agent/tests/snapshots/workspace-context/session.jsonl # examples/acp-agent/tests/snapshots/workspace-edit/session.jsonl # examples/headless-agent/tests/semantic-checkpoint-snapshots/tool-outcome-unknown/session.expected.jsonl # examples/headless-agent/tests/snapshots/advanced-toolchain/session.1.jsonl # examples/headless-agent/tests/snapshots/advanced-toolchain/session.2.jsonl # examples/headless-agent/tests/snapshots/advanced-toolchain/session.jsonl # examples/headless-agent/tests/snapshots/advanced-toolchain/stream-json.expected.jsonl # examples/headless-agent/tests/snapshots/goal-tools/stream-json.expected.jsonl # examples/headless-agent/tests/snapshots/missing-credential/stream-json.expected.jsonl # examples/headless-agent/tests/snapshots/provider-retry/stream-json.expected.jsonl # examples/headless-agent/tests/snapshots/pty-tools/session.jsonl # examples/headless-agent/tests/snapshots/pty-tools/stream-json.expected.jsonl # examples/headless-agent/tests/snapshots/ralph-loop/stream-json.expected.jsonl # examples/headless-agent/tests/subagent-inheritance-snapshots/parent-override/child.expected.jsonl # examples/headless-agent/tests/subagent-inheritance-snapshots/parent-override/parent.expected.jsonl # examples/jsonrpc-agent/tests/snapshots/bash-tool/notifications.expected.jsonl # examples/jsonrpc-agent/tests/snapshots/bash-tool/session.jsonl # examples/jsonrpc-agent/tests/snapshots/persistent-tools/notifications.expected.jsonl # examples/jsonrpc-agent/tests/snapshots/persistent-tools/session.jsonl # examples/jsonrpc-agent/tests/snapshots/subagent-spawn/notifications.expected.jsonl # examples/jsonrpc-agent/tests/snapshots/subagent-spawn/session.1.jsonl # examples/jsonrpc-agent/tests/snapshots/subagent-spawn/session.jsonl # examples/jsonrpc-agent/tests/snapshots/text-turn/notifications.expected.jsonl # examples/jsonrpc-agent/tests/snapshots/text-turn/session.jsonl # packages/client/runtime/README.i18n.yaml # packages/client/runtime/src/client/sessions/request-inspection.ts # packages/compact/compact-basic/README.i18n.yaml # packages/compact/compact-basic/README.md # packages/compact/compact-basic/README.zh.md # packages/compact/compact-basic/src/index.ts # packages/context/time-context/tests/time-context.spec.ts # packages/context/tmux-context/README.i18n.yaml # packages/context/tmux-context/tests/tmux-context.spec.ts # packages/context/workspace-context/tests/workspace-context.spec.ts # packages/cordis/tool-cordis/src/api-catalog.ts # packages/core/agent-loop/README.i18n.yaml # packages/core/agent-loop/README.md # packages/core/agent-loop/README.zh.md # packages/core/agent-loop/src/agent.ts # packages/core/agent/README.i18n.yaml # packages/core/agent/README.md # packages/core/agent/README.zh.md # packages/core/agent/src/types.ts # packages/core/session/README.i18n.yaml # packages/core/session/README.md # packages/core/session/README.zh.md # packages/fs/tool-str-replace-editor/tests/tools.spec.ts # packages/goal/command-goal/tests/command-goal.spec.ts # packages/goal/goal/tests/goal.spec.ts # packages/host/apiproxy/README.i18n.yaml # packages/host/apiproxy/README.md # packages/host/apiproxy/README.zh.md # packages/host/apiproxy/src/api/index.ts # packages/host/apiproxy/tests/api-proxy-workspace.spec.ts # packages/llm/llm/README.i18n.yaml # packages/llm/llm/README.md # packages/llm/llm/README.zh.md # packages/llm/llm/src/index.ts # packages/pty/pty-local/tests/index.spec.ts # packages/pty/pty-local/tests/local.spec.ts # packages/pty/pty/tests/service.spec.ts # packages/pty/tool-bash-persistent/tests/loader-composition.spec.ts # packages/pty/tool-bash-persistent/tests/tools.spec.ts # packages/pty/tool-pty/tests/loader-composition.spec.ts # packages/pty/tool-pty/tests/tools.spec.ts # packages/session-persistence/session-checkpoint-policy/tests/crash-recovery.e2e.ts # packages/skill/tool-skill/tests/tool-skill.spec.ts # packages/tasks/tasks-local/tests/tasks.spec.ts # packages/ui/tui/README.i18n.yaml # packages/ui/tui/tests/tui.spec.ts # packages/ui/user-approval/src/index.ts # packages/ui/user-approval/tests/approval.spec.ts
356 lines
14 KiB
TypeScript
356 lines
14 KiB
TypeScript
import { describe, expect, expectTypeOf, it } from 'vitest'
|
|
import { Context, Service, symbols } from 'cordis'
|
|
import { createUserMessage, freezeMessage } from '@deepseek-ai/dsh-llm'
|
|
import { Session, SessionId, type UserMessage } from '@deepseek-ai/dsh-session'
|
|
import AgentRegistry, {
|
|
agentEvents,
|
|
Inbox,
|
|
} from '@deepseek-ai/dsh-agent'
|
|
|
|
import type {
|
|
Agent,
|
|
AgentCancelCause,
|
|
AgentFactory,
|
|
CreateAgentOptions,
|
|
ResumeAgentOptions,
|
|
} from '@deepseek-ai/dsh-agent'
|
|
|
|
function stubAgent(rawId: string, overrides: Partial<Agent> = {}): Agent {
|
|
const id = SessionId(rawId)
|
|
const session = new Session(id)
|
|
const agent: Agent = {
|
|
id,
|
|
options: {},
|
|
session,
|
|
inbox: new Inbox(session, { inserted: () => {}, discarded: () => {} }),
|
|
status: 'idle',
|
|
ctx: new Context(),
|
|
send: () => {},
|
|
followup: () => {},
|
|
steer: () => {},
|
|
inject: () => {},
|
|
reserveTurnAdmission: () => undefined,
|
|
cancel() {},
|
|
whenIdle: () => Promise.resolve(),
|
|
}
|
|
return Object.assign(agent, overrides)
|
|
}
|
|
|
|
describe('Inbox', () => {
|
|
it('rejects an invalid durable splice during reconstruction', () => {
|
|
const session = new Session(SessionId('invalid-inbox-replay'))
|
|
session.append('agent/inbox/spliced', {
|
|
target: 'next-turn',
|
|
start: 1,
|
|
inserted: [],
|
|
})
|
|
|
|
expect(() => new Inbox(session, { inserted: () => {}, discarded: () => {} }))
|
|
.toThrow('invalid persisted inbox splice at session seq 0')
|
|
})
|
|
|
|
it('updates a pending message by identity and reports a missing identity', () => {
|
|
const session = new Session(SessionId('update-inbox'))
|
|
const inbox = new Inbox(session, { inserted: () => {}, discarded: () => {} })
|
|
const original = createUserMessage({
|
|
content: [{ type: 'text', text: 'original' }],
|
|
source: { kind: 'user' },
|
|
})
|
|
const replacement = freezeMessage({
|
|
...original,
|
|
content: [{ type: 'text', text: 'replacement' }],
|
|
})
|
|
inbox.append('next-turn', original)
|
|
|
|
expect(inbox.update('next-turn', createUserMessage({
|
|
content: [{ type: 'text', text: 'missing' }],
|
|
source: { kind: 'user' },
|
|
}).id, replacement)).toBe(false)
|
|
expect(inbox.update('next-turn', original.id, replacement)).toBe(true)
|
|
expect(inbox.nextTurn).toEqual([replacement])
|
|
})
|
|
|
|
it('clears both pending lists as durable cancellations', () => {
|
|
const session = new Session(SessionId('clear-inbox'))
|
|
const discarded: UserMessage[] = []
|
|
const inbox = new Inbox(session, {
|
|
inserted: () => {},
|
|
discarded: message => void discarded.push(message),
|
|
})
|
|
const nextTurn = createUserMessage({ content: [{ type: 'text', text: 'turn' }], source: { kind: 'user' } })
|
|
const nextStep = createUserMessage({ content: [{ type: 'text', text: 'step' }], source: { kind: 'user' } })
|
|
inbox.append('next-turn', nextTurn)
|
|
inbox.append('next-step', nextStep)
|
|
const beforeClear = session.events.length
|
|
|
|
inbox.clear()
|
|
|
|
expect(inbox.hasPending).toBe(false)
|
|
expect(discarded).toEqual([nextStep, nextTurn])
|
|
expect(session.events.slice(beforeClear).map(event => event.type === 'agent/inbox/spliced'
|
|
? event.data
|
|
: event.type)).toEqual([
|
|
{ target: 'next-step', start: 0, removedCount: 1, inserted: [], outcome: 'canceled' },
|
|
{ target: 'next-turn', start: 0, removedCount: 1, inserted: [], outcome: 'canceled' },
|
|
])
|
|
|
|
inbox.clear()
|
|
expect(session.events).toHaveLength(beforeClear + 2)
|
|
})
|
|
})
|
|
|
|
describe('AgentRegistry', () => {
|
|
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',
|
|
])
|
|
})
|
|
|
|
it('dispatches serial listeners with the fused agent subject', async () => {
|
|
const ctx = new Context()
|
|
const agent = stubAgent('serial-event')
|
|
const signal = new AbortController().signal
|
|
const heard: Array<{ agent: Agent; turn: number; signal: AbortSignal }> = []
|
|
ctx.on('agent/turn-stopping', async (subject, turn, receivedSignal) => {
|
|
await Promise.resolve()
|
|
heard.push({ agent: subject, turn, signal: receivedSignal })
|
|
})
|
|
|
|
await agentEvents(ctx, agent).serial('agent/turn-stopping', 3, signal)
|
|
|
|
expect(heard).toEqual([{ agent, turn: 3, signal }])
|
|
})
|
|
})
|
|
|
|
describe('explicit cancellation contract', () => {
|
|
it('exposes the closed typed cancellation cause at the Agent seam', () => {
|
|
expectTypeOf<Parameters<Agent['cancel']>[0]>().toEqualTypeOf<AgentCancelCause>()
|
|
})
|
|
})
|
|
|
|
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<object, string[]>()
|
|
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'])
|
|
})
|
|
})
|