Files
deepseek-harness/packages/core/agent-loop/tests/scope-lifecycle.spec.ts
T
涂轶翔 101f26de4e fix(system-prompt): 保留 section API 的增量系统指令 (#6941)
* feat(system-prompt): admit section updates incrementally

* docs(system-prompt): accept retirement restart gap

* test(system-prompt): cover retirement and reentry before admission

* test(system-prompt): align rebase fixtures and persistence history

* fix: align section prompt consumers and CI fixtures

* test: pin credentials for section snapshot fixtures

* test: align remaining snapshots with section admission

* test: preserve section metadata in Web and PowerShell replays

* refactor(system-prompt): retire sections through Cordis cleanup

* chore: refresh section admission history after rebase

* fix(system-prompt): advance admission head after compaction

* fix(system-prompt): trim sections before admission hashing

* docs: move system upgrade guides to current version

* docs: add system message contribution cookbook

* perf(system-prompt): avoid indexing history for admission

* refactor(system-prompt): derive admission from logged sections

* test(system-prompt): update lifecycle and compaction consumers

* test(system-prompt): refresh CLI section event expectations

* test(system-prompt): refresh question composer section metadata

* feat(system-prompt): resolve same-name sections by scope

* refactor(persona): use ordinary section registrations

* refactor(system-prompt): clarify assembly and related control flow

* test(system-prompt): reconcile rebased section snapshots

* test(python): use current system text helper after rebase

* test(system-prompt): refresh CLI expected section blocks

* test(system-prompt): reconcile latest master integration

* test(agent-loop): seed tools before deferred addition assertion

* refactor(compaction): replace system heads when compacting prefixes

* refactor(system-prompt): separate source text and notice attribution

* fix(system-prompt): preserve legacy instructions in compaction snapshots

* refactor(compaction): build system snapshots while reading the summary prefix

* refactor(compaction): rebuild current system instructions

* refactor(system-prompt): defer compaction rebuild to admission

* refactor(system-prompt): remove redundant fixtures and setup

* fix(plan-mode): announce committed user transitions

* docs(system-prompt): reconcile section lifecycle and compaction design

* refactor(system-prompt): consolidate projection version increments

* fix(system-prompt): reconcile master integration and replay fixtures

* docs(system-prompt): align upgrade guide with current release

* refactor(system-prompt): make admission operations explicit

* fix(system-prompt): reconcile master API and release changes

* docs(system-prompt): regenerate catalogs after master refresh

* refactor(llm-pi-ai): delegate text rendering to pi-ai

* fix(llm-pi-ai): preserve blank lines between system text parts

* refactor(system-prompt): remove redundant retirement metadata

* refactor(system-prompt): own admission and use canonical surface targets

* refactor(system-prompt): compare captured sections at commitment

Assembly fixes section text and lifecycle; PromptAssembly.systemUpdates() compares them with the committed projection when the loop commits. This replaces SystemPrompt.admit(), needsRebuild() and isCurrent(), the SystemAdmission export, the loop's reassembly after compaction, and SessionSurface.systemHeadResetSeq. The projection records a pending rebuild as a boolean that an attributed reset clears.

After a compaction inside a step, the rebuilt head uses the sections captured for that step; later source changes arrive as ordinary updates at the next step.

* test: await the session read fixture and type a matcher for lint

* test(tool-executor-ptc): describe same-name section override on executor replacement

Duplicate section names no longer reject a scoped executor; the earlier registration is overridden and returns as an ordinary update when the executor leaves.

* docs(upgrade-guide): move system-prompt integrations to v0.2.2-rc.3

The root version on master is 0.2.2-rc.3; verify-upgrade-guides rejects a guide added under an earlier version directory.

* refactor(system-prompt): rebuild over system messages without sections

A system message without source.sections now marks rebuilding pending, like a compaction summary. The next model attempt replaces the head with current sections and clears later system messages. This removes the separate legacy flag and its appended whole-prompt replacement and notice.

Sessions written by earlier releases, migrated logs, and imported DeepSeek conversations take the same path, so the importer and its tests return to their master versions.

* test(web): refresh the imported-conversation recording and drop a stray bytecode file

The Web recording for a resumed DeepSeek import was recorded while the prompt was appended after the imported history; the head is replaced again, as on master. The .pyc under the macOS signing skill was staged by accident in an earlier merge.

* refactor(session): scan system nodes on read

surface.systemNodes is read only when a system rebuild is written. Scanning the current surface nodes on each read restores the surface fold's plan types and state to their master definitions, which no longer carry the system message.

* refactor(session): rename SystemSurfaceNode.hasContent to isEmpty

The flag reports that the logged content array has no blocks. isEmpty matches the documented "empty head" wording and covers a head that was written empty without ever being cleared.

* refactor(llm): join system text through extractTextContent

extractTextContent gains a trim option that trims each text block and omits blocks left empty. The DeepSeek serializer, the pi-ai converter, and the prompt inspector use it with a blank-line separator in place of three hand-written joins.

The pi-ai converter now trims system and developer text like the other two, so whitespace-only blocks are omitted there as well.

* test(snapshots): refresh the PowerShell and cordis-inspect recordings

The two PowerShell scenarios still held the initial system message as one unattributed block; replay now writes one block per section with its attribution. The cordis-inspect-jsdoc recording embeds the API catalog, which names SystemSurfaceNode.isEmpty since the rename.

* test(plan-mode,harness-dev-context): cover a rejected pre-step and a repeated legacy prompt

A rejected pre-step must leave a queued plan-mode switch pending and unannounced until the next accepted step. A second unattributed system message with the same legacy paragraphs must keep the admitted paragraphs.

* test(web): refresh Web recordings for section-attributed system messages

Twenty-seven Web recordings still held the initial system message as one unattributed block. Replay now writes one text block per section with its attribution; twenty-six recordings differ only in that line.

plan-review also records the plan-mode switch notice before the first prompt and appends a plan:status update on exit in place of a head replacement and a series header, so its expanded golden gains the notice row.

The Creator persona test joins the system text blocks with blank lines, as the adapters do, before matching the persona line.

* refactor(system-prompt): require the retry argument of systemUpdates

The agent loop passes it on every attempt. A custom loop that omitted it on a retry received a full comparison in place of the pending rebuild, with no diagnostic; the type now makes each caller state which attempt it is.

* docs(upgrade-guide): move the system prompt integrations guide to v0.2.2-rc.5

The root version is 0.2.2-rc.5 after the master merge, and verify-upgrade-guides rejects a guide added under an earlier version directory.

* test(web): refresh the mention path presence recording for section-attributed system messages

* test: align two specs that master left failing

The DeepSeek settings spec waited for a saved notice carrying the provider label from before the rename to DeepSeek API. The Windows packaging workflow spec seeded one of the two helpers that the Stage workflow helpers step copies.

* chore: remove a Python cache file committed by mistake
2026-11-19 21:11:38 +08:00

1194 lines
51 KiB
TypeScript

import * as NativeToolExecutor from '@deepseek-ai/dsh-tool-executor-native'
import { createUserMessage } from '@deepseek-ai/dsh-llm'
import { describe, expect, it, onTestFinished, vi } from 'vitest'
import { Context, symbols, type EffectMeta, type Fiber } from '@deepseek-ai/cordis'
import LlmRuntime from '@deepseek-ai/dsh-llm'
import SessionStore, { type SessionId, type SessionEvent } from '@deepseek-ai/dsh-session'
import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
import ToolRuntime from '@deepseek-ai/dsh-tools'
import { defineContentToolFixture } from '@deepseek-ai/dsh-tool-testkit'
import AgentRegistry, { agentEvents, assembleContextFor } from '@deepseek-ai/dsh-agent'
import type { Agent } from '@deepseek-ai/dsh-agent'
import { scopeOf } from '@deepseek-ai/dsh-scope'
import AgentLoop from '@deepseek-ai/dsh-agent-loop'
import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
import type { ContentBlock } from '@deepseek-ai/dsh-llm'
import { MockAdapter, textResponse } from './mock-adapter.ts'
import { brandString } from '@deepseek-ai/dsh-brand'
async function harnessWithLoop(adapter: MockAdapter = new MockAdapter([textResponse('ok')])): Promise<{ ctx: Context; loopFiber: Fiber }> {
const ctx = new Context()
await ctx.plugin(LlmRuntime)
await ctx.plugin(SessionStore)
await ctx.plugin(SessionProjectionRegistry)
await ctx.plugin(SystemPrompt, { personaPrefix: 'You are the deployment.' })
await ctx.plugin(ToolRuntime)
await ctx.plugin(NativeToolExecutor)
await ctx.plugin(AgentRegistry)
const loopFiber = await ctx.plugin(AgentLoop, { agents: [] })
ctx.llm.registerAdapter(['mock'], adapter)
return { ctx, loopFiber }
}
async function harness(adapter: MockAdapter = new MockAdapter([textResponse('ok')])): Promise<Context> {
return (await harnessWithLoop(adapter)).ctx
}
function waitForIdle(ctx: Context, agent: Agent): Promise<void> {
return new Promise((resolve) => {
const dispose = ctx.on('agent/status', ({ agent: subject, status }) => {
if (subject === agent && status === 'idle') {
dispose()
resolve()
}
})
})
}
const text = (t: string): ContentBlock[] => [{ type: 'text', text: t }]
/** Throw an arbitrary callback value to exercise the public unknown-error boundary. */
function throwUnknown(value: unknown): never {
throw value
}
/** Invoke the exact lifecycle effect to exercise same-stack reentrant teardown. */
function disposeCurrentLifecycle(ownerCtx: Context): void {
const lifecycle = [...ownerCtx.fiber._disposables]
.find((dispose) => {
const effect = (dispose as typeof dispose & { [symbols.effect]?: EffectMeta })[symbols.effect]
return effect?.label.startsWith('agentLoop.lifecycle(') === true
})
if (lifecycle === undefined) throw new Error('agent lifecycle effect not found')
void lifecycle()
}
describe('agent scope lifecycle', () => {
it('awaits serial creation before caller readiness', async () => {
const ctx = await harness()
const entered = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<undefined>()
const order: string[] = []
ctx.on('agent/created', async () => {
order.push('created:start')
entered.resolve(undefined)
await release.promise
order.push('created:end')
})
ctx.on('agent/created', () => { order.push('created:second') })
const creating = ctx.agentLoop.create(brandString<SessionId>('serial-start')).then((agent) => {
order.push('ready')
return agent
})
try {
await entered.promise
expect(order).toEqual(['created:start'])
release.resolve(undefined)
await creating
expect(order).toEqual(['created:start', 'created:end', 'created:second', 'ready'])
} finally {
release.resolve(undefined)
await ctx.fiber.dispose()
}
})
it('retains both entries and scoped effects until an asynchronous creation listener settles on owner unload', async () => {
const ctx = await harness()
const entered = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<undefined>()
let ownerCtx!: Context
const owner = await ctx.plugin(Object.assign((inner: Context) => { ownerCtx = inner }, { inject: ['agents'] }))
const order: string[] = []
const id = brandString<SessionId>('serial-owner-dispose')
ctx.on('agent/created', async ({ agent }) => {
entered.resolve(undefined)
await release.promise
expect(ctx.agents.get(id)).toBe(agent)
expect(ctx.sessions.get(id)).toBe(agent.session)
expect(order).toEqual([])
order.push('created:end')
})
ctx.on('agent/disposed', () => { order.push('agent-disposed') })
ctx.on('session/disposed', () => { order.push('session-disposed') })
const creating = ownerCtx.agents.create({
sessionId: id,
setup(agentCtx) { agentCtx.effect(() => () => { order.push('scope-disposed') }) },
})
const rejected = expect(creating).rejects.toThrow('owner disposed during setup')
try {
await entered.promise
const disposing = owner.dispose()
expect(ctx.agents.get(id)).toBeDefined()
release.resolve(undefined)
await rejected
await disposing
expect(order).toEqual(['created:end', 'scope-disposed', 'agent-disposed', 'session-disposed'])
expect(ctx.agents.get(id)).toBeUndefined()
expect(ctx.sessions.get(id)).toBeUndefined()
} finally {
release.resolve(undefined)
await ctx.fiber.dispose()
}
})
it('rolls back both registries and the scope when asynchronous creation fails', async () => {
const adapter = new MockAdapter([textResponse('unexpected')])
const ctx = await harness(adapter)
const reason = new Error('async creation veto')
const order: string[] = []
ctx.on('agent/created', async ({ agent }) => {
agent.followup(createUserMessage({ content: text('queued during creation'), source: { kind: 'user' } }))
await Promise.resolve()
throw reason
})
ctx.on('agent/created', () => { order.push('later-listener') })
ctx.on('agent/disposed', () => { order.push('agent-disposed') })
ctx.on('session/disposed', () => { order.push('session-disposed') })
await expect(ctx.agents.create({
sessionId: brandString<SessionId>('async-veto'),
setup(agentCtx) { agentCtx.effect(() => () => { order.push('scope-disposed') }) },
})).rejects.toBe(reason)
expect(order).toEqual(['scope-disposed', 'agent-disposed', 'session-disposed'])
expect(ctx.agents.list()).toEqual([])
expect(ctx.sessions.list()).toEqual([])
expect(adapter.requests).toHaveLength(0)
await ctx.fiber.dispose()
})
it('rejects an already-aborted creation signal before publishing either object', async () => {
const ctx = await harness()
const reason = new Error('cancelled before creation')
const controller = new AbortController()
controller.abort(reason)
await expect(ctx.agents.create({
sessionId: brandString<SessionId>('pre-aborted-s'),
signal: controller.signal,
})).rejects.toBe(reason)
expect(ctx.agents.get(brandString<SessionId>('pre-aborted-s'))).toBeUndefined()
expect(ctx.sessions.get(brandString<SessionId>('pre-aborted-s'))).toBeUndefined()
const valueController = new AbortController()
valueController.abort('plain cancellation reason')
await expect(ctx.agents.create({
sessionId: brandString<SessionId>('pre-aborted-value-s'),
signal: valueController.signal,
})).rejects.toMatchObject({
message: 'agent "pre-aborted-value-s" creation aborted',
cause: 'plain cancellation reason',
})
expect(ctx.agents.get(brandString<SessionId>('pre-aborted-value-s'))).toBeUndefined()
expect(ctx.sessions.get(brandString<SessionId>('pre-aborted-value-s'))).toBeUndefined()
await ctx.fiber.dispose()
})
it('joins cleanup when an abort lands reentrantly during scope preparation', async () => {
const ctx = await harness()
const reason = new Error('cancelled while preparing')
const controller = new AbortController()
let aborted = false
let scopeReleased = false
ctx.on('internal/plugin', (fiber) => {
if (aborted || fiber.name !== 'scope') return
aborted = true
fiber.ctx.effect(() => () => new Promise<void>((resolve) => {
setImmediate(() => {
scopeReleased = true
resolve()
})
}))
controller.abort(reason)
})
try {
await expect(ctx.agents.create({
sessionId: brandString<SessionId>('prepare-abort-s'),
signal: controller.signal,
})).rejects.toBe(reason)
expect(scopeReleased).toBe(true)
expect(ctx.agents.get(brandString<SessionId>('prepare-abort-s'))).toBeUndefined()
expect(ctx.sessions.get(brandString<SessionId>('prepare-abort-s'))).toBeUndefined()
} finally {
await ctx.fiber.dispose()
}
})
it('normalizes non-Error create failures for rollback while rethrowing the original value', async () => {
const ctx = await harness()
let thrown: unknown
ctx.on('session/created', () => {
if (thrown === undefined) return
const value = thrown
thrown = undefined
throwUnknown(value)
})
const createFailure = { source: 'create' }
thrown = createFailure
let createCaught: unknown
try {
await ctx.agentLoop.create(brandString<SessionId>('unknown-create'))
} catch (error: unknown) {
createCaught = error
}
expect(createCaught).toBe(createFailure)
const ownedFailure = { source: 'createAgent' }
thrown = ownedFailure
await expect(ctx.agents.create({
sessionId: brandString<SessionId>('unknown-owned-create-s'),
})).rejects.toBe(ownedFailure)
expect(ctx.agents.get(brandString<SessionId>('unknown-create'))).toBeUndefined()
expect(ctx.agents.get(brandString<SessionId>('unknown-owned-create-s'))).toBeUndefined()
await ctx.fiber.dispose()
})
it('tags agent.ctx with the Agent scope key', async () => {
const ctx = await harness()
const agent = await ctx.agentLoop.create(brandString<SessionId>('a1'), { provider: 'mock', model: 'mock' })
expect(scopeOf(agent.ctx)).toBe(agent)
await agent.whenIdle()
})
it('scoped registrations live in the agent world and die with the agent', async () => {
const ctx = await harness()
const handle = await ctx.agents.create({ sessionId: brandString<SessionId>('s1'), agentOptions: { provider: 'mock', model: 'mock' } })
const { agent } = handle
agent.ctx.systemPrompt.section({ name: 'test:scoped-persona', order: 0, text: 'You run tests.' })
agent.ctx.tools.register(defineContentToolFixture({
name: 'mine', description: 'scoped', parameters: {},
execute: () => Promise.resolve(text('ran')),
}))
const scopedAssembly = await ctx.systemPrompt.assemble(assembleContextFor(agent))
expect(scopedAssembly.sections.find(s => s.name === 'test:scoped-persona')?.text).toBe('You run tests.')
expect(scopedAssembly.tools.map(t => t.name)).toContain('mine')
// Other assemblies are untouched.
const globalAssembly = await ctx.systemPrompt.assemble()
expect(globalAssembly.sections.find(s => s.name === 'deployment:persona-prefix')?.text).toBe('You are the deployment.')
expect(globalAssembly.sections.find(s => s.name === 'test:scoped-persona')).toBeUndefined()
expect(globalAssembly.tools.map(t => t.name)).not.toContain('mine')
await handle.dispose()
// The scoped world unwound with the agent: nothing leaked into the registries.
expect(ctx.tools.get('mine', agent)).toBeUndefined()
const after = await ctx.systemPrompt.assemble({ agent, scope: agent })
expect(after.sections.find(s => s.name === 'deployment:persona-prefix')?.text).toBe('You are the deployment.')
expect(after.sections.find(s => s.name === 'test:scoped-persona')).toBeUndefined()
})
it('owns the inbox projection until AgentLoop unloads', async () => {
const { ctx, loopFiber } = await harnessWithLoop()
onTestFinished(() => ctx.fiber.dispose())
const cold = ctx.sessions.create(brandString<SessionId>('projection-before-any-agent'))
expect(ctx.sessionProjections.checkpoint(cold).inbox?.val).toEqual({ 'next-turn': [], 'next-step': [] })
let first!: Awaited<ReturnType<typeof ctx.agents.create>>
let second!: Awaited<ReturnType<typeof ctx.agents.create>>
const firstOwner = await ctx.plugin(Object.assign(async (inner: Context) => {
first = await inner.agents.create({
sessionId: brandString<SessionId>('projection-owner-first'),
agentOptions: { provider: 'mock', model: 'mock' },
})
}, { inject: ['agents'] }))
const secondOwner = await ctx.plugin(Object.assign(async (inner: Context) => {
second = await inner.agents.create({
sessionId: brandString<SessionId>('projection-owner-second'),
agentOptions: { provider: 'mock', model: 'mock' },
})
}, { inject: ['agents'] }))
expect(ctx.sessionProjections.checkpoint(first.agent.session).inbox?.val).toBeDefined()
await firstOwner.dispose()
expect(ctx.sessionProjections.checkpoint(second.agent.session).inbox?.val).toBeDefined()
await secondOwner.dispose()
expect(ctx.sessionProjections.checkpoint(second.agent.session).inbox?.val).toBeDefined()
await Promise.all([first.dispose(), second.dispose()])
const row = ctx.sessionProjections.checkpoint(second.agent.session).inbox
const coldRow = ctx.sessionProjections.checkpoint(cold).inbox
await loopFiber.dispose()
cold.append('turn/start', { turn: 1 })
// The released unit keeps each Session's last row and folds no event after the unload.
expect(ctx.sessionProjections.checkpoint(second.agent.session)).toHaveProperty('inbox', row)
expect(ctx.sessionProjections.checkpoint(cold)).toHaveProperty('inbox', coldRow)
expect(ctx.sessionProjections.checkpoint(ctx.sessions.create(brandString<SessionId>('projection-after-unload')))).not.toHaveProperty('inbox')
})
it('agent.ctx listeners hear only their own agent (scoped dispatch end to end)', async () => {
const ctx = await harness(new MockAdapter([textResponse('one'), textResponse('two')]))
const a = await ctx.agentLoop.create(brandString<SessionId>('a'), { provider: 'mock', model: 'mock' })
const b = await ctx.agentLoop.create(brandString<SessionId>('b'), { provider: 'mock', model: 'mock' })
const heard: string[] = []
a.ctx.on('agent/status', ({ agent: subject, status }) => void heard.push(`a-sees:${subject.id}:${status}`))
a.ctx.on('session/event', (_s, event) => {
if (event.type === 'user/message') heard.push('a-sees:user-message')
})
b.followup(createUserMessage({ content: text('for b'), source: { kind: 'user' } }))
await waitForIdle(ctx, b)
expect(heard).toEqual([]) // nothing of b's leaked into a's scope
a.followup(createUserMessage({ content: text('for a'), source: { kind: 'user' } }))
await waitForIdle(ctx, a)
expect(heard).toContain('a-sees:a:running')
expect(heard).toContain('a-sees:user-message')
})
it('runs setup in the guaranteed slot: scoped world complete before agent/created and the first assembly', async () => {
const ctx = await harness()
const order: string[] = []
ctx.on('agent/created', ({ agent }) => {
order.push('agent/created')
// The scoped section is already registered by the time agent/created fires.
void ctx.systemPrompt.assemble(assembleContextFor(agent)).then((assembly) => {
order.push(`persona:${assembly.sections.find(s => s.name === 'test:scoped-persona')?.text}`)
})
})
const handle = await ctx.agents.create({
sessionId: brandString<SessionId>('child-s'),
agentOptions: { provider: 'mock', model: 'mock' },
setup: async (agentCtx) => {
order.push('setup')
await Promise.resolve()
agentCtx.systemPrompt.section({ name: 'test:scoped-persona', order: 0, text: 'You are the child.' })
},
})
expect(order).toEqual(['setup', 'agent/created', 'persona:You are the child.'])
await handle.dispose()
})
it('announces the Session before setup and the Agent after setup completes', async () => {
const ctx = await harness()
const gate = Promise.withResolvers<undefined>()
const setupStarted = Promise.withResolvers<undefined>()
const order: string[] = []
ctx.on('session/created', (session) => {
expect(ctx.sessions.get(session.id)).toBe(session)
expect(ctx.agents.get(session.id)?.session).toBeUndefined()
order.push('session/created')
})
ctx.on('agent/created', () => void order.push('agent/created'))
const acceptedOptions = { provider: 'mock', model: 'mock' }
const creating = ctx.agents.create({
sessionId: brandString<SessionId>('atomic'),
agentOptions: acceptedOptions,
setup: async (agentCtx, agent) => {
expect(agent.id).toBe(brandString<SessionId>('atomic'))
agentCtx.on('agent/created', () => void order.push('setup-listener:agent/created'))
order.push('setup:start')
setupStarted.resolve(undefined)
await gate.promise
order.push('setup:end')
return {
commit: () => {
expect(ctx.agents.get(brandString<SessionId>('atomic'))).toBeUndefined()
expect(ctx.sessions.get(brandString<SessionId>('atomic'))?.id).toBe(brandString<SessionId>('atomic'))
order.push('setup:commit')
},
}
},
})
await setupStarted.promise
expect(ctx.agents.get(brandString<SessionId>('atomic'))).toBeUndefined()
expect(ctx.sessions.get(brandString<SessionId>('atomic'))?.id).toBe(brandString<SessionId>('atomic'))
expect(order).toEqual(['session/created', 'setup:start'])
gate.resolve(undefined)
const handle = await creating
expect(handle.agent.options).toBe(acceptedOptions)
expect(order).toEqual([
'session/created',
'setup:start',
'setup:end',
'setup:commit',
'agent/created',
'setup-listener:agent/created',
])
await handle.dispose()
})
it('rejects a concurrent same-id creation before its setup starts', async () => {
const ctx = await harness()
const gate = Promise.withResolvers<undefined>()
const setupStarted = Promise.withResolvers<undefined>()
const sessionId = brandString<SessionId>('concurrent-enter')
const first = ctx.agents.create({
sessionId,
agentOptions: { provider: 'mock', model: 'mock' },
setup: async () => {
setupStarted.resolve(undefined)
await gate.promise
},
})
await setupStarted.promise
const session = ctx.sessions.get(sessionId)
expect(session).toBeDefined()
const secondSetup = vi.fn()
await expect(ctx.agents.create({
sessionId,
agentOptions: { provider: 'mock', model: 'mock' },
setup: secondSetup,
})).rejects.toThrow(/already exists/)
expect(secondSetup).not.toHaveBeenCalled()
expect(ctx.agents.list()).toEqual([])
expect(ctx.sessions.list()).toEqual([session])
gate.resolve(undefined)
const handle = await first
expect(handle.agent.session).toBe(session)
await handle.dispose()
expect(ctx.agents.list()).toEqual([])
expect(ctx.sessions.list()).toEqual([])
})
it('uses signal only for creation: aborts pending setup but not a returned live handle', async () => {
const adapter = new MockAdapter([textResponse('ok')])
const ctx = await harness(adapter)
onTestFinished(() => ctx.fiber.dispose())
const pendingController = new AbortController()
const setupStarted = Promise.withResolvers<undefined>()
const pending = ctx.agents.create({
sessionId: brandString<SessionId>('signal-pending-s'),
agentOptions: { provider: 'mock', model: 'mock' },
signal: pendingController.signal,
setup: async () => {
setupStarted.resolve(undefined)
await new Promise<never>(() => {})
},
})
await setupStarted.promise
pendingController.abort(new Error('cancel pending creation'))
await expect(pending).rejects.toThrow('cancel pending creation')
expect(ctx.agents.get(brandString<SessionId>('signal-pending-s'))).toBeUndefined()
expect(ctx.sessions.get(brandString<SessionId>('signal-pending-s'))).toBeUndefined()
const liveController = new AbortController()
const live = await ctx.agents.create({
sessionId: brandString<SessionId>('signal-live-s'),
agentOptions: { provider: 'mock', model: 'mock' },
signal: liveController.signal,
})
liveController.abort(new Error('too late'))
await Promise.resolve()
expect(ctx.agents.get(live.agent.id)).toBe(live.agent)
expect(live.agent.status).toBe('idle')
live.agent.followup(createUserMessage({ content: text('continue'), source: { kind: 'user' } }))
await live.agent.whenIdle()
expect(adapter.requests).toHaveLength(1)
await live.dispose()
})
it('owner unload aborts pending setup and disposes the announced Session', async () => {
const ctx = await harness()
const gate = Promise.withResolvers<undefined>()
const setupStarted = Promise.withResolvers<undefined>()
const published: string[] = []
ctx.on('session/created', () => void published.push('session/created'))
ctx.on('session/disposed', () => void published.push('session/disposed'))
ctx.on('agent/created', () => void published.push('agent/created'))
let creating!: ReturnType<typeof ctx.agents.create>
const owner = await ctx.plugin(Object.assign((inner: Context) => {
creating = inner.agents.create({
sessionId: brandString<SessionId>('owner-race-s'),
agentOptions: { provider: 'mock', model: 'mock' },
setup: async () => {
setupStarted.resolve(undefined)
await gate.promise
},
})
}, { inject: ['agents'] }))
await setupStarted.promise
await owner.dispose()
await expect(creating).rejects.toThrow(/owner disposed during setup/)
expect(published).toEqual(['session/created', 'session/disposed'])
expect(ctx.agents.get(brandString<SessionId>('owner-race-s'))).toBeUndefined()
expect(ctx.sessions.get(brandString<SessionId>('owner-race-s'))).toBeUndefined()
// Let the losing callback settle; Promise.race already observes it.
gate.resolve(undefined)
await Promise.resolve()
// The other ordering in the same race: setup resolves first (its reaction
// is queued), then owner disposal flips active before that continuation can
// publish. The post-race active check must still reject.
const gate2 = Promise.withResolvers<undefined>()
const setupStarted2 = Promise.withResolvers<undefined>()
let creating2!: ReturnType<typeof ctx.agents.create>
const owner2 = await ctx.plugin(Object.assign((inner: Context) => {
creating2 = inner.agents.create({
sessionId: brandString<SessionId>('owner-race-s-2'),
agentOptions: { provider: 'mock', model: 'mock' },
setup: async () => {
setupStarted2.resolve(undefined)
await gate2.promise
},
})
}, { inject: ['agents'] }))
await setupStarted2.promise
gate2.resolve(undefined)
const unload2 = owner2.dispose()
await expect(creating2).rejects.toThrow(/owner disposed during setup/)
await unload2
expect(ctx.agents.get(brandString<SessionId>('owner-race-s-2'))).toBeUndefined()
expect(ctx.sessions.get(brandString<SessionId>('owner-race-s-2'))).toBeUndefined()
})
it('an AgentLoop unload aborts pending setup, awaits cleanup, and releases both ids', async () => {
const { ctx, loopFiber } = await harnessWithLoop()
const gate = Promise.withResolvers<undefined>()
const setupStarted = Promise.withResolvers<undefined>()
const published: string[] = []
ctx.on('session/created', () => void published.push('session/created'))
ctx.on('session/disposed', () => void published.push('session/disposed'))
ctx.on('agent/created', () => void published.push('agent/created'))
const creating = ctx.agents.create({
sessionId: brandString<SessionId>('factory-setup-race-s'),
agentOptions: { provider: 'mock', model: 'mock' },
setup: async () => {
setupStarted.resolve(undefined)
await gate.promise
},
})
await setupStarted.promise
await loopFiber.dispose()
await expect(creating).rejects.toThrow(/agent loop is not active/)
expect(published).toEqual(['session/created', 'session/disposed'])
expect(ctx.agents.get(brandString<SessionId>('factory-setup-race-s'))).toBeUndefined()
expect(ctx.sessions.get(brandString<SessionId>('factory-setup-race-s'))).toBeUndefined()
gate.resolve(undefined)
await ctx.fiber.dispose()
})
it('factory unload during scope minting prevents setup and drains cleanup', async () => {
const { ctx, loopFiber } = await harnessWithLoop()
let unloaded = false
let setupCalls = 0
ctx.on('internal/plugin', (fiber) => {
if (unloaded || fiber.name !== 'scope') return
unloaded = true
void loopFiber.dispose()
})
const creating = ctx.agents.create({
sessionId: brandString<SessionId>('factory-scope-race-s'),
agentOptions: { provider: 'mock', model: 'mock' },
setup: () => { setupCalls += 1 },
})
await expect(creating).rejects.toThrow(/agent loop is not active/)
await loopFiber.dispose()
expect(setupCalls).toBe(0)
expect(ctx.agents.get(brandString<SessionId>('factory-scope-race-s'))).toBeUndefined()
expect(ctx.sessions.get(brandString<SessionId>('factory-scope-race-s'))).toBeUndefined()
await ctx.fiber.dispose()
})
it('caller unload during scope minting owns and drains the half-built child', async () => {
const ctx = await harness()
const gate = Promise.withResolvers<undefined>()
const cleanupStarted = Promise.withResolvers<undefined>()
let ownerFiber!: Fiber
let ownerDisposal!: Promise<void>
let scopeFiber: Fiber | undefined
let creating!: ReturnType<typeof ctx.agents.create>
ctx.on('internal/plugin', (fiber) => {
if (fiber.name !== 'scope' || scopeFiber !== undefined) return
scopeFiber = fiber
fiber.ctx.effect(() => async () => {
cleanupStarted.resolve(undefined)
await gate.promise
})
ownerDisposal = ownerFiber.dispose()
})
const owner = ctx.plugin(Object.assign((inner: Context) => {
ownerFiber = inner.fiber
creating = inner.agents.create({
sessionId: brandString<SessionId>('caller-scope-race-s'),
agentOptions: { provider: 'mock', model: 'mock' },
})
}, { inject: ['agents'] }))
await cleanupStarted.promise
let ownerSettled = false
void ownerDisposal.then(() => { ownerSettled = true })
await Promise.resolve()
expect(ownerSettled).toBe(false)
gate.resolve(undefined)
await expect(creating).rejects.toThrow(/owner disposed during setup/)
await ownerDisposal
await owner
expect(scopeFiber?.uid).toBeNull()
expect(ctx.agents.get(brandString<SessionId>('caller-scope-race-s'))).toBeUndefined()
expect(ctx.sessions.get(brandString<SessionId>('caller-scope-race-s'))).toBeUndefined()
await owner.dispose()
await ctx.fiber.dispose()
})
it('create rechecks provider liveness before its first publication edge', async () => {
const { ctx, loopFiber } = await harnessWithLoop()
const sessionsBefore = ctx.sessions.list().length
let unloaded = false
let unloading!: Promise<void>
ctx.on('internal/plugin', (fiber) => {
if (unloaded || fiber.name !== 'scope') return
unloaded = true
unloading = loopFiber.dispose()
})
// The mid-setup unload races publication: create either rejects or its
// published agent is torn straight back down — both leave no state.
await ctx.agentLoop.create(brandString<SessionId>('config-scope-race'), { provider: 'mock', model: 'mock' })
.then(() => undefined, () => undefined)
await unloading
expect(ctx.agents.get(brandString<SessionId>('config-scope-race')) === undefined).toBe(true)
expect(ctx.sessions.list().length).toBe(sessionsBefore)
await ctx.fiber.dispose()
})
it('create leaves no lifecycle state when session preparation fails', async () => {
const ctx = await harness()
const id = brandString<SessionId>('config-prepare-failure')
await expect(ctx.agentLoop.create(id, { provider: 'mock', model: 'mock' }, { cwd: 'relative' }))
.rejects.toThrow(/absolute path/)
const replacement = await ctx.agentLoop.create(id, { provider: 'mock', model: 'mock' }, { cwd: '/recovered' })
expect(ctx.agents.get(id)).toBe(replacement)
await replacement.whenIdle()
await ctx.fiber.dispose()
})
it('factory unload awaits provisional cleanup when scope preparation throws', async () => {
const { ctx, loopFiber } = await harnessWithLoop()
let triggered = false
ctx.on('internal/plugin', (fiber) => {
if (triggered || fiber.name !== 'scope') return
triggered = true
void loopFiber.dispose()
throw new Error('scope preparation failed')
})
await expect(ctx.agents.create({
sessionId: brandString<SessionId>('factory-scope-throw-s'),
agentOptions: { provider: 'mock', model: 'mock' },
})).rejects.toThrow('scope preparation failed')
await loopFiber.dispose()
expect(ctx.agents.get(brandString<SessionId>('factory-scope-throw-s'))).toBeUndefined()
expect(ctx.sessions.get(brandString<SessionId>('factory-scope-throw-s'))).toBeUndefined()
await ctx.fiber.dispose()
})
it('AgentLoop unload is a structural co-owner of every live programmatic agent', async () => {
const { ctx, loopFiber } = await harnessWithLoop()
const loop = ctx.agentLoop
const sessionId = brandString<SessionId>('factory-live')
const handle = await ctx.agents.create({
sessionId: brandString<SessionId>('factory-live-s'),
agentOptions: { provider: 'mock', model: 'mock' },
})
await loopFiber.dispose()
expect(handle.agent.status).toBe('idle')
expect(ctx.agents.get(sessionId)).toBeUndefined()
expect(ctx.sessions.get(sessionId)).toBeUndefined()
expect(ctx.fiber.getEffects().filter(effect => effect.label === `agentLoop.lifecycle(${sessionId})`)).toEqual([])
// The consumer handle shares the provider's completed quiescence boundary.
await handle.dispose()
await expect(loop.createAgent(ctx, {
sessionId: brandString<SessionId>('factory-inactive-s'),
})).rejects.toThrow(/agent loop is not active|inactive context/)
await ctx.fiber.dispose()
})
it('keeps AgentLoop dependencies available when the caller injects only agents', async () => {
const ctx = await harness()
let creating!: ReturnType<typeof ctx.agents.create>
const owner = await ctx.plugin(Object.assign((inner: Context) => {
creating = inner.agents.create({
sessionId: brandString<SessionId>('dependency-origin-s'),
agentOptions: { provider: 'mock', model: 'mock' },
setup: (agentCtx) => {
agentCtx.tools.register(defineContentToolFixture({
name: 'dependency-origin-tool',
description: 'proves AgentLoop dependency origin',
parameters: {},
execute: () => Promise.resolve(text('ok')),
}))
agentCtx.systemPrompt.section({
name: 'dependency-origin-section',
order: 1,
text: 'factory dependency API',
})
},
})
}, { inject: ['agents'] }))
const handle = await creating
const assembly = await ctx.systemPrompt.assemble(assembleContextFor(handle.agent))
expect(assembly.tools.map(tool => tool.name)).toContain('dependency-origin-tool')
expect(assembly.sections.map(section => section.name)).toContain('dependency-origin-section')
await handle.dispose()
await owner.dispose()
await ctx.fiber.dispose()
})
it('keeps the Session live through reentrant session/created teardown without starting setup', async () => {
const ctx = await harness()
let ownerCtx!: Context
let creating!: ReturnType<typeof ctx.agents.create>
const lifecycle: string[] = []
const setup = vi.fn()
ctx.on('session/created', (session) => {
if (session.id !== brandString<SessionId>('session-created-barrier-s')) return
lifecycle.push('session-created:dispose')
disposeCurrentLifecycle(ownerCtx)
})
ctx.on('session/created', (session) => {
if (session.id !== brandString<SessionId>('session-created-barrier-s')) return
const agent = ctx.agents.get(brandString<SessionId>('session-created-barrier-s'))
expect(ctx.sessions.get(session.id)).toBe(session)
expect(agent).toBeUndefined()
lifecycle.push('session-created:observer')
})
ctx.on('agent/created', () => void lifecycle.push('agent-created'))
ctx.on('agent/disposed', () => void lifecycle.push('agent-disposed'))
ctx.on('session/disposed', (session) => {
if (session.id === brandString<SessionId>('session-created-barrier-s')) lifecycle.push('session-disposed')
})
const owner = await ctx.plugin(Object.assign((inner: Context) => {
ownerCtx = inner
creating = inner.agents.create({
sessionId: brandString<SessionId>('session-created-barrier-s'),
setup,
agentOptions: { provider: 'mock', model: 'mock' },
})
}, { inject: ['agents'] }))
await expect(creating).rejects.toThrow(/owner disposed during setup/)
await owner.dispose()
expect(setup).not.toHaveBeenCalled()
expect(lifecycle).toEqual([
'session-created:dispose',
'session-created:observer',
'session-disposed',
])
expect(ctx.agents.get(brandString<SessionId>('session-created-barrier-s'))).toBeUndefined()
expect(ctx.sessions.get(brandString<SessionId>('session-created-barrier-s'))).toBeUndefined()
await ctx.fiber.dispose()
})
it('keeps both entries and the scope live through a reentrant agent/created teardown', async () => {
const ctx = await harness()
let ownerCtx!: Context
let creating!: ReturnType<typeof ctx.agents.create>
const lifecycle: string[] = []
ctx.on('session/created', (session) => {
if (session.id === brandString<SessionId>('agent-created-barrier-s')) lifecycle.push('session-created')
})
ctx.on('agent/created', ({ agent }) => {
if (agent.id !== brandString<SessionId>('agent-created-barrier-s')) return
lifecycle.push('agent-created:dispose')
disposeCurrentLifecycle(ownerCtx)
})
ctx.on('agent/created', ({ agent }) => {
if (agent.id !== brandString<SessionId>('agent-created-barrier-s')) return
expect(ctx.agents.get(agent.id)).toBe(agent)
expect(ctx.sessions.get(agent.session.id)).toBe(agent.session)
agent.ctx.effect(() => () => { lifecycle.push('scope-disposed') })
lifecycle.push('agent-created:observer')
})
ctx.on('agent/disposed', ({ agent }) => {
if (agent.id === brandString<SessionId>('agent-created-barrier-s')) lifecycle.push('agent-disposed')
})
ctx.on('session/disposed', (session) => {
if (session.id === brandString<SessionId>('agent-created-barrier-s')) lifecycle.push('session-disposed')
})
const owner = await ctx.plugin(Object.assign((inner: Context) => {
ownerCtx = inner
creating = inner.agents.create({
sessionId: brandString<SessionId>('agent-created-barrier-s'),
agentOptions: { provider: 'mock', model: 'mock' },
})
}, { inject: ['agents'] }))
await expect(creating).rejects.toThrow(/owner disposed during setup/)
await owner.dispose()
expect(lifecycle).toEqual([
'session-created',
'agent-created:dispose',
'agent-created:observer',
'scope-disposed',
'agent-disposed',
'session-disposed',
])
expect(ctx.agents.get(brandString<SessionId>('agent-created-barrier-s'))).toBeUndefined()
expect(ctx.sessions.get(brandString<SessionId>('agent-created-barrier-s'))).toBeUndefined()
await ctx.fiber.dispose()
})
it('rechecks caller liveness after agent/created before starting the driver', async () => {
const ctx = await harness()
let ownerCtx!: Context
let creating!: ReturnType<typeof ctx.agents.create>
let announced!: Agent
const statuses: string[] = []
let scopeDisposed = false
let observerSawLive = false
ctx.on('agent/status', ({ agent, status }) => {
if (agent.id === brandString<SessionId>('agent/created-dispose-s')) statuses.push(status)
})
ctx.on('agent/created', ({ agent }) => {
if (agent.id !== brandString<SessionId>('agent/created-dispose-s')) return
announced = agent
disposeCurrentLifecycle(ownerCtx)
})
ctx.on('agent/created', ({ agent }) => {
if (agent.id !== brandString<SessionId>('agent/created-dispose-s')) return
expect(ctx.agents.get(agent.id)).toBe(agent)
expect(ctx.sessions.get(agent.session.id)).toBe(agent.session)
agent.ctx.effect(() => () => { scopeDisposed = true })
observerSawLive = true
})
const owner = await ctx.plugin(Object.assign((inner: Context) => {
ownerCtx = inner
creating = inner.agents.create({
sessionId: brandString<SessionId>('agent/created-dispose-s'),
agentOptions: { provider: 'mock', model: 'mock' },
})
}, { inject: ['agents'] }))
await expect(creating).rejects.toThrow(/owner disposed during setup/)
await owner.dispose()
expect(announced.status).toBe('idle')
expect(statuses).toEqual([])
expect(observerSawLive).toBe(true)
expect(scopeDisposed).toBe(true)
expect(announced.session.snapshotEvents()).toEqual([])
expect(ctx.agents.get(brandString<SessionId>('agent/created-dispose-s'))).toBeUndefined()
expect(ctx.sessions.get(brandString<SessionId>('agent/created-dispose-s'))).toBeUndefined()
await ctx.fiber.dispose()
})
it('a rejecting setup disposes the announced Session and unwinds the unpublished Agent scope', async () => {
const ctx = await harness()
const published: string[] = []
ctx.on('session/created', () => void published.push('session/created'))
ctx.on('session/disposed', () => void published.push('session/disposed'))
ctx.on('agent/created', () => void published.push('agent/created'))
await expect(ctx.agents.create({
sessionId: brandString<SessionId>('bad-s'),
agentOptions: { provider: 'mock', model: 'mock' },
setup: async () => {
await Promise.resolve()
throw new Error('boom setup')
},
})).rejects.toThrow('boom setup')
// Nothing leaked: no agent, no session, and the ids are reusable.
expect(published).toEqual(['session/created', 'session/disposed'])
expect(ctx.agents.get(brandString<SessionId>('bad-s'))).toBeUndefined()
expect(ctx.sessions.get(brandString<SessionId>('bad-s'))).toBeUndefined()
const retry = await ctx.agents.create({ sessionId: brandString<SessionId>('bad-s'), agentOptions: { provider: 'mock', model: 'mock' } })
await retry.dispose()
})
it('rejects an exotic durable seed before publishing either object', async () => {
const ctx = await harness()
const published: string[] = []
ctx.on('session/created', () => { published.push('session') })
ctx.on('agent/created', () => { published.push('agent') })
class ExoticData { readonly value = 'not durable JSON' }
const seed = [{
seq: 0,
type: 'test/exotic-seed',
data: new ExoticData(),
}] as unknown as SessionEvent[]
await expect(ctx.agents.create({
sessionId: brandString<SessionId>('exotic-seed-session'),
agentOptions: { provider: 'mock', model: 'mock' },
seed,
})).rejects.toThrow(/seed event at index 0 is not losslessly JSON-serializable/)
expect(published).toEqual([])
expect(ctx.agents.get(brandString<SessionId>('exotic-seed-session'))).toBeUndefined()
expect(ctx.sessions.get(brandString<SessionId>('exotic-seed-session'))).toBeUndefined()
const retry = await ctx.agents.create({
sessionId: brandString<SessionId>('exotic-seed-session'),
agentOptions: { provider: 'mock', model: 'mock' },
})
await retry.dispose()
})
it('a throwing session/created listener disposes the scope (pre-nesting rollback window)', async () => {
const ctx = await harness()
let boom = true
const disposed: string[] = []
ctx.on('agent/disposed', ({ agent }) => void disposed.push(agent.id))
ctx.on('session/created', () => {
if (boom) { boom = false; throw new Error('boom created') }
})
await expect(ctx.agents.create({
sessionId: brandString<SessionId>('bad-s'), agentOptions: { provider: 'mock', model: 'mock' },
})).rejects.toThrow('boom created')
expect(ctx.agents.get(brandString<SessionId>('bad-s'))).toBeUndefined()
expect(ctx.sessions.get(brandString<SessionId>('bad-s'))).toBeUndefined()
expect(disposed).toEqual([]) // inserted but never announced: no impossible disposed edge
// The rollback also disposed the scope fiber: re-creating works cleanly.
const retry = await ctx.agents.create({ sessionId: brandString<SessionId>('bad-s'), agentOptions: { provider: 'mock', model: 'mock' } })
expect(scopeOf(retry.agent.ctx)).toBe(retry.agent)
await retry.dispose()
})
it('pairs session and agent announcements when agent creation aborts publication', async () => {
const ctx = await harness()
const lifecycle: string[] = []
ctx.on('session/created', (session) => { lifecycle.push(`session-created:${session.id}`) })
ctx.on('session/disposed', (session) => { lifecycle.push(`session-disposed:${session.id}`) })
ctx.on('agent/created', ({ agent }) => {
lifecycle.push(`agent-created:${agent.id}`)
throw new Error('agent observer failed')
})
ctx.on('agent/disposed', ({ agent }) => { lifecycle.push(`agent-disposed:${agent.id}`) })
await expect(ctx.agents.create({
sessionId: brandString<SessionId>('partial-session'),
agentOptions: { provider: 'mock', model: 'mock' },
})).rejects.toThrow('agent observer failed')
expect(lifecycle).toEqual([
'session-created:partial-session',
'agent-created:partial-session',
'agent-disposed:partial-session',
'session-disposed:partial-session',
])
expect(ctx.agents.get(brandString<SessionId>('partial-session'))).toBeUndefined()
expect(ctx.sessions.get(brandString<SessionId>('partial-session'))).toBeUndefined()
})
it('the config create helper rolls back when publication throws', async () => {
const ctx = await harness()
const sessionsBefore = ctx.sessions.list().length
let boom = true
ctx.on('session/created', () => {
if (boom) {
boom = false
throw new Error('config publish failed')
}
})
await expect(ctx.agentLoop.create(brandString<SessionId>('config-bad'), { provider: 'mock', model: 'mock' }))
.rejects.toThrow('config publish failed')
await expect.poll(() => ctx.agents.get(brandString<SessionId>('config-bad')) === undefined).toBe(true)
await expect.poll(() => ctx.sessions.list().length).toBe(sessionsBefore)
})
it('registrations through a disposed agent ctx throw INACTIVE_EFFECT', async () => {
const ctx = await harness()
const handle = await ctx.agents.create({ sessionId: brandString<SessionId>('s1'), agentOptions: { provider: 'mock', model: 'mock' } })
await handle.dispose()
expect(() => handle.agent.ctx.on('agent/status', () => {})).toThrow(/inactive context/)
})
it('agentEvents fuses carrier and subject for custom drivers', async () => {
const ctx = await harness()
const agent = await ctx.agentLoop.create(brandString<SessionId>('a1'), { provider: 'mock', model: 'mock' })
const other = await ctx.agentLoop.create(brandString<SessionId>('a2'), { provider: 'mock', model: 'mock' })
const heard: string[] = []
agent.ctx.on('agent/error', ({ agent: subject, turn }) => void heard.push(`${subject.id}:${turn}`))
agentEvents(ctx, other).emit('agent/error', { turn: 1, step: 0, error: new Error('not for a1') })
agentEvents(ctx, agent).emit('agent/error', { turn: 2, step: 0, error: new Error('for a1') })
expect(heard).toEqual(['a1:2'])
})
it('owner unload honors the documented teardown order: unregistration AFTER the drain, before detach', async () => {
const ctx = await harness()
let handle!: Awaited<ReturnType<typeof ctx.agents.create>>
const owner = await ctx.plugin(Object.assign(async (inner: Context) => {
handle = await inner.agents.create({ sessionId: brandString<SessionId>('o1-s'), agentOptions: { provider: 'mock', model: 'mock' } })
}, { inject: ['agents'] }))
const { agent } = handle
const order: string[] = []
ctx.on('session/event', (_s, event) => {
if (event.type === 'turn/end') order.push('turn-end')
})
ctx.on('agent/disposed', () => {
order.push(`disposed(listed=${ctx.agents.get(brandString<SessionId>('o1-s')) !== undefined})`)
order.push(`session-still-stored=${ctx.sessions.get(brandString<SessionId>('o1-s')) !== undefined}`)
})
// Open a turn so disposal must drain real work before registry removal.
// Waiting for turn/start avoids pre-step disposal dropping the queued prompt
// before a turn opens.
const turnOpen = new Promise<void>((resolve) => {
const off = ctx.on('session/event', (_s, event) => {
if (event.type === 'turn/start') { off(); resolve() }
})
})
agent.followup(createUserMessage({ content: text('work'), source: { kind: 'user' } }))
await turnOpen
await owner.dispose()
expect(order).toEqual([
'turn-end',
'disposed(listed=false)',
'session-still-stored=true',
])
expect(ctx.sessions.get(brandString<SessionId>('o1-s'))).toBeUndefined()
})
it('handle.dispose() during owner unload still awaits true quiescence (shared boundary)', async () => {
const ctx = await harness()
let handle!: Awaited<ReturnType<typeof ctx.agents.create>>
const owner = await ctx.plugin(Object.assign(async (inner: Context) => {
handle = await inner.agents.create({ sessionId: brandString<SessionId>('h1-s'), agentOptions: { provider: 'mock', model: 'mock' } })
}, { inject: ['agents'] }))
const teardownDone: string[] = []
ctx.on('agent/disposed', () => void teardownDone.push('unregistered'))
// Owner unload begins FIRST (invokes the raw cordis wrapper)…
const unload = owner.dispose()
// …and a concurrent handle.dispose() must not resolve before the chain
// actually finished (the raw wrapper returns undefined on a repeat call).
await handle.dispose()
expect(teardownDone).toContain('unregistered')
expect(ctx.agents.get(brandString<SessionId>('h1-s'))).toBeUndefined()
expect(ctx.sessions.get(brandString<SessionId>('h1-s'))).toBeUndefined()
await unload
})
it('successful handle disposal retires its caller ownership effect', async () => {
const ctx = await harness()
const sessionId = brandString<SessionId>('retired-owner-effect')
const handle = await ctx.agents.create({
sessionId,
agentOptions: { provider: 'mock', model: 'mock' },
})
expect(ctx.fiber.getEffects().map(effect => effect.label)).toContain(`agentLoop.lifecycle(${sessionId})`)
await handle.dispose()
expect(ctx.fiber.getEffects().filter(effect => effect.label === `agentLoop.lifecycle(${sessionId})`)).toEqual([])
await ctx.fiber.dispose()
})
it('owner unload after handle-first teardown follows the same in-flight boundary', async () => {
const ctx = await harness()
const gate = Promise.withResolvers<undefined>()
const cleanupStarted = Promise.withResolvers<undefined>()
let handle!: Awaited<ReturnType<typeof ctx.agents.create>>
const owner = await ctx.plugin(Object.assign(async (inner: Context) => {
handle = await inner.agents.create({
sessionId: brandString<SessionId>('manual-first-s'),
agentOptions: { provider: 'mock', model: 'mock' },
setup(agentCtx) {
agentCtx.effect(() => async () => {
cleanupStarted.resolve(undefined)
await gate.promise
})
},
})
}, { inject: ['agents'] }))
const disposing = handle.dispose()
await cleanupStarted.promise
let ownerSettled = false
const unloading = owner.dispose().then(() => { ownerSettled = true })
await Promise.resolve()
expect(ownerSettled).toBe(false)
gate.resolve(undefined)
await Promise.all([disposing, unloading])
expect(ctx.agents.get(brandString<SessionId>('manual-first-s'))).toBeUndefined()
expect(ctx.sessions.get(brandString<SessionId>('manual-first-s'))).toBeUndefined()
await ctx.fiber.dispose()
})
it('reopens ids after the prior private scope finishes quiescing', async () => {
const ctx = await harness()
const gate = Promise.withResolvers<undefined>()
const cleanupStarted = Promise.withResolvers<undefined>()
const sessionId = brandString<SessionId>('quiescent-reuse')
const first = await ctx.agents.create({
sessionId,
agentOptions: { provider: 'mock', model: 'mock' },
setup(agentCtx) {
agentCtx.effect(() => async () => {
cleanupStarted.resolve(undefined)
await gate.promise
})
},
})
const disposing = first.dispose()
await cleanupStarted.promise
expect(ctx.agents.get(sessionId)).toBe(first.agent)
expect(ctx.sessions.get(sessionId)).toBe(first.agent.session)
gate.resolve(undefined)
await disposing
expect(ctx.agents.get(sessionId)).toBeUndefined()
expect(ctx.sessions.get(sessionId)).toBeUndefined()
const replacement = await ctx.agents.create({ sessionId, agentOptions: { provider: 'mock', model: 'mock' } })
expect(ctx.agents.get(sessionId)).toBe(replacement.agent)
expect(ctx.sessions.get(sessionId)).toBe(replacement.agent.session)
await replacement.dispose()
await ctx.fiber.dispose()
})
it('drains a run re-entered by cancel\'s own idle transition before removing the scope', async () => {
// Automation shaped like goal-round-driver: the running→idle transition that
// disposal's cancel produces immediately queues a follow-up prompt. The
// teardown must drain that replacement run to true quiescence instead of
// awaiting only the first captured done and unwinding under a live run.
const adapter = new MockAdapter([textResponse('one'), textResponse('never awaited')])
const ctx = await harness(adapter)
const handle = await ctx.agents.create({
sessionId: brandString<SessionId>('drain-reentered-run'),
agentOptions: { provider: 'mock', model: 'mock' },
})
const agent = handle.agent
let reentered = false
ctx.on('agent/status', ({ agent: subject, status }) => {
if (subject !== agent || status !== 'idle' || reentered) return
reentered = true
agent.followup(createUserMessage({ content: [{ type: 'text', text: 'reentrant' }], source: { kind: 'user' } }))
})
agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
await waitForIdle(ctx, agent)
expect(reentered).toBe(true)
// Idle again: the reentrant batch was already claimed and settled (its
// prompt was blocked by nothing, so it ran) — arm a SECOND reentry that
// fires from the disposal cancel's idle transition itself.
reentered = false
await handle.dispose()
// The reentrant run either never started or was drained: the registries
// are empty and nothing still drives the detached session.
expect(ctx.agents.get(agent.id)).toBeUndefined()
expect(ctx.sessions.get(agent.id)).toBeUndefined()
const eventsAfter = agent.session.snapshotEvents().length
await new Promise(resolve => setTimeout(resolve, 30))
expect(agent.session.snapshotEvents().length).toBe(eventsAfter)
await ctx.fiber.dispose()
})
})