fix(scope): harden final ownership boundaries

This commit is contained in:
Tianyi Cui
2026-07-12 05:13:17 +08:00
parent 36b8370027
commit a9cb70d896
52 changed files with 2839 additions and 514 deletions

View File

@@ -8,9 +8,9 @@ This is the only package in the harness that contains concrete loop logic. Every
### Public API
Lifecycle (scoped): programmatic creation and resume snapshot caller-owned identity/configuration data, reserve both IDs, mint `agent.ctx`, and install the ordered teardown skeleton before awaiting optional `setup`. A create hands one-read raw seed and metadata references synchronously to the session boundary, which rejects exotic shells and materializes accepted values in a single recursive pass; pre-cloning either value could incorrectly sanitize prototypes. Resume installs an owner-liveness sentinel before persistence load, captures each loaded metadata field once, then hands ownership directly to the full lifecycle. After setup resolves, the factory checks its lifecycle flag, owner-fiber state, and owning agent status around one microtask checkpoint so a same-turn Cordis unload wins before publication. Successful setup inserts both session and agent before announcing either, enables driving immediately before `agent/session-start`, then starts the loop. Setup calls to `send`/`steer`/`inject`/`cancel` reject structurally; load/setup rejection or owner unload publishes nothing. Teardown runs stop/drain (including outstanding idle-injection flushes) → unregister → detach session → unwind scope. All `agent/*` dispatches go through `agentEvents(ctx, agent)`; per-step assembly through `assembleContextFor(agent)`; the turn-end durability checkpoint through `ctx.sessions.flush(session)`.
Lifecycle (scoped): programmatic creation and resume snapshot caller-owned identity/configuration data, obtain registry/store-owned capabilities for both unpublished IDs, mint `agent.ctx`, and install the ordered teardown skeleton before awaiting optional `setup`. The capabilities reject competing `register`/`enter`/`prepare`/`create` calls, so setup cannot publish the factory objects or same-id replacements. A create hands one-read raw seed and metadata references synchronously to the session boundary, which rejects exotic shells and materializes accepted values in a single recursive pass; pre-cloning either value could incorrectly sanitize prototypes. Resume installs an owner-liveness sentinel before persistence load, captures each loaded metadata field once, then hands ownership directly to the full lifecycle. After setup resolves, the factory checks its lifecycle flag, owner-fiber state, and owning agent status around one microtask checkpoint so a same-turn Cordis unload wins before publication. Successful setup inserts both session and agent before announcing either, enables driving immediately before `agent/session-start`, then starts the loop. The concrete agent owns runtime-pinned `id`, frozen detached `options`, `session`, and `ctx` bindings. Load/setup rejection or owner unload publishes nothing; partial creation announcements are paired during rollback. Teardown runs stop/drain (including outstanding idle-injection flushes) → unregister → detach session → unwind scope. All non-vetoing `agent/*` notifications go through `agentEvents(ctx, agent)`, which contains sync/async listener failures per observer; per-step assembly goes through `assembleContextFor(agent)`; the turn-end durability checkpoint goes through `ctx.sessions.flush(session)`.
- `ctx.agentLoop.create(id: string, options?: AgentOptions, meta?: { cwd?: string }): ReactLoopAgent`config-driven create: an agent on a fresh per-run session id `${id}-session-<uuid>` with optional session metadata. Used for `cordis.yml`-configured agents. The per-run uuid avoids colliding with the on-disk log a prior run materialized once a durable persistence backend is loaded; each run is a new session (a deliberate demo simplification — a real resume-or-create policy is a TODO). Disposed with the calling fiber.
- `ctx.agentLoop.create(id: string, options?: AgentOptions, meta?: { cwd?: string }): ReactLoopAgent`synchronous no-setup create, used directly by programs and by `cordis.yml`-configured agents. It creates a fresh per-run session id `${id}-session-<uuid>` with optional metadata; the uuid avoids colliding with a prior durable log. Each call is a new session (a deliberate demo simplification — a real resume-or-create policy is a TODO). Disposed with the calling fiber.
`AgentLoop` also implements the `AgentFactory` seam and registers itself via `ctx.agents.setFactory(this)`, so plugins create/resume agents through `ctx.agents` (the interface):

View File

@@ -7,10 +7,10 @@
*/
import type { Context } from 'cordis'
import { scopeTarget } from '@deepseek-ai/dsh-scope'
import type { Scoped } from '@deepseek-ai/dsh-scope'
import { agentEvents } from '@deepseek-ai/dsh-agent'
import type { AgentId, AgentOptions, AgentStatus, SendOptions } from '@deepseek-ai/dsh-agent'
import type { Agent } from '@deepseek-ai/dsh-agent'
import { deepFreeze } from '@deepseek-ai/dsh-llm'
import type { ContentBlock, MessageSource } from '@deepseek-ai/dsh-llm'
import type { Session } from '@deepseek-ai/dsh-session'
import { Inbox } from './inbox.ts'
@@ -65,6 +65,26 @@ export function prepareReactLoopAgent(
}
}
/**
* Install the concrete agent's scope context exactly once. Construction and
* scope minting are mutually referential (the scope key is the agent), so the
* factory performs this one post-construction binding before setup receives
* the unpublished agent. The runtime slot is non-writable/non-configurable;
* TypeScript `readonly` alone would still let JavaScript redirect later
* registrations to another context.
* @param agent - the unpublished concrete agent to bind.
* @param ctx - its fully extended agent scope context.
*/
export function bindReactLoopAgentContext(agent: ReactLoopAgent, ctx: Context): void {
if (Object.hasOwn(agent, 'ctx')) throw new Error(`agent "${agent.id}" context is already bound`)
Object.defineProperty(agent, 'ctx', {
value: ctx,
enumerable: true,
writable: false,
configurable: false,
})
}
/**
* The concrete {@link Agent} implementation owned by the agent-loop plugin.
*
@@ -84,18 +104,7 @@ export class ReactLoopAgent implements Agent {
* context are mutually referential (the scope is keyed BY this agent), so
* neither can exist strictly before the other.
*/
ctx!: Context
/**
* The dispatch carrier for this agent's own emits (`agent/status`,
* `agent/queued`, `agent/error`): keyed by the agent, base = the agent
* (listener `this` is the agent). Built lazily because it is self-referential.
*/
private get carrier(): Scoped<Agent> {
return (this.#carrier ??= scopeTarget(this, this))
}
#carrier: Scoped<Agent> | undefined
declare readonly ctx: Context
private _status: AgentStatus = 'idle'
private currentAbort: AbortController | undefined
@@ -143,6 +152,16 @@ export class ReactLoopAgent implements Agent {
public readonly options: AgentOptions,
public readonly session: Session,
) {
const acceptedOptions = deepFreeze(structuredClone(options))
// Pin the public ownership/identity bindings in the runtime object. A
// JavaScript caller can otherwise replace TS-readonly parameter properties
// after publication and split the registry, driver, session, and model
// configuration into different worlds.
Object.defineProperties(this, {
id: { value: id, enumerable: true, writable: false, configurable: false },
options: { value: acceptedOptions, enumerable: true, writable: false, configurable: false },
session: { value: session, enumerable: true, writable: false, configurable: false },
})
const { promise, resolve } = Promise.withResolvers<void>()
this.disposed = promise
this.resolveDisposed = resolve
@@ -161,11 +180,7 @@ export class ReactLoopAgent implements Agent {
// waiter (docs/defensive-patterns.md "contain callback exceptions" — a lifecycle await must
// not hang on one bad listener).
if (status !== 'running') this.settleIdleWaiters()
try {
this.loopCtx.emit(this.carrier, 'agent/status', this, status)
} catch (error: unknown) {
this.loopCtx.logger.warn(`agent "${this.id}": agent/status listener threw on ${status}: ${String(error)}`)
}
agentEvents(this.loopCtx, this).emit('agent/status', status)
}
/**
@@ -194,7 +209,7 @@ export class ReactLoopAgent implements Agent {
if (this._status === 'disposed') throw new Error(`agent "${this.id}" is disposed`)
const source = this.resolveSource(options)
this.#inbox.enqueue({ content, source })
this.loopCtx.emit(this.carrier, 'agent/queued', this, content, { source, steering: false })
agentEvents(this.loopCtx, this).emit('agent/queued', content, { source, steering: false })
}
steer(content: ContentBlock[], options?: SendOptions): void {
@@ -203,7 +218,7 @@ export class ReactLoopAgent implements Agent {
if (this._status !== 'running') { this.send(content, options); return }
const source = this.resolveSource(options)
this.#inbox.steer({ content, source })
this.loopCtx.emit(this.carrier, 'agent/queued', this, content, { source, steering: true })
agentEvents(this.loopCtx, this).emit('agent/queued', content, { source, steering: true })
}
inject(content: ContentBlock[], options?: SendOptions): void {
@@ -269,14 +284,10 @@ export class ReactLoopAgent implements Agent {
if (turnRecorded) {
// Through the store's flush (the carrier owner), never a raw parallel.
const flush = this.loopCtx.sessions.flush(this.session).catch((error: unknown) => {
const err = error instanceof Error ? error : new Error(String(error))
this.loopCtx.logger.warn(`agent "${this.id}": flush after idle injection failed: ${err.message}`)
try {
this.loopCtx.emit(this.carrier, 'agent/error', this, turn, 0, err)
} catch {
// contained: the failure is already logged; a throwing agent/error
// listener must not escape this fire-and-forget catch.
}
const rendered = renderThrown(error)
const err = error instanceof Error ? error : new Error(rendered)
this.loopCtx.logger.warn(`agent "${this.id}": flush after idle injection failed: ${rendered}`)
agentEvents(this.loopCtx, this).emit('agent/error', turn, 0, err)
})
this.pendingIdleFlushes.add(flush)
// Attach the same retirement callback to both settlement arms so even a
@@ -393,11 +404,7 @@ export class ReactLoopAgent implements Agent {
// setStatus refuses transitions out of 'disposed', so emit directly —
// 'disposed' is part of the agent/status contract. Guarded: a throwing
// listener must not break the disposal chain.
try {
this.loopCtx.emit(this.carrier, 'agent/status', this, 'disposed')
} catch {
// listener error during disposal — nothing safe left to do with it
}
agentEvents(this.loopCtx, this).emit('agent/status', 'disposed')
}
// An unexpected driver rejection must not skip registry/session/scope
// cleanup. The normal loop contains turn failures itself; allSettled is the
@@ -414,3 +421,12 @@ export class ReactLoopAgent implements Agent {
}
}
}
/** Render an arbitrary thrown value without allowing coercion to throw again. */
function renderThrown(value: unknown): string {
try {
return value instanceof Error ? value.message : String(value)
} catch {
return '<unrenderable thrown value>'
}
}

View File

@@ -13,17 +13,24 @@ import z from 'schemastery'
import { createScope } from '@deepseek-ai/dsh-scope'
import type { Scope } from '@deepseek-ai/dsh-scope'
import { agentEvents } from '@deepseek-ai/dsh-agent'
import type { AgentFactory, AgentHandle, AgentId, AgentOptions, CreateAgentOptions, ResumeAgentOptions, SessionStartSource } from '@deepseek-ai/dsh-agent'
import type { AgentFactory, AgentHandle, AgentId, AgentOptions, AgentRegistrationReservation, CreateAgentOptions, ResumeAgentOptions, SessionStartSource } from '@deepseek-ai/dsh-agent'
import type {} from '@deepseek-ai/dsh-llm'
import { SessionId, type SessionHeader } from '@deepseek-ai/dsh-session'
import type { Session } from '@deepseek-ai/dsh-session'
import type { Session, SessionRegistrationReservation } from '@deepseek-ai/dsh-session'
import type {} from '@deepseek-ai/dsh-system-prompt'
import type {} from '@deepseek-ai/dsh-tools'
import type { SessionPersistence } from '@deepseek-ai/dsh-session-persistence'
import { prepareReactLoopAgent, ReactLoopAgent } from './agent.ts'
import { bindReactLoopAgentContext, prepareReactLoopAgent, ReactLoopAgent } from './agent.ts'
export { ReactLoopAgent } from './agent.ts'
/** Both unpublished identity capabilities held by one factory transaction. */
interface RegistrationReservations {
agent: AgentRegistrationReservation
session: SessionRegistrationReservation
release(): void
}
declare module 'cordis' {
interface Context {
agentLoop: AgentLoop
@@ -71,10 +78,6 @@ export interface Config {
export class AgentLoop extends Service implements AgentFactory {
static inject = ['agents', 'sessions', 'llm', 'tools', 'systemPrompt']
/** IDs held by unpublished async creation transactions. */
private pendingAgentIds = new Set<AgentId>()
private pendingSessionIds = new Set<SessionId>()
// The schema validates plain strings (cordis.yml config values are untyped at
// runtime); the {@link Config} TYPE declares the branded `id`/`resumeSessionId`
// because the config format is the boundary where an id enters. The brand is a
@@ -153,14 +156,19 @@ export class AgentLoop extends Service implements AgentFactory {
* @returns the running agent, owned by the calling fiber (no handle).
*/
create(id: AgentId, options: AgentOptions = {}, meta: Pick<SessionHeader, 'cwd'> = {}): ReactLoopAgent {
this.assertAgentIdFree(id)
const sessionId = SessionId(`${id}-session-${randomUUID()}`)
const reservations = this.reserve(id, sessionId)
// Config/programmatic path: prepare the session and let start() fold its
// lifecycle into the agent's composite effect (so a fiber unload tears the
// session + agent down as one ordered chain, capturing the loop's closing
// flush). The whole effect is owned by THIS fiber; no AgentHandle is needed.
const session = this.ctx.sessions.prepare(SessionId(`${id}-session-${randomUUID()}`), { meta })
const { agent } = this.start(id, options, session, 'startup')
return agent
try {
const session = reservations.session.prepare({ meta })
const { agent } = this.start(id, options, session, 'startup', reservations)
return agent
} finally {
reservations.release()
}
}
/**
@@ -188,16 +196,16 @@ export class AgentLoop extends Service implements AgentFactory {
const agentOptions = structuredClone(options.agentOptions ?? {})
const seed = options.seed
const meta = options.meta
const release = this.reserve(agentId, sessionId)
const reservations = this.reserve(agentId, sessionId)
try {
const session = this.ctx.sessions.prepare(sessionId, {
const session = reservations.session.prepare({
...seed !== undefined ? { seed } : {},
...meta !== undefined ? { meta } : {},
})
// A seeded (forked) create is still a fresh start, NOT a resume.
return await this.startOwned(agentId, agentOptions, session, 'startup', setup)
return await this.startOwned(agentId, agentOptions, session, 'startup', reservations, setup)
} finally {
release()
reservations.release()
}
}
@@ -273,7 +281,7 @@ export class AgentLoop extends Service implements AgentFactory {
return transactionSettled
}, `agentLoop.resumeLoad(${agentId})`)
try {
const release = this.reserve(agentId, sessionId)
const reservations = this.reserve(agentId, sessionId)
try {
const loadTask = persistence.load(sessionId)
const { meta, events } = await Promise.race([
@@ -292,7 +300,7 @@ export class AgentLoop extends Service implements AgentFactory {
// An out-of-band direct registry/session insertion can still race this
// service's reservation, so the public enter primitives re-check exact
// liveness at publication.
const session = this.ctx.sessions.prepare(sessionId, {
const session = reservations.session.prepare({
seed: events,
meta: {
createdAt,
@@ -305,12 +313,12 @@ export class AgentLoop extends Service implements AgentFactory {
// effect before it reaches its first setup await. Only then disarm the
// load sentinel: ownership passes directly from one effect to the other
// with no disposal gap.
const starting = this.startOwned(agentId, agentOptions, session, 'resume', setup)
const starting = this.startOwned(agentId, agentOptions, session, 'resume', reservations, setup)
observingOwner = false
await disposeLoadSentinel()
return await starting
} finally {
release()
reservations.release()
}
} finally {
try {
@@ -327,29 +335,24 @@ export class AgentLoop extends Service implements AgentFactory {
}
}
/**
* Reject a duplicate agent id BEFORE the session is entered into the store, so
* a failed factory call never leaves an orphaned live session (and lazy
* persistence state) behind. `register()` enforces the same uniqueness, but
* only after the session has already entered the store.
*/
private assertAgentIdFree(id: AgentId): void {
if (this.ctx.agents.get(id) !== undefined || this.pendingAgentIds.has(id)) {
throw new Error(`agent "${id}" is already registered`)
}
}
/** Reserve both public identities for one unpublished async transaction. */
private reserve(agentId: AgentId, sessionId: SessionId): () => void {
this.assertAgentIdFree(agentId)
if (this.ctx.sessions.get(sessionId) !== undefined || this.pendingSessionIds.has(sessionId)) {
throw new Error(`session "${sessionId}" already exists`)
}
this.pendingAgentIds.add(agentId)
this.pendingSessionIds.add(sessionId)
return () => {
this.pendingAgentIds.delete(agentId)
this.pendingSessionIds.delete(sessionId)
/** Reserve both public identities in their owning registries. */
private reserve(agentId: AgentId, sessionId: SessionId): RegistrationReservations {
const agent = this.ctx.agents.reserve(agentId)
try {
const session = this.ctx.sessions.reserve(sessionId)
return {
agent,
session,
release() {
// Both owner capabilities are independently idempotent, so the
// composite needs no second state machine of its own.
session.release()
agent.release()
},
}
} catch (error: unknown) {
agent.release()
throw error
}
}
@@ -361,7 +364,12 @@ export class AgentLoop extends Service implements AgentFactory {
* `active`, unwinds the scope, and wins the race without any late Cordis
* effect collection.
*/
private prepareLifecycle(id: AgentId, options: AgentOptions, session: Session): {
private prepareLifecycle(
id: AgentId,
options: AgentOptions,
session: Session,
reservations: RegistrationReservations,
): {
agent: ReactLoopAgent
active: () => boolean
deactivated: Promise<void>
@@ -378,7 +386,7 @@ export class AgentLoop extends Service implements AgentFactory {
const driver = prepareReactLoopAgent(this.ctx, id, options, session)
const { agent } = driver
const scope: Scope = createScope(this.ctx, agent)
agent.ctx = scope.ctx.extend({ agent })
bindReactLoopAgentContext(agent, scope.ctx.extend({ agent }))
let active = true
let detachSession: (() => void) | undefined
@@ -422,19 +430,15 @@ export class AgentLoop extends Service implements AgentFactory {
const publish = (source: SessionStartSource): void => {
// Publication is one synchronous, rollback-covered sequence. Setup has
// already completed, so its scoped listeners observe both announcements.
detachSession = agent.ctx.sessions.enter(session)
detachAgent = this.ctx.agents.enter(agent)
detachSession = agent.ctx.sessions.enter(session, reservations.session)
detachAgent = this.ctx.agents.enter(agent, reservations.agent)
this.ctx.sessions.announce(session)
this.ctx.agents.announce(agent)
// Setup is over and both entries are live. Open the driving surface just
// before session-start so its listeners retain their supported ability to
// inject/queue, while setup itself can never drive an unpublished agent.
driver.enableDrive()
try {
agentEvents(this.ctx, agent).emit('agent/session-start', source)
} catch (error: unknown) {
this.ctx.logger.warn(`agent "${id}": agent/session-start listener threw: ${String(error)}`)
}
agentEvents(this.ctx, agent).emit('agent/session-start', source)
stop = driver.startDriver()
}
@@ -453,9 +457,13 @@ export class AgentLoop extends Service implements AgentFactory {
/** Publish a no-setup config agent synchronously. */
private start(
id: AgentId, options: AgentOptions, session: Session, source: SessionStartSource,
id: AgentId,
options: AgentOptions,
session: Session,
source: SessionStartSource,
reservations: RegistrationReservations,
): { agent: ReactLoopAgent; disposeAgent: () => Promise<void> } {
const lifecycle = this.prepareLifecycle(id, options, session)
const lifecycle = this.prepareLifecycle(id, options, session, reservations)
try {
lifecycle.publish(source)
return { agent: lifecycle.agent, disposeAgent: lifecycle.disposeAgent }
@@ -485,9 +493,10 @@ export class AgentLoop extends Service implements AgentFactory {
*/
private async startOwned(
id: AgentId, options: AgentOptions, session: Session, source: SessionStartSource,
reservations: RegistrationReservations,
setup?: (agentCtx: Context) => Promise<void> | void,
): Promise<AgentHandle> {
const lifecycle = this.prepareLifecycle(id, options, session)
const lifecycle = this.prepareLifecycle(id, options, session, reservations)
try {
// The owner-disposal branch makes a never-settling setup unable to hold
// the transaction or its ID reservations forever. Promise.race installs

View File

@@ -7,7 +7,7 @@ import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
import ToolRegistry from '@deepseek-ai/dsh-tools'
import AgentRegistry from '@deepseek-ai/dsh-agent'
import AgentLoop, { ReactLoopAgent } from '@deepseek-ai/dsh-agent-loop'
import { prepareReactLoopAgent } from '../src/agent.ts'
import { bindReactLoopAgentContext, prepareReactLoopAgent } from '../src/agent.ts'
import { MockAdapter, textResponse } from './mock-adapter.ts'
async function harness(adapter: MockAdapter) {
@@ -49,6 +49,34 @@ function send(agent: ReactLoopAgent, text: string) {
}
describe('ReactLoopAgent', () => {
it('owns immutable runtime bindings for id, options, session, and scoped context', async () => {
const ctx = await harness(new MockAdapter([textResponse('unused')]))
const options = { model: 'mock' }
const agent = ctx.agentLoop.create(AgentId('owned-bindings'), options)
const acceptedSession = agent.session
const acceptedContext = agent.ctx
options.model = 'caller-mutated'
expect(agent.options).toEqual({ model: 'mock' })
expect(Object.isFrozen(agent.options)).toBe(true)
expect(Reflect.set(agent, 'id', AgentId('redirected'))).toBe(false)
expect(Reflect.set(agent, 'options', { model: 'other' })).toBe(false)
expect(Reflect.set(agent, 'session', ctx.sessions.create(SessionId('other')))).toBe(false)
expect(Reflect.set(agent, 'ctx', new Context())).toBe(false)
expect(agent.id).toBe('owned-bindings')
expect(agent.session).toBe(acceptedSession)
expect(agent.ctx).toBe(acceptedContext)
expect(() => { bindReactLoopAgentContext(agent, new Context()) }).toThrow(/context is already bound/)
for (const name of ['id', 'options', 'session', 'ctx']) {
expect(Object.getOwnPropertyDescriptor(agent, name)).toMatchObject({
configurable: false,
writable: false,
})
}
await ctx.fiber.dispose()
})
it('send() throws after disposal', async () => {
const adapter = new MockAdapter(['hang'])
const ctx = await harness(adapter)
@@ -197,6 +225,23 @@ describe('ReactLoopAgent', () => {
warn.mockRestore()
})
it('idle inject() safely renders a hostile non-Error flush failure', async () => {
const ctx = await harness(new MockAdapter([textResponse('ok')]))
const hostile = { [Symbol.toPrimitive]() { throw new Error('no coercion') } }
ctx.on('session/flush', () => { throw hostile })
const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
const agent = ctx.agentLoop.create(AgentId('hostile-flush'), { model: 'mock' })
const errors: string[] = []
ctx.on('agent/error', (_a, _turn, _step, error) => void errors.push(error.message))
agent.inject([{ type: 'text', text: 'notice' }])
await new Promise(r => setTimeout(r, 20))
expect(errors).toEqual(['<unrenderable thrown value>'])
expect(warn).toHaveBeenCalledWith(expect.stringContaining('<unrenderable thrown value>'))
warn.mockRestore()
})
it('idle inject() with a non-serializable source opens no turn (nothing to close)', async () => {
const adapter = new MockAdapter([textResponse('ok')])
const ctx = await harness(adapter)
@@ -416,7 +461,7 @@ describe('ReactLoopAgent', () => {
expect(adapter.requests).toHaveLength(1)
expect(agent.status).toBe('idle')
expect(warn).toHaveBeenCalledWith(expect.stringContaining('agent/status listener threw on running'))
expect(warn).toHaveBeenCalledWith(expect.stringContaining('agent event "agent/status" listener threw'))
warn.mockRestore()
})
@@ -434,7 +479,7 @@ describe('ReactLoopAgent', () => {
expect(adapter.requests).toHaveLength(1)
expect(agent.status).toBe('idle')
expect(warn).toHaveBeenCalledWith(expect.stringContaining('agent/status listener threw on idle'))
expect(warn).toHaveBeenCalledWith(expect.stringContaining('agent event "agent/status" listener threw'))
warn.mockRestore()
})
})

View File

@@ -197,6 +197,35 @@ describe('agent scope lifecycle', () => {
await handle.dispose()
})
it('makes setup-time publication structurally impossible through public stores', async () => {
const ctx = await harness()
const lifecycle: string[] = []
ctx.on('session/created', () => void lifecycle.push('session'))
ctx.on('agent/created', () => void lifecycle.push('agent'))
const handle = await ctx.agents.create({
agentId: AgentId('guarded-publication'),
sessionId: SessionId('guarded-publication-s'),
agentOptions: { model: 'mock' },
setup: (agentCtx) => {
const agent = agentCtx.agent!
expect(() => agentCtx.agents.enter(agent)).toThrow(/reserved for unpublished creation/)
expect(() => agentCtx.agents.register(agent)).toThrow(/reserved for unpublished creation/)
expect(() => agentCtx.sessions.enter(agent.session)).toThrow(/reserved for unpublished creation/)
expect(() => agentCtx.sessions.prepare(agent.session.id)).toThrow(/reserved for unpublished creation/)
expect(() => agentCtx.sessions.create(agent.session.id)).toThrow(/reserved for unpublished creation/)
expect(lifecycle).toEqual([])
expect(ctx.agents.get(agent.id)).toBeUndefined()
expect(ctx.sessions.get(agent.session.id)).toBeUndefined()
},
})
expect(lifecycle).toEqual(['session', 'agent'])
expect(ctx.agents.get(handle.agent.id)).toBe(handle.agent)
expect(ctx.sessions.get(handle.agent.session.id)).toBe(handle.agent.session)
await handle.dispose()
})
it('structurally rejects every driving verb during setup', async () => {
const ctx = await harness()
const handle = await ctx.agents.create({
@@ -357,6 +386,33 @@ describe('agent scope lifecycle', () => {
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({
agentId: AgentId('partial-agent'),
sessionId: SessionId('partial-session'),
agentOptions: { model: 'mock' },
})).rejects.toThrow('agent observer failed')
expect(lifecycle).toEqual([
'session-created:partial-session',
'agent-created:partial-agent',
'agent-disposed:partial-agent',
'session-disposed:partial-session',
])
expect(ctx.agents.get(AgentId('partial-agent'))).toBeUndefined()
expect(ctx.sessions.get(SessionId('partial-session'))).toBeUndefined()
})
it('the synchronous config helper rolls back when publication throws', async () => {
const ctx = await harness()
const sessionsBefore = ctx.sessions.list().length

View File

@@ -8,10 +8,10 @@ Tracks live agents so UI, hook, and orchestrator plugins can find them without i
### Public API
The scoped-registration surface: `Agent.ctx` is the agent's scope context (`dsh-scope`, key = the agent) — register tools/sections/variables/listeners through it for that agent alone, all unwound on disposal. `agentEvents(ctx, agent)` is the fused dispatcher every agent-subject event goes through (carrier + injected subject in one move); `assembleContextFor(agent)` builds the per-agent assembly context (`agent` + `scope` together). `CreateAgentOptions.setup(agentCtx)` and `ResumeAgentOptions.setup(agentCtx)` compose a fresh or resumed agent's scoped world while the factory keeps the agent and session unpublished; creation awaits setup and a same-turn owner-unload checkpoint before either creation notification or the first assembly. Setup composes, it never drives: the concrete loop rejects driving verbs until the `agent/session-start` boundary.
The scoped-registration surface: `Agent.ctx` is the agent's scope context (`dsh-scope`, key = the agent) — register tools/sections/variables/listeners through it for that agent alone, all unwound on disposal. `agentEvents(ctx, agent)` is the fused dispatcher every agent-subject event goes through (carrier + injected subject in one move); its notification mode invokes every listener and contains both synchronous throws and returned-promise rejections. `assembleContextFor(agent)` builds the per-agent assembly context (`agent` + `scope` together). `CreateAgentOptions.setup(agentCtx)` and `ResumeAgentOptions.setup(agentCtx)` compose a fresh or resumed agent's scoped world while registry/store-owned reservation capabilities keep both identities unpublished; creation awaits setup and a same-turn owner-unload checkpoint before either creation notification or the first assembly. Setup composes, it never drives or publishes: driving verbs and ordinary agent/session insertion both reject until the owning publication boundary.
- `ctx.agents.register(agent: Agent): () => Promise<void> | void` — record an **already-constructed** agent. Disposed with the calling fiber.
- Advanced ordered lifecycle: `enter(agent): () => void` inserts without announcing, and `announce(agent)` emits `agent/created` only for that exact live entry. The async factory uses this split after setup; ordinary plugins use `register()`.
- Advanced ordered lifecycle: `reserve(id)` returns an opaque unpublished-identity capability owned by the calling fiber (owner unload releases an abandoned reservation); `enter(agent, reservation?): () => void` inserts under one captured, runtime-pinned id without announcing; and `announce(agent)` emits `agent/created` exactly once for that exact live entry, rejecting repeat or reentrant announcement. While reserved, bare `register`/`enter` calls for the id reject, including from setup. The factory uses this split; ordinary plugins use `register()`.
- `ctx.agents.get(id: AgentId): Agent | undefined`
- `ctx.agents.list(): Agent[]`
@@ -20,7 +20,7 @@ The scoped-registration surface: `Agent.ctx` is the agent's scope context (`dsh-
Agent *creation* is provided by the plugin implementing `AgentFactory` (`dsh-agent-loop`), registered via `setFactory`. This keeps creation on the `dsh-agent` interface so consumers (UI, the ACP bridge) program against `ctx.agents` without depending on the concrete loop package.
- `ctx.agents.setFactory(factory: AgentFactory): () => Promise<void> | void` — register the creation factory (the loop calls this on construction). Throws on a second factory; the slot clears on dispose.
- `ctx.agents.create(options: CreateAgentOptions): Promise<AgentHandle>` — snapshot caller-owned IDs/options/metadata and hand the one-read raw seed synchronously to the session boundary for one-pass lossless-JSON materialization, construct and await optional setup while unpublished, insert and announce both session and agent, open the `agent/session-start` driving boundary, then start a new loop on the caller-supplied `sessionId`. Agent/session IDs are reserved across setup; seed rejection, setup rejection, or owner unload publishes nothing. Publication is rollback-covered: if a creation listener throws, entries and scope unwind but effects of already-delivered notifications remain observable; an agent whose announcement began emits `agent/disposed` during that rollback. Rejects if no factory is registered.
- `ctx.agents.create(options: CreateAgentOptions): Promise<AgentHandle>` — snapshot caller-owned IDs/options/metadata and hand the one-read raw seed synchronously to the session boundary for one-pass lossless-JSON materialization, construct and await optional setup while unpublished, insert and announce both session and agent, open the `agent/session-start` driving boundary, then start a new loop on the caller-supplied `sessionId`. Registry/store reservation capabilities block every competing public insertion across setup; seed rejection, setup rejection, or owner unload publishes nothing. Publication is rollback-covered: if a creation listener throws, entries and scope unwind but effects of already-delivered notifications remain observable; any creation announcement that began is paired by `agent/disposed` or `session/disposed`. Rejects if no factory is registered.
- `ctx.agents.resume(options: ResumeAgentOptions): Promise<AgentHandle>` — snapshot caller-owned IDs/options, load a persisted session ([session persistence](../../../docs/rfc/implemented/architecture/2026-06-14-session-persistence.md)), mint a fresh agent scope, await optional setup while unpublished, then follow the same insert → announce → session-start → loop-start boundary. The IDs are reserved across persistence load and setup; load/setup rejection or owner unload publishes nothing. Rejects if no factory is registered or session persistence is unconfigured.
`AgentHandle = { agent: Agent; dispose(): Promise<void> }`. The disposer is a **capability** — only the holder can tear this agent down. `dispose()` stops the loop, `await`s its exit plus every outstanding idle-injection flush (quiescence — NOT just the `disposed` status flip), unregisters the agent, removes its session from the store, and finally unwinds its scoped world. This order captures every agent-started `session/flush` before the session is detached and keeps scoped listeners alive through those checkpoints. `ctx.agents.get(id)` still returns a bare `Agent` — the handle is only for the OWNER that created it. The ACP bridge and in-process subagent backends are production consumers; config-created agents are owned by the loop fiber and never need a handle.

View File

@@ -45,7 +45,10 @@ type Tail<K extends AgentSubjectEvent> = Params<Events[K]> extends [Agent, ...in
*/
export interface AgentEventDispatch {
/**
* Fire-and-forget notification (Cordis `emit`) in the agent's scope.
* Fire-and-forget notification in the agent's scope. Every listener is
* invoked; synchronous throws and returned-promise rejections are logged and
* contained per listener, so a notification cannot veto lifecycle progress
* or starve a later observer.
* @param name - the agent-subject event to emit.
* @param rest - the event's arguments after the injected agent.
*/
@@ -96,9 +99,22 @@ export function agentEvents(ctx: Context, agent: Agent): AgentEventDispatch {
// tuple — hence one contained, shape-preserving cast per method.
return {
emit(name, ...rest) {
// eslint-disable-next-line @typescript-eslint/unbound-method -- the events mixin accessor returns a pre-bound function
const emit = ctx.emit as (thisArg: Scoped<Agent>, name: string, ...args: unknown[]) => void
emit(carrier, name, agent, ...rest)
// Cordis emit invokes callbacks through Array.map: one synchronous throw
// starves later listeners, and returned promises are discarded. Agent
// notifications are non-vetoing, so resolve the same filtered callback
// set ourselves and contain both failure modes independently.
const args: unknown[] = [carrier, name, agent, ...rest]
const callbacks = ctx.events.dispatch('emit', args)
for (const callback of callbacks) {
try {
const returned: unknown = callback(...args)
void Promise.resolve(returned).catch((error: unknown) => {
ctx.logger.warn(`agent event "${name}" listener rejected: ${renderThrown(error)}`)
})
} catch (error: unknown) {
ctx.logger.warn(`agent event "${name}" listener threw: ${renderThrown(error)}`)
}
}
},
async serial(name, ...rest) {
// eslint-disable-next-line @typescript-eslint/unbound-method -- the events mixin accessor returns a pre-bound function
@@ -129,6 +145,15 @@ export function agentEvents(ctx: Context, agent: Agent): AgentEventDispatch {
}
}
/** Render an arbitrary thrown value without allowing coercion to throw again. */
function renderThrown(value: unknown): string {
try {
return value instanceof Error ? `${value.name}: ${value.message}` : String(value)
} catch {
return '<unrenderable thrown value>'
}
}
/**
* The assembly context for one agent's prompt: the typed `agent` DX field and
* the `scope` layer selector, set together (setting `agent` without `scope`

View File

@@ -9,6 +9,7 @@ import { Context, Service } from 'cordis'
import { scopeTarget } from '@deepseek-ai/dsh-scope'
import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session'
import type { Agent, AgentId, AgentOptions } from './types.ts'
import { agentEvents } from './dispatch.ts'
export * from './types.ts'
export { agentEvents, assembleContextFor } from './dispatch.ts'
@@ -141,9 +142,9 @@ export interface AgentFactory {
* creation notifications in order, unlocks driving at
* `agent/session-start`, and only then starts the loop. The sequence is
* rollback-covered, but notifications delivered before a later listener
* failure remain observable; if agent announcement began, rollback emits
* `agent/disposed`, while the session entry is removed without a separate
* disposal event. The owner disposes the resolved handle to stop/drain,
* failure remain observable; every agent or session creation announcement
* that began is paired by `agent/disposed` or `session/disposed` during
* rollback. The owner disposes the resolved handle to stop/drain,
* unregister, remove the session, and unwind the scope.
* @param options - agent/session identity, configuration, and optional setup.
* @returns the owned handle after setup, both announcements, and loop start complete.
@@ -164,6 +165,33 @@ export interface AgentFactory {
/** Thrown when create/resume is called before an agent factory is registered. */
const NO_FACTORY_MESSAGE = 'no agent factory registered (load an agent-loop plugin)'
/** Render an arbitrary thrown value without allowing coercion to throw again. */
function renderThrown(value: unknown): string {
try {
return value instanceof Error ? `${value.name}: ${value.message}` : String(value)
} catch {
return '<unrenderable thrown value>'
}
}
/**
* Unforgeable ownership handle for one unpublished agent id. The factory holds
* this object across asynchronous setup; while it is live, ordinary public
* registration of that id fails, so setup cannot publish the factory's agent
* (or a replacement with the same id) ahead of the transaction. Callers obtain
* handles only from {@link AgentRegistry.reserve}.
*/
export interface AgentRegistrationReservation {
/** The reserved registry id. */
readonly id: AgentId
/**
* Release the unpublished reservation; idempotent. The registry also
* releases it automatically when the fiber that called `reserve` disposes.
* @returns nothing.
*/
release(): void
}
/**
* Agent registry (`ctx.agents`): tracks live agents so UI, hook, and
* orchestrator plugins can find them without depending on the concrete loop
@@ -173,6 +201,10 @@ const NO_FACTORY_MESSAGE = 'no agent factory registered (load an agent-loop plug
*/
export class AgentRegistry extends Service {
private store = new Map<AgentId, Agent>()
/** The one accepted registry key for each live agent; never reread caller state. */
private acceptedIds = new WeakMap<Agent, AgentId>()
/** Unpublished identities held across factory setup/load transactions. */
private reservations = new Map<AgentId, AgentRegistrationReservation>()
/** Entries whose `agent/created` announcement phase began. */
private announced = new WeakSet<Agent>()
private factory: AgentFactory | undefined
@@ -188,6 +220,49 @@ export class AgentRegistry extends Service {
ctx.accessor('agent', { get: () => undefined })
}
/**
* Reserve an unpublished agent id. Registration through {@link register} or
* bare {@link enter} fails until the returned capability is released; the
* owning factory passes the exact capability back to `enter` at publication.
* This makes “setup cannot publish” structural rather than a cooperative
* convention, including attempts to register a different object under the
* reserved id. The reservation belongs to the calling fiber and is released
* automatically if that owner unloads before the transaction settles.
* @param id - the id the factory transaction will publish.
* @returns the opaque reservation capability.
* @throws if the id is malformed, live, or already reserved.
*/
reserve(id: AgentId): AgentRegistrationReservation {
if (typeof id !== 'string') throw new TypeError('agent id must be a string')
if (this.store.has(id) || this.reservations.has(id)) {
throw new Error(`agent "${id}" is already registered or reserved`)
}
let active = true
const rawRelease = (): void => {
if (!active) return
active = false
this.reservations.delete(id)
}
let disposeEffect!: () => Promise<void> | void
const reservation: AgentRegistrationReservation = Object.freeze({
id,
release: () => {
rawRelease()
// Remove the now-inert ownership effect on manual transaction settle;
// its cleanup is the exact idempotent raw release above.
void disposeEffect()
},
})
this.reservations.set(id, reservation)
try {
disposeEffect = this.ctx.effect(() => rawRelease, `agents.reserve(${id})`)
} catch (error: unknown) {
rawRelease()
throw error
}
return reservation
}
/**
* Register the agent-creation factory (the loop calls this on construction,
* effect-scoped). Throws if a factory is already registered. Returns the
@@ -269,43 +344,87 @@ export class AgentRegistry extends Service {
* returned detach closure into its pre-installed composite teardown before
* calling {@link announce}. Ordinary callers use {@link register}.
* @param agent - the prepared, unpublished agent.
* @param reservation - the exact unpublished-id capability, when a factory
* reserved this id across setup.
* @returns an idempotent closure that removes this exact entry and emits
* `agent/disposed` with listener failures contained.
*/
enter(agent: Agent): () => void {
if (this.store.has(agent.id)) {
throw new Error(`agent "${agent.id}" is already registered`)
enter(agent: Agent, reservation?: AgentRegistrationReservation): () => void {
const id = agent.id
if (typeof id !== 'string') throw new TypeError('agent id must be a string')
const held = this.reservations.get(id)
if (reservation === undefined) {
if (held !== undefined) throw new Error(`agent "${id}" is reserved for unpublished creation`)
} else if (reservation.id !== id || held !== reservation) {
throw new Error(`agent "${id}" registration reservation is not active for this id`)
}
this.store.set(agent.id, agent)
if (this.acceptedIds.has(agent)) {
throw new Error(`agent "${id}" is already registered`)
}
if (this.store.has(id)) {
throw new Error(`agent "${id}" is already registered`)
}
try {
// Registration accepts ownership of the public identity contract. Pin an
// own data slot from the one captured value so a custom JavaScript Agent
// with a getter or writable field cannot later present a different id to
// event listeners while the registry still owns the accepted key.
Object.defineProperty(agent, 'id', {
value: id,
enumerable: true,
writable: false,
configurable: false,
})
} catch {
// Only the engine's property-definition failure is swallowed; the stable
// public error below is the registration contract exposed to callers.
throw new TypeError('agent id must be installable as a stable own property')
}
this.store.set(id, agent)
this.acceptedIds.set(agent, id)
let entered = true
return () => {
if (!entered) return
entered = false
this.store.delete(agent.id)
this.store.delete(id)
this.acceptedIds.delete(agent)
// An insertion rolled back before announce was never externally created,
// so emitting disposed would invent an impossible lifecycle edge. Marking
// happens before the created emit: if a later created listener throws,
// earlier listeners may already have observed it and must see disposal.
if (!this.announced.delete(agent)) return
try {
this.ctx.emit(scopeTarget(agent, agent), 'agent/disposed', agent)
} catch (error: unknown) {
this.ctx.logger.warn(`agent "${agent.id}": agent/disposed listener threw: ${String(error)}`)
}
agentEvents(this.ctx, agent).emit('agent/disposed')
}
}
/**
* Announce an agent previously inserted with {@link enter}.
* @param agent - the live inserted agent to announce.
* @throws if `agent` is not the exact live registry entry for its id.
* @throws if `agent` is not the exact live registry entry for its id, or its
* creation announcement already began (including a reentrant call from a
* creation listener).
*/
announce(agent: Agent): void {
if (this.store.get(agent.id) !== agent) {
throw new Error(`agent "${agent.id}" is not live in this registry`)
const id = this.acceptedIds.get(agent)
if (id === undefined || this.store.get(id) !== agent) {
throw new Error(`agent "${id ?? '<unknown>'}" is not live in this registry`)
}
if (this.announced.has(agent)) {
throw new Error(`agent "${id}" was already announced`)
}
// Mark before dispatch so a listener cannot recursively create a second
// lifecycle edge; detach still pairs a partially delivered first edge.
this.announced.add(agent)
this.ctx.emit(scopeTarget(agent, agent), 'agent/created', agent)
const args: unknown[] = [scopeTarget(agent, agent), 'agent/created', agent]
for (const callback of this.ctx.events.dispatch('emit', args)) {
// A synchronous creation failure vetoes publication and rolls back.
// Returned-promise rejection happens after this synchronous boundary, so
// observe and report it instead of leaking an unhandled rejection.
const returned: unknown = callback(...args)
void Promise.resolve(returned).catch((error: unknown) => {
this.ctx.logger.warn(`agent "${id}": agent/created listener rejected: ${renderThrown(error)}`)
})
}
}
/**

View File

@@ -288,7 +288,10 @@ declare module 'cordis' {
* {@link AgentRegistry}. Its session is already live in the session store,
* but concrete factories may keep driving verbs locked until the subsequent
* `agent/session-start` boundary; that event is the first supported place
* to inject or queue work during startup.
* to inject or queue work during startup. A synchronous listener throw
* vetoes publication and rollback emits the matching disposal edges;
* returned-promise rejection is observed and logged but cannot
* retroactively veto this synchronous boundary.
* @param agent - the newly registered agent with its live session and completed setup.
* Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): a listener registered
* through `agent.ctx` fires only for that agent's dispatches; a listener on a

View File

@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import { Session, SessionId } from '@deepseek-ai/dsh-session'
import AgentRegistry, { Agent, AgentId } from '@deepseek-ai/dsh-agent'
import AgentRegistry, { Agent, AgentId, agentEvents } from '@deepseek-ai/dsh-agent'
function stubAgent(rawId: string): Agent {
const id = AgentId(rawId)
@@ -78,6 +78,32 @@ describe('AgentRegistry', () => {
expect(ctx.agents.get(AgentId('main'))).toBeUndefined()
})
it('observes async agent/created rejection without rolling back or starving peers', async () => {
const ctx = new Context()
await ctx.plugin(AgentRegistry)
const warnings: string[] = []
ctx.logger.warn = ((message: unknown) => { warnings.push(String(message)) }) as typeof ctx.logger.warn
const hostile = { [Symbol.toPrimitive]() { throw new Error('cannot stringify') } }
const heard: string[] = []
ctx.on('agent/created', () => Promise.reject(new Error('ordinary async failure')) as never)
// eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- hostile thrown values are the boundary under test
ctx.on('agent/created', () => Promise.reject(hostile) as never)
ctx.on('agent/created', (agent) => { heard.push(agent.id) })
const agent = stubAgent('async-created')
const dispose = ctx.agents.register(agent)
await Promise.resolve()
await Promise.resolve()
expect(ctx.agents.get(agent.id)).toBe(agent)
expect(heard).toEqual(['async-created'])
expect(warnings).toEqual([
'agent "async-created": agent/created listener rejected: Error: ordinary async failure',
'agent "async-created": agent/created listener rejected: <unrenderable thrown value>',
])
await dispose()
})
it('splits insertion from announcement and makes the detach exact/idempotent', async () => {
const ctx = new Context()
await ctx.plugin(AgentRegistry)
@@ -107,6 +133,149 @@ describe('AgentRegistry', () => {
// no disposed-without-created notification.
expect(disposed).toEqual([first])
})
it('captures and pins one runtime id before insertion, announcement, and detach', async () => {
const ctx = new Context()
await ctx.plugin(AgentRegistry)
const existing = stubAgent('occupied')
const disposeExisting = ctx.agents.register(existing)
const candidate = stubAgent('placeholder')
let reads = 0
Object.defineProperty(candidate, 'id', {
configurable: true,
get() {
reads += 1
return reads === 1 ? AgentId('accepted') : AgentId('occupied')
},
})
const detach = ctx.agents.enter(candidate)
expect(reads).toBe(1)
expect(candidate.id).toBe('accepted')
expect(reads).toBe(1)
expect(Object.getOwnPropertyDescriptor(candidate, 'id')).toMatchObject({
configurable: false,
writable: false,
value: 'accepted',
})
expect(ctx.agents.get(AgentId('accepted'))).toBe(candidate)
expect(ctx.agents.get(AgentId('occupied'))).toBe(existing)
expect(() => ctx.agents.enter(candidate)).toThrow(/already registered/)
ctx.agents.announce(candidate)
detach()
expect(ctx.agents.get(AgentId('accepted'))).toBeUndefined()
expect(ctx.agents.get(AgentId('occupied'))).toBe(existing)
await disposeExisting()
expect(() => ctx.agents.enter({ ...stubAgent('bad'), id: 42 } as unknown as Agent))
.toThrow(/id must be a string/)
const pinnedAccessor = stubAgent('pinned')
Object.defineProperty(pinnedAccessor, 'id', {
configurable: false,
get: () => AgentId('pinned'),
})
expect(() => ctx.agents.enter(pinnedAccessor)).toThrow(/installable as a stable own property/)
})
it('uses an opaque one-id reservation to gate unpublished factory insertion', async () => {
const ctx = new Context()
await ctx.plugin(AgentRegistry)
const held = ctx.agents.reserve(AgentId('held'))
expect(() => ctx.agents.reserve(AgentId('held'))).toThrow(/already registered or reserved/)
expect(() => ctx.agents.enter(stubAgent('held'))).toThrow(/reserved for unpublished creation/)
const other = ctx.agents.reserve(AgentId('other'))
expect(() => ctx.agents.enter(stubAgent('held'), other)).toThrow(/not active for this id/)
const agent = stubAgent('held')
const detach = ctx.agents.enter(agent, held)
ctx.agents.announce(agent)
held.release()
held.release()
expect(ctx.agents.get(AgentId('held'))).toBe(agent)
expect(() => ctx.agents.reserve(AgentId('held'))).toThrow(/already registered or reserved/)
detach()
other.release()
const expired = ctx.agents.reserve(AgentId('expired'))
expired.release()
expect(() => ctx.agents.enter(stubAgent('expired'), expired)).toThrow(/not active for this id/)
expect(() => ctx.agents.reserve(42 as unknown as AgentId)).toThrow(/id must be a string/)
})
it('owns reservations by the calling fiber and rolls back failed ownership registration', async () => {
const ctx = new Context()
await ctx.plugin(AgentRegistry)
let held!: import('@deepseek-ai/dsh-agent').AgentRegistrationReservation
let scopedAgents!: AgentRegistry
const owner = await ctx.plugin(Object.assign((inner: Context) => {
scopedAgents = inner.agents
held = inner.agents.reserve(AgentId('fiber-held'))
}, { inject: ['agents'] }))
expect(() => ctx.agents.reserve(AgentId('fiber-held'))).toThrow(/already registered or reserved/)
await owner.dispose()
const reused = ctx.agents.reserve(AgentId('fiber-held'))
reused.release()
held.release() // idempotent after the automatic owner-disposal release
// A disposed tracker cannot own a new effect. The failed effect install
// must remove the map entry it tentatively reserved before propagating.
expect(() => scopedAgents.reserve(AgentId('inactive-owner'))).toThrow(/inactive context/)
const recovered = ctx.agents.reserve(AgentId('inactive-owner'))
recovered.release()
})
it('rejects direct and reentrant repeat announcements to preserve one lifecycle pair', async () => {
const ctx = new Context()
await ctx.plugin(AgentRegistry)
let created = 0
let disposed = 0
let reentrantError = ''
ctx.on('agent/created', (agent) => {
created += 1
try {
ctx.agents.announce(agent)
} catch (error: unknown) {
reentrantError = String(error)
}
})
ctx.on('agent/disposed', () => { disposed += 1 })
const agent = stubAgent('once')
const detach = ctx.agents.enter(agent)
ctx.agents.announce(agent)
expect(reentrantError).toMatch(/already announced/)
expect(() => { ctx.agents.announce(agent) }).toThrow(/already announced/)
detach()
expect({ created, disposed }).toEqual({ created: 1, disposed: 1 })
})
})
describe('agentEvents()', () => {
it('contains synchronous throws and returned-promise rejections per listener', async () => {
const ctx = new Context()
const warnings: string[] = []
ctx.logger.warn = ((message: unknown) => { warnings.push(String(message)) }) as typeof ctx.logger.warn
const agent = stubAgent('contained')
const heard: string[] = []
const hostile = { [Symbol.toPrimitive]() { throw new Error('cannot stringify') } }
ctx.on('agent/status', () => { throw hostile })
ctx.on('agent/status', () => Promise.reject(new Error('async listener')) as never)
ctx.on('agent/status', (_subject, status) => { heard.push(status) })
expect(() => { agentEvents(ctx, agent).emit('agent/status', 'running') }).not.toThrow()
await Promise.resolve()
await Promise.resolve()
expect(heard).toEqual(['running'])
expect(warnings).toEqual([
'agent event "agent/status" listener threw: <unrenderable thrown value>',
'agent event "agent/status" listener rejected: Error: async listener',
])
})
})
describe('AgentRegistry factory seam', () => {

View File

@@ -9,7 +9,7 @@ Scoped-context registration primitive. `createScope(ctx, key)` mints a Cordis co
- `Scope.rawDispose` The EXACT Cordis disposer for the backing fiber — a composite (generator) effect yields THIS function to nest the scope's teardown at that yield position (Cordis dedupes nested effects by function identity; yielding a wrapper leaves the scope disposing as a concurrent sibling).
- `Scope.dispose(): Promise<void>` Idempotent, shared quiescence boundary for every registration made through the scope. Racing/repeat calls await the same teardown, including when `rawDispose` invoked the underlying single-shot Cordis disposer first.
- `scopeOf(ctx: Context): ScopeKey | undefined` The tag a context (or any context derived from it) carries; `undefined` = context-global.
- `scopeTarget(base: T, key?: ScopeKey): Scoped<T>` Build the dispatch `thisArg` for a scope-filtered event: composes `base`'s own `Context.filter` with the scope predicate (untagged listener ⇒ admitted; tagged ⇒ admitted iff tag === key; `key === undefined` ⇒ untagged only). Listener `this` stays `base`-shaped. `{ global: true }` listeners bypass filtering (Cordis semantics).
- `scopeTarget(base: T, key: ScopeKey | undefined): Scoped<T>` Build the dispatch `thisArg` for a scope-filtered event: capture and compose `base`'s own `Context.filter` with the scope predicate (untagged listener ⇒ admitted; tagged ⇒ admitted iff tag === key; `key === undefined` ⇒ untagged only). The carrier uses a dedicated surrogate proxy target whose immutable filter slot cannot be replaced by a base property pinned before, during, or after construction; ordinary property access, writes, own-key visibility, methods, invocation, and construction delegate to `base`, and callable carriers match the base's constructable/non-constructable shape. For non-overlay base-owned properties, descriptor queries preserve values and flags except that configurable is normalized to `true`, as required to report those properties through an extensible surrogate. Listener `this` stays `base`-shaped. `{ global: true }` listeners bypass filtering (Cordis semantics).
- `Scoped<T>` The compile-time carrier brand: scope-filtered events demand it as their `this` type, so dispatching with a bare subject is a compile error.
- `isScopeCarrier(value)` / `carrierKeyOf(value)` Runtime carrier marks, used by the dev invariants to assert every scope-filtered dispatch carries a carrier keyed to the subject its arguments name.
- `scopeHost(ctx, services)` Test/tooling host that snapshots the requested service list before activation, fails loud with stable missing-service diagnostics, and whose shared `dispose()` waits for both the host fiber and every minted scope, including a child already tearing down through `rawDispose`.

View File

@@ -171,6 +171,20 @@ export function scopeOf(ctx: Context): ScopeKey | undefined {
return (ctx as Context & { [kScope]?: ScopeKey })[kScope]
}
/** Whether a callable has JavaScript's internal construction capability. */
function isConstructable(value: (...args: unknown[]) => unknown): boolean {
try {
// A Proxy has [[Construct]] iff its target does. Its trap returns before
// the engine invokes `value` or reads `value.prototype`, so a hostile but
// constructable callable cannot be mistaken for a non-constructor.
Reflect.construct(new Proxy(value, { construct: () => ({}) }), [])
return true
} catch {
// The harmless outer trap leaves lack of [[Construct]] as the only failure.
return false
}
}
/**
* Build the dispatch carrier for a scope-filtered event: `base` overlaid with
* a `Context.filter` that admits a listener iff
@@ -206,7 +220,10 @@ export function scopeOf(ctx: Context): ScopeKey | undefined {
* @returns the carrier to pass as the dispatch `thisArg`.
*/
export function scopeTarget<T extends object>(base: T, key: ScopeKey | undefined): Scoped<T> {
const baseFilter = (base as { [CordisContext.filter]?: (ctx: Context) => boolean })[CordisContext.filter]
const baseFilter: unknown = (base as { [CordisContext.filter]?: unknown })[CordisContext.filter]
if (baseFilter !== undefined && typeof baseFilter !== 'function') {
throw new TypeError('scope target Context.filter must be a function when present')
}
const filter = (ctx: Context): boolean => {
if (baseFilter && !baseFilter.call(base, ctx)) return false
const tag = scopeOf(ctx)
@@ -214,34 +231,57 @@ export function scopeTarget<T extends object>(base: T, key: ScopeKey | undefined
}
const overlay: Record<string | symbol, unknown> = {
[CordisContext.filter]: filter,
[kCarrier]: { key },
[kCarrier]: Object.freeze({ key }),
}
// A hand-rolled proxy, NOT cordis withProps: withProps delegates gets with
// the PROXY as receiver, so a getter on `base` runs with proxy `this` and a
// method call through the carrier gets a proxy receiver — either one throws
// on a native `#private` field of the subject (TypeError: private member
// not declared). Cordis hands the carrier to listeners as `this`, and the
// event declarations type it `Scoped<Agent>` — so subject method calls
// through it are a SUPPORTED shape and must reach the real object: gets
// delegate with `base` as receiver, functions come back bound to `base`,
// and sets land on `base` directly.
return new Proxy(base, {
// Use a dedicated extensible proxy TARGET, never `base` itself. Proxy get
// invariants force a trap to return a base's non-configurable/non-writable
// own value verbatim; if a caller pinned Context.filter during or after
// construction, a base-target proxy would therefore silently replace the
// composed scope predicate with the caller's filter. The surrogate owns the
// two immutable overlay slots, so later descriptor changes on `base` cannot
// affect isolation. It shares the base prototype and delegates ordinary
// reads/writes/keys to preserve the supported transparent shape. Callable
// targets use native bound built-ins so V8 contributes no user-code surface;
// the chosen built-in matches whether `base` has [[Construct]], and the traps
// below delegate the actual call/construction to `base`.
const callableBase = typeof base === 'function'
? base as unknown as (...args: unknown[]) => unknown
: undefined
const constructable = callableBase !== undefined && isConstructable(callableBase)
const target: object = callableBase === undefined
? {}
: constructable
? Object.bind(undefined)
: Math.max.bind(undefined)
Reflect.setPrototypeOf(target, Reflect.getPrototypeOf(base))
Object.defineProperties(target, {
[CordisContext.filter]: {
value: filter,
enumerable: false,
writable: false,
configurable: false,
},
[kCarrier]: {
value: overlay[kCarrier],
enumerable: false,
writable: false,
configurable: false,
},
})
const carrier = new Proxy(target, {
get(target, prop) {
// Proxy get invariants pin what this trap may report for a
// non-configurable OWN property of the base: a non-writable data prop
// must be reported AS-IS (neither overlaid nor bound), a getterless
// accessor as undefined — checked FIRST so even an overlay key
// colliding with a frozen own prop of a (pathological) base yields the
// base's value instead of an engine TypeError. Such a base forgoes
// scope filtering; no production base freezes these keys.
// The callable surrogate has engine-owned pinned properties (`prototype`,
// `caller`, …); honor those target invariants. For object carriers the
// only pinned target properties are the exact overlay values above.
const own = Reflect.getOwnPropertyDescriptor(target, prop)
const pinned = own !== undefined && own.configurable === false
&& own.get === undefined && own.writable !== true
// hasOwn, not `in`: the overlay literal inherits Object.prototype, so
// `in` would claim `toString`/`constructor` and shadow the subject's.
if (!pinned && Object.hasOwn(overlay, prop)) return overlay[prop]
const value: unknown = Reflect.get(target, prop, target)
if (typeof value !== 'function' || pinned) return value
if (pinned) {
const value: unknown = Reflect.get(target, prop, target)
return value
}
const value: unknown = Reflect.get(base, prop, base)
if (typeof value !== 'function') return value
// `constructor` is looked up, never invoked as a subject method — keep
// the real one (withProps special-cases it the same way), so
// `carrier.constructor` still identifies the subject's class.
@@ -249,12 +289,66 @@ export function scopeTarget<T extends object>(base: T, key: ScopeKey | undefined
// `Function.prototype.bind` types as `any`; the value is structurally
// T[prop] and the trap's contract is untyped (`any`), so unknown is the
// honest safe return.
return value.bind(target) as unknown
return value.bind(base) as unknown
},
set(target, prop, value) {
return Reflect.set(target, prop, value, target)
set(_target, prop, value) {
if (Object.hasOwn(overlay, prop)) return false
return Reflect.set(base, prop, value, base)
},
}) as Scoped<T>
has(_target, prop) {
// A Proxy may not hide a non-configurable target key. Configurable
// surrogate-only keys (bound-function name/length) are omitted; the
// base's own/inherited surface remains authoritative.
const own = Reflect.getOwnPropertyDescriptor(target, prop)
return own?.configurable === false || Reflect.has(base, prop)
},
ownKeys(target) {
const requiredTargetKeys = Reflect.ownKeys(target).filter((prop) => {
return Reflect.getOwnPropertyDescriptor(target, prop)?.configurable === false
})
return [...new Set([...requiredTargetKeys, ...Reflect.ownKeys(base)])]
},
getOwnPropertyDescriptor(target, prop) {
const targetDescriptor = Reflect.getOwnPropertyDescriptor(target, prop)
if (targetDescriptor?.configurable === false) return targetDescriptor
const baseDescriptor = Reflect.getOwnPropertyDescriptor(base, prop)
if (baseDescriptor !== undefined) return { ...baseDescriptor, configurable: true }
// Configurable surrogate-only function metadata is intentionally hidden.
return undefined
},
defineProperty(_target, prop, attributes) {
if (Object.hasOwn(overlay, prop)) return false
return Reflect.defineProperty(base, prop, attributes)
},
deleteProperty(_target, prop) {
if (Object.hasOwn(overlay, prop)) return false
return Reflect.deleteProperty(base, prop)
},
preventExtensions() {
// Keeping the surrogate extensible is required for ownKeys to report
// caller-owned base fields that may change over the carrier's lifetime.
return false
},
setPrototypeOf() {
// The carrier prototype and base delegation must not be split.
return false
},
apply(_target, thisArg, args) {
const callable = callableBase as (...values: unknown[]) => unknown
const result: unknown = Reflect.apply(callable, thisArg, args)
return result
},
construct(_target, args, newTarget) {
const constructor = callableBase as unknown as new (...values: unknown[]) => object
const result: unknown = Reflect.construct(
constructor,
args,
newTarget === carrier ? constructor : newTarget,
)
return result as object
},
})
return carrier as Scoped<T>
}
/**
@@ -266,10 +360,8 @@ export function scopeTarget<T extends object>(base: T, key: ScopeKey | undefined
* @returns true iff `value` came from {@link scopeTarget}.
*/
export function isScopeCarrier(value: unknown): value is Scoped<object> {
if (typeof value !== 'object' || value === null) return false
// A property READ, not an `in` check: the carrier overlays its marks in the
// get trap only (no `has` trap), so `kCarrier in carrier` would fall
// through to the wrapped base and always answer false.
if ((typeof value !== 'object' && typeof value !== 'function') || value === null) return false
// A property read checks the immutable marker owned by the surrogate target.
return (value as { [kCarrier]?: { key: ScopeKey | undefined } })[kCarrier] !== undefined
}

View File

@@ -232,7 +232,7 @@ describe('scopeTarget dispatch filtering', () => {
expect(detached()).toBe(2)
})
it('delegates sets to the base and leaves frozen own function props unbound (proxy invariant)', () => {
it('delegates the ordinary reflective surface while keeping overlays immutable', () => {
const frozenFn = (): string => 'frozen'
const base: { mutable: number; pinned: () => string; toString: () => string } = {
mutable: 0,
@@ -243,25 +243,158 @@ describe('scopeTarget dispatch filtering', () => {
const carrier = scopeTarget(base, undefined)
carrier.mutable = 7
expect(base.mutable).toBe(7) // sets land on the base, not a detached overlay
// A non-configurable, non-writable own data prop must be reported
// unchanged (binding it would violate the proxy get invariant).
expect(carrier.pinned).toBe(frozenFn)
// The surrogate target frees reads from the base property's proxy
// invariant, so even a frozen own method can be safely bound to the base.
expect(carrier.pinned).not.toBe(frozenFn)
expect(carrier.pinned()).toBe('frozen')
// The overlay literal inherits Object.prototype; hasOwn (not `in`) keeps
// it from shadowing the subject's own prototype-surface members.
expect(String(carrier)).toBe('base-str')
expect('mutable' in carrier).toBe(true)
expect(Object.hasOwn(carrier, 'mutable')).toBe(true)
expect(Object.keys(carrier)).toEqual(['mutable', 'pinned', 'toString'])
Object.defineProperty(carrier, 'extra', { value: 1, configurable: true })
expect((base as typeof base & { extra?: number }).extra).toBe(1)
expect(delete (carrier as typeof carrier & { extra?: number }).extra).toBe(true)
expect(Reflect.preventExtensions(carrier)).toBe(false)
expect(Reflect.setPrototypeOf(carrier, null)).toBe(false)
})
it('honors the get invariant even when an overlay key collides with a frozen own prop of the base', () => {
// Pathological but engine-enforced: a base whose own [Context.filter] is
// a non-configurable, non-writable data prop pins what any proxy over it
// may report for that key. The carrier must yield the base's value (an
// overlay there would be a runtime TypeError from the engine, not a
// filtering choice). Such a base forgoes scope filtering by construction.
it('keeps isolation when the base filter is pinned before, during, or after construction', async () => {
const ctx = new Context()
const keyA = { name: 'A' }
const keyB = { name: 'B' }
const scopeA = await mintScope(ctx, keyA)
const scopeB = await mintScope(ctx, keyB)
const heard: string[] = []
ctx.on('scope-test/ping', value => void heard.push(`global:${value}`))
scopeA.ctx.on('scope-test/ping', value => void heard.push(`A:${value}`))
scopeB.ctx.on('scope-test/ping', value => void heard.push(`B:${value}`))
const pinnedFilter = (): boolean => true
const base = {}
Object.defineProperty(base, Context.filter, { value: pinnedFilter, writable: false, configurable: false })
const carrier = scopeTarget(base, { name: 'key' })
expect((carrier as Record<symbol, unknown>)[Context.filter]).toBe(pinnedFilter)
const pinnedData = {}
Object.defineProperty(pinnedData, Context.filter, {
value: pinnedFilter,
writable: false,
configurable: false,
})
const pinnedCarrier = scopeTarget(pinnedData, keyA)
ctx.emit(pinnedCarrier, 'scope-test/ping', 'before')
const duringRead = {}
Object.defineProperty(duringRead, Context.filter, {
configurable: true,
get() {
Object.defineProperty(duringRead, Context.filter, {
value: pinnedFilter,
writable: false,
configurable: false,
})
return pinnedFilter
},
})
ctx.emit(scopeTarget(duringRead, keyA), 'scope-test/ping', 'during')
const pinnedAfter = { [Context.filter]: pinnedFilter }
const afterCarrier = scopeTarget(pinnedAfter, keyA)
Object.defineProperty(pinnedAfter, Context.filter, {
value: pinnedFilter,
writable: false,
configurable: false,
})
ctx.emit(afterCarrier, 'scope-test/ping', 'after')
const pinnedGetterless = {}
Object.defineProperty(pinnedGetterless, Context.filter, { set(_value: unknown) {}, configurable: false })
ctx.emit(scopeTarget(pinnedGetterless, keyA), 'scope-test/ping', 'getterless')
expect(heard).toEqual([
'global:before', 'A:before',
'global:during', 'A:during',
'global:after', 'A:after',
'global:getterless', 'A:getterless',
])
expect((pinnedCarrier as Record<symbol, unknown>)[Context.filter]).not.toBe(pinnedFilter)
expect(Reflect.set(pinnedCarrier, Context.filter, pinnedFilter)).toBe(false)
expect(Reflect.defineProperty(pinnedCarrier, Context.filter, { value: pinnedFilter })).toBe(false)
expect(Reflect.deleteProperty(pinnedCarrier, Context.filter)).toBe(false)
expect(() => scopeTarget({ [Context.filter]: 1 }, { name: 'A' })).toThrow(
/Context\.filter must be a function/,
)
})
it('preserves callable and constructable bases', () => {
function Subject(this: { value?: number }, value: number): number {
if (new.target) {
this.value = value
return value
}
return value * 2
}
const carrier = scopeTarget(Subject as typeof Subject & (new (value: number) => { value: number }), {
name: 'callable',
})
const called: unknown = Reflect.apply(carrier, { value: 0 }, [3])
expect(called).toBe(6)
const instance = new carrier(4)
expect(instance).toBeInstanceOf(Subject)
expect(instance.value).toBe(4)
const prototypeDescriptor = Object.getOwnPropertyDescriptor(carrier, 'prototype')
const subjectPrototype: unknown = Reflect.get(Subject, 'prototype')
expect(prototypeDescriptor?.configurable).toBe(true)
expect(prototypeDescriptor?.value).toBe(subjectPrototype)
class Derived extends carrier {}
const derived = new Derived(5)
expect(derived).toBeInstanceOf(Derived)
expect(derived).toBeInstanceOf(Subject)
expect(derived.value).toBe(5)
expect(isScopeCarrier(carrier)).toBe(true)
})
it('matches non-constructable and bound-constructor function shapes', () => {
const arrow = (value: number): number => value + 1
const arrowCarrier = scopeTarget(arrow, { name: 'arrow' })
const arrowResult: unknown = Reflect.apply(arrowCarrier, undefined, [2])
expect(arrowResult).toBe(3)
expect('prototype' in arrowCarrier).toBe(false)
expect(Object.getOwnPropertyDescriptor(arrowCarrier, 'prototype')).toBeUndefined()
expect(() => { Reflect.construct(arrowCarrier, []) }).toThrow(TypeError)
class Subject {
constructor(readonly value: number) {}
}
const bound = Subject.bind(undefined, 7)
const boundCarrier = scopeTarget(bound, { name: 'bound-constructor' })
expect('prototype' in boundCarrier).toBe(false)
expect(Object.getOwnPropertyDescriptor(boundCarrier, 'prototype')).toBeUndefined()
const instance = new boundCarrier()
expect(instance).toBeInstanceOf(Subject)
expect(instance.value).toBe(7)
})
it('detects construction without reading a hostile base prototype', () => {
class Subject {
constructor(readonly value: number) {}
}
let prototypeReads = 0
const hostile = new Proxy(Subject, {
get(target, prop, receiver) {
if (prop === 'prototype') {
prototypeReads += 1
throw new Error('hostile prototype getter')
}
return Reflect.get(target, prop, receiver) as unknown
},
})
const carrier = scopeTarget(hostile, { name: 'hostile-constructor' })
expect(prototypeReads).toBe(0)
const instance: unknown = Reflect.construct(carrier, [9], Subject)
expect(instance).toBeInstanceOf(Subject)
expect(instance).toMatchObject({ value: 9 })
expect(prototypeReads).toBe(0)
})
it('keeps the real constructor: class identity survives the carrier', () => {

View File

@@ -4,7 +4,7 @@ Event-sourced session log and in-memory store. A `Session` is the append-only so
## Service: `SessionStore` (ctx key: `sessions`)
Creates and holds event-sourced `Session` instances. Persistence is intentionally not implemented here — plugins subscribe to `session/event` and flush on `session/flush`.
Creates and holds event-sourced `Session` instances. Persistence is intentionally not implemented here — plugins subscribe to `session/event`, flush on `session/flush`, and may mirror the paired `session/created`/`session/disposed` lifecycle.
### Public API
@@ -16,17 +16,18 @@ Creates and holds event-sourced `Session` instances. Persistence is intentionall
#### Advanced: ordered-teardown lifecycle primitives
`create()` covers the common case (the session is owned by the calling fiber). When a session must be torn down **in order with another resource** — so a final flush is captured before `onAppend` detaches — `create()`'s self-contained effect is wrong, because a fiber unload disposes sibling effects *concurrently*. For that, split the lifecycle and fold it into the owner's single effect:
`create()` covers the common case (the session is owned by the calling fiber). When a session must be torn down **in order with another resource** — so a final flush is captured before the store-owned append observer detaches — `create()`'s self-contained effect is wrong, because a fiber unload disposes sibling effects *concurrently*. For that, split the lifecycle and fold it into the owner's single effect:
- `ctx.sessions.prepare(id?, options?): Session` — read `options.seed`/`options.meta` once, validate and detach the metadata/header, and construct the `Session` WITHOUT entering it into the store. Same options as `create`.
- `ctx.sessions.enter(session): () => void` — wire `onAppend``session/event`, capture its scope carrier, and add the session to the store; returns the idempotent DETACH disposer, which clears both notification and carrier state. Does NOT emit `session/created` (the caller installs the disposer first, then calls `announce`, so a throwing listener rolls the attach back). It re-checks the id because public `prepare`/`enter` calls may be interleaved; a stale prepared object must not overwrite a live same-id session.
- `ctx.sessions.announce(session): void` — emit `session/created` for an entered session.
- `ctx.sessions.reserve(id): SessionRegistrationReservation` — hold an unpublished id under the calling fiber and construct its one owned Session through `reservation.prepare(options?)`. Until `release()` or owner unload, bare `prepare`/`create`/`enter` calls for that id reject; the factory later presents the exact capability to `enter`, making setup-time publication structurally impossible without leaking an abandoned reservation across HMR disposal.
- `ctx.sessions.enter(session, reservation?): () => void` — install the module-private `session/event` observer, capture its scope carrier, and add the session under one accepted id; returns the idempotent DETACH disposer, which clears notification, carrier, and accepted-key state. Does NOT emit `session/created` (the caller installs the disposer first, then calls `announce`, so a throwing listener rolls the attach back). It re-checks the id because public `prepare`/`enter` calls may be interleaved; a stale prepared object must not overwrite a live same-id session. A factory passes the opaque capability from `reserve(id)` so setup cannot enter the reserved session or publish a same-id replacement before the owning transaction.
- `ctx.sessions.announce(session): void` — begin the one allowed `session/created` announcement for an entered session; repeat and reentrant calls reject before dispatch. Its detach emits `session/disposed` exactly once, including rollback after a partially delivered creation notification; a never-announced entry emits neither edge.
`dsh-agent-loop` is the canonical consumer: after unpublished agent setup it enters both session and agent before announcing either, then nests loop stop, agent removal, session detach, and scope unwind in one ordered lifecycle. The final flush therefore settles before this package detaches the session, whether teardown starts from an `AgentHandle` or owner-fiber unload.
### Live service events
The store announces creation, publishes each append, and provides an awaited durability checkpoint. Exact `session/*` signatures, modes, and scope-carrier behavior live in the generated [Cordis event catalog](../../../docs/cordis-catalog/events.md); the append-only payload vocabulary is separately generated into the [persistence catalog](../../../docs/persistence-catalog.md). Persistence consumers write behind from the append notification and drain on the store-owned flush entry point rather than dispatching the event directly.
The store pairs announced creation with disposal, publishes each append, and provides an awaited durability checkpoint. Disposal listener failures, including returned-promise rejections, are contained per observer so teardown cannot be interrupted. Exact `session/*` signatures, modes, and scope-carrier behavior live in the generated [Cordis event catalog](../../../docs/cordis-catalog/events.md); the append-only payload vocabulary is separately generated into the [persistence catalog](../../../docs/persistence-catalog.md). Persistence consumers write behind from the append notification and drain on the store-owned flush entry point rather than dispatching the event directly.
### Class: `Session`
@@ -37,8 +38,8 @@ Plain class (not a Cordis Service). Create via `ctx.sessions.create()`.
- `session.deriveEventMessage(event): Message | null` — the per-event projection `deriveMessages()` folds: one event's derived message (an unfrozen clone), or `null` when it produces none (a non-surface event, or an empty-content `assistant/message` hosting only usage). External reconstructors and the dev invariant fold the same function over a log prefix's surface, so no two paths can disagree about what a request's messages were (the reconstructability RFC).
- `session.surface: SurfaceManager` — the derived surface, lazily rebuilt from `surfaceOp` markers in the log. Processes only new events (delta) on each access — the log is append-only, so prior events never change. `surface.replaceGeneration` is the rewrite signal: bumped by every folded `replace` and by `invalidate()`, never reset, so an incremental consumer comparing generations cannot be fooled.
- `session.events` — a cached, frozen array snapshot over deep-frozen events. Repeated reads without an append return the same array; an append invalidates the cache and the next read returns a new snapshot, while earlier snapshots stay unchanged. Neither a cast nor a retained reference can push into the live log or rewrite an accepted event.
- `session.seq`, `session.id`
- `session.header: SessionHeader` — detached, deep-frozen creation metadata (`version`, `id`, `createdAt`, optional `cwd`/`parentSession`/`seedLength`). Construction validates its lossless-JSON shape and requires the header id to match `session.id`, so a caller cannot later mutate persistence routing or lineage through an aliased header. Kept out of the event log (a storage concern, not replayable state); a minimal header (stamped with the current `SESSION_FORMAT_VERSION`) is synthesized for bare `Session` construction.
- `session.seq`, `session.id``id` is a non-writable, non-configurable runtime identity slot, not merely TypeScript-readonly.
- `session.header: SessionHeader` — detached, deep-frozen creation metadata (`version`, `id`, `createdAt`, optional `cwd`/`parentSession`/`seedLength`) published through a non-writable, non-configurable slot. Construction validates its lossless-JSON shape and requires the header id to match `session.id`, so a caller cannot later replace or mutate persistence routing or lineage. Kept out of the event log (a storage concern, not replayable state); a minimal header (stamped with the current `SESSION_FORMAT_VERSION`) is synthesized for bare `Session` construction.
### Lossless JSON utilities

View File

@@ -34,7 +34,10 @@ declare module 'cordis' {
interface Events {
/**
* A session was created in the store.
* A session was created in the store. A synchronous listener throw vetoes
* publication and rollback emits the matching `session/disposed` edge;
* returned-promise rejection is observed and logged but cannot retroactively
* veto this synchronous boundary.
* Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): the carrier is the
* session's owner scope, captured when the session was ENTERED (an agent's
* session is entered through `agent.ctx`, so its events dispatch in that
@@ -45,6 +48,18 @@ declare module 'cordis' {
* @mode emit
*/
'session/created'(this: Scoped<Session>, session: Session): void
/**
* A previously announced session left the store. Emitted exactly once on
* normal detach or publication rollback, and never for a prepared/entered
* session whose `session/created` announcement did not begin. Listener
* failures (including returned-promise rejections) are logged and contained
* per listener so teardown always reaches quiescence.
* Scope-filtered dispatch uses the same owner carrier captured at entry;
* agent-scoped listeners hear only their own session's teardown.
* @param session - the session that is no longer live in the store.
* @mode emit
*/
'session/disposed'(this: Scoped<Session>, session: Session): void
/**
* An event was appended to a session log (sync, fire-and-forget). This is
* the per-append feed a UI or invariant plugin tails.
@@ -253,6 +268,17 @@ function assertSessionEventEnvelope(value: Record<string, unknown>, index: numbe
}
}
/** Render an arbitrary thrown value without allowing coercion to throw again. */
function renderThrown(value: unknown): string {
try {
return value instanceof Error ? `${value.name}: ${value.message}` : String(value)
} catch {
return '<unrenderable thrown value>'
}
}
const appendObservers = new WeakMap<Session, (event: SessionEvent) => void>()
/**
* An event-sourced session: an append-only log of {@link SessionEvent}s.
*
@@ -261,8 +287,6 @@ function assertSessionEventEnvelope(value: Record<string, unknown>, index: numbe
*/
export class Session {
private log: SessionEvent[] = []
/** Set by the store so appends are observable; undefined when detached. */
onAppend: ((event: SessionEvent) => void) | undefined
/**
* Derived surface — a cached linked list of message-producing events.
@@ -336,6 +360,14 @@ export class Session {
})
}
this.header = snapshotSessionHeader(id, header)
// TypeScript readonly prevents ordinary typed assignment only. Pin both
// public identity bindings at runtime too: setup/plugins receive the live
// Session object, and replacing either slot would split registry keys,
// persistence routing, and the already-validated header.
Object.defineProperties(this, {
id: { value: id, enumerable: true, writable: false, configurable: false },
header: { value: this.header, enumerable: true, writable: false, configurable: false },
})
}
/** Cached immutable public snapshot of the private append-only log. */
@@ -359,8 +391,8 @@ export class Session {
/**
* Append one typed event to the log and synchronously notify observers via
* `onAppend`. The hot path never blocks on I/O — persistence plugins buffer
* asynchronously.
* the store-owned, module-private append observer. The hot path never blocks
* on I/O — persistence plugins buffer asynchronously.
*
* @param type - The event type (key of {@link SessionEventMap}).
* @param data - The event payload; must be JSON-serializable.
@@ -444,7 +476,7 @@ export class Session {
const acceptedEvent = deepFreeze(event)
this.log.push(acceptedEvent as unknown as SessionEvent)
this.eventsSnapshot = undefined
this.onAppend?.(acceptedEvent as unknown as SessionEvent)
appendObservers.get(this)?.(acceptedEvent as unknown as SessionEvent)
return acceptedEvent
}
@@ -599,6 +631,29 @@ export class SessionForkError extends Error {
}
}
/**
* Unforgeable ownership handle for one unpublished session id. A factory keeps
* this capability across load/setup, preventing setup code from entering the
* prepared Session or publishing a replacement under the same id. Obtain it
* only from {@link SessionStore.reserve}.
*/
export interface SessionRegistrationReservation {
/** The reserved store id. */
readonly id: SessionId
/**
* Construct the one Session owned by this reservation.
* @param options - seed events and creation metadata.
* @returns the still-unpublished Session.
*/
prepare(options?: CreateSessionOptions): Session
/**
* Release the unpublished reservation; idempotent. The store also releases
* it automatically when the fiber that called `reserve` disposes.
* @returns nothing.
*/
release(): void
}
/**
* In-memory session store (`ctx.sessions`).
*
@@ -607,6 +662,14 @@ export class SessionForkError extends Error {
*/
export class SessionStore extends Service {
private store = new Map<SessionId, Session>()
/** The one accepted map key for each live session; never reread caller state. */
private acceptedIds = new WeakMap<Session, SessionId>()
/** Sessions whose creation announcement began and therefore require a pair. */
private announced = new WeakSet<Session>()
/** Unpublished identities held across factory load/setup transactions. */
private reservations = new Map<SessionId, SessionRegistrationReservation>()
/** The exact prepared object owned by each reservation capability. */
private reservedSessions = new WeakMap<SessionRegistrationReservation, Session>()
/**
* Each live session's dispatch carrier, captured at {@link enter} from the
* ENTERING context's scope tag (an agent session is entered through
@@ -621,6 +684,59 @@ export class SessionStore extends Service {
super(ctx, 'sessions')
}
/**
* Reserve one unpublished session id across an asynchronous factory
* transaction. Bare `prepare`/`create`/`enter` calls for the id reject until
* release; the capability constructs exactly one Session and is passed back
* to {@link enter} at publication. The reservation belongs to the calling
* fiber, so owner unload releases an abandoned id automatically.
* @param id - the session id the transaction will publish.
* @returns the opaque reservation capability.
* @throws if the id is malformed, live, or already reserved.
*/
reserve(id: SessionId): SessionRegistrationReservation {
if (typeof id !== 'string') throw new TypeError('session id must be a string')
if (this.store.has(id) || this.reservations.has(id)) {
throw new Error(`session "${id}" already exists or is reserved`)
}
let active = true
let prepared = false
const rawRelease = (): void => {
if (!active) return
active = false
this.reservedSessions.delete(reservation)
this.reservations.delete(id)
}
let disposeEffect!: () => Promise<void> | void
const reservation: SessionRegistrationReservation = Object.freeze({
id,
prepare: (options?: CreateSessionOptions) => {
if (!active) {
throw new Error(`session "${id}" reservation is no longer active`)
}
if (prepared) throw new Error(`session "${id}" reservation already prepared a session`)
prepared = true
const session = this.prepareReserved(id, options, reservation)
this.reservedSessions.set(reservation, session)
return session
},
release: () => {
rawRelease()
// Remove the now-inert ownership effect on manual transaction settle;
// its cleanup is the exact idempotent raw release above.
void disposeEffect()
},
})
this.reservations.set(id, reservation)
try {
disposeEffect = this.ctx.effect(() => rawRelease, `sessions.reserve(${id})`)
} catch (error: unknown) {
rawRelease()
throw error
}
return reservation
}
/**
* Create a session owned by the calling fiber: disposing that fiber stops
* event notification and removes the session from the store. `options.seed`
@@ -630,7 +746,7 @@ export class SessionStore extends Service {
* fills `version`/`id`/`createdAt`).
*
* For an agent whose session must be torn down IN ORDER with its loop (so the
* loop's final flush is captured before `onAppend` detaches), do NOT use this
* loop's final flush is captured before the store-owned observer detaches), do NOT use this
* — fold the session lifecycle into the agent's own effect via
* {@link prepare} + {@link enter} + {@link announce} (see `dsh-agent-loop`'s
* `startOwned`).
@@ -647,7 +763,7 @@ export class SessionStore extends Service {
// Single effect owned by the calling fiber. Yield the detach BEFORE
// announcing so a throwing `session/created` listener rolls the attach back
// (the generator effect disposes already-yielded disposers on a throw)
// instead of leaking the store entry + onAppend.
// instead of leaking the store entry + append observer.
this.ctx.effect(function* (this: SessionStore) {
yield this.enter(session)
this.announce(session)
@@ -661,7 +777,7 @@ export class SessionStore extends Service {
* Pairs with {@link enter} + {@link announce}: a caller that owns a composite
* `ctx.effect` (the agent factory) folds the session lifecycle into that ONE
* effect so a fiber unload tears the session + agent down as a single ORDERED
* chain rather than as racing sibling effects — which would detach `onAppend`
* chain rather than as racing sibling effects — which would detach the append observer
* before the loop's closing `session/flush`, dropping the closing events.
*
* @param id - the session id; omitted, the store mints `session-<n>`.
@@ -672,7 +788,27 @@ export class SessionStore extends Service {
* non-absolute path.
*/
prepare(id?: SessionId, options?: CreateSessionOptions): Session {
const sessionId = SessionId(id ?? `session-${++this.counter}`)
return this.prepareReserved(id, options)
}
/** Shared prepare implementation, optionally authorized by a reservation. */
private prepareReserved(
id?: SessionId,
options?: CreateSessionOptions,
reservation?: SessionRegistrationReservation,
): Session {
let sessionId: SessionId
if (id === undefined) {
do sessionId = SessionId(`session-${++this.counter}`)
while (this.store.has(sessionId) || this.reservations.has(sessionId))
} else {
sessionId = SessionId(id)
}
if (typeof sessionId !== 'string') throw new TypeError('session id must be a string')
const held = this.reservations.get(sessionId)
if (reservation === undefined && held !== undefined) {
throw new Error(`session "${sessionId}" is reserved for unpublished creation`)
}
if (this.store.has(sessionId)) throw new Error(`session "${sessionId}" already exists`)
const seed = options?.seed
const meta = snapshotSessionMeta(options?.meta)
@@ -691,9 +827,9 @@ export class SessionStore extends Service {
}
/**
* Enter a {@link prepare}d session into the store: wire `onAppend` →
* `session/event` and add it to the store. Returns the DETACH disposer
* (`onAppend = undefined` + store removal). Does NOT emit `session/created` —
* Enter a {@link prepare}d session into the store: wire the module-private
* append observer to `session/event` and add it to the store. Returns the
* DETACH disposer (observer + store removal). Does NOT emit `session/created` —
* the caller yields this disposer inside its effect and THEN calls
* {@link announce}, so a throwing `session/created` listener rolls the attach
* back instead of leaking it.
@@ -707,11 +843,23 @@ export class SessionStore extends Service {
* assume that.
*
* @param session - a {@link prepare}d session not yet in the store.
* @returns the detach disposer (`onAppend = undefined` + store removal).
* @param reservation - the exact unpublished-id capability when a factory
* reserved this session across setup.
* @returns the detach disposer (observer + store removal).
* @throws if a session with this id is already in the store.
*/
enter(session: Session): () => void {
if (this.store.has(session.id)) throw new Error(`session "${session.id}" already exists`)
enter(session: Session, reservation?: SessionRegistrationReservation): () => void {
const id = session.id
if (typeof id !== 'string') throw new TypeError('session id must be a string')
const held = this.reservations.get(id)
if (reservation === undefined) {
if (held !== undefined) throw new Error(`session "${id}" is reserved for unpublished creation`)
} else if (reservation.id !== id || held !== reservation
|| this.reservedSessions.get(reservation) !== session) {
throw new Error(`session "${id}" registration reservation does not own this prepared session`)
}
if (this.store.has(id)) throw new Error(`session "${id}" already exists`)
if (appendObservers.has(session)) throw new Error(`session "${id}" is already attached to a store`)
// The carrier is decided HERE, once, from the ENTERING context's scope tag
// (`this.ctx` is the caller's context — the tracker mechanism): every
// session/created|event|flush dispatch for this session uses it, so the
@@ -720,24 +868,65 @@ export class SessionStore extends Service {
const carrier = scopeTarget(session, scopeOf(this.ctx))
this.carriers.set(session, carrier)
const emitCtx = this.ctx
session.onAppend = (event) => { emitCtx.emit(carrier, 'session/event', session, event) }
this.store.set(session.id, session)
appendObservers.set(session, (event) => { emitCtx.emit(carrier, 'session/event', session, event) })
this.acceptedIds.set(session, id)
this.store.set(id, session)
let entered = true
return () => {
if (!entered) return
entered = false
session.onAppend = undefined
const wasAnnounced = this.announced.delete(session)
appendObservers.delete(session)
this.acceptedIds.delete(session)
this.carriers.delete(session)
this.store.delete(session.id)
this.store.delete(id)
if (wasAnnounced) this.emitDisposed(session, carrier, id)
}
}
/** Emit `session/created` for an {@link enter}ed session (with the carrier
* {@link enter} captured). Separate from {@link enter} so the caller can
* yield the detach disposer first (rollback safety — see {@link enter}).
* @param session - the entered session to announce to listeners. */
/** Emit `session/created` exactly once for an {@link enter}ed session (with
* the carrier {@link enter} captured). Separate from {@link enter} so the
* caller can yield the detach disposer first (rollback safety — see
* {@link enter}).
* @param session - the entered session to announce to listeners.
* @throws if the session is not live or its announcement already began,
* including a reentrant call from a creation listener. */
announce(session: Session): void {
this.ctx.emit(this.liveCarrierFor(session), 'session/created', session)
const carrier = this.liveCarrierFor(session)
if (this.announced.has(session)) {
throw new Error(`session "${session.id}" was already announced`)
}
// Mark before emit: Cordis emit may deliver to earlier listeners and then
// throw. Rollback must still pair that partial creation with disposal, and
// a listener cannot recursively create a second lifecycle edge.
this.announced.add(session)
const args: unknown[] = [carrier, 'session/created', session]
for (const callback of this.ctx.events.dispatch('emit', args)) {
// Synchronous throws intentionally propagate and veto publication; the
// yielded detach then emits the paired disposal edge. An async function
// is nevertheless assignable to a void listener, so observe its returned
// promise: rejection is too late to roll back and must be logged instead
// of becoming unhandled.
const returned: unknown = callback(...args)
void Promise.resolve(returned).catch((error: unknown) => {
this.ctx.logger.warn(`session "${session.id}": session/created listener rejected: ${renderThrown(error)}`)
})
}
}
/** Emit the paired teardown notification with per-listener containment. */
private emitDisposed(session: Session, carrier: Scoped<Session>, id: SessionId): void {
const args: unknown[] = [carrier, 'session/disposed', session]
for (const callback of this.ctx.events.dispatch('emit', args)) {
try {
const returned: unknown = callback(...args)
void Promise.resolve(returned).catch((error: unknown) => {
this.ctx.logger.warn(`session "${id}": session/disposed listener rejected: ${renderThrown(error)}`)
})
} catch (error: unknown) {
this.ctx.logger.warn(`session "${id}": session/disposed listener threw: ${renderThrown(error)}`)
}
}
}
/**
@@ -756,8 +945,9 @@ export class SessionStore extends Service {
/** Return the exact live session's carrier; detached/prepared objects reject. */
private liveCarrierFor(session: Session): Scoped<Session> {
if (this.store.get(session.id) !== session) {
throw new Error(`session "${session.id}" is not live in this store`)
const id = this.acceptedIds.get(session)
if (id === undefined || this.store.get(id) !== session) {
throw new Error(`session "${id ?? session.id}" is not live in this store`)
}
const carrier = this.carriers.get(session)
// enter() installs store + carrier in one synchronous sequence; a live
@@ -765,7 +955,7 @@ export class SessionStore extends Service {
// to subject-less dispatch (that would silently cross scope boundaries).
/* v8 ignore next -- enter installs store and carrier in one synchronous sequence */
if (carrier === undefined) {
throw new Error(`session "${session.id}" has no dispatch carrier`)
throw new Error(`session "${id}" has no dispatch carrier`)
}
return carrier
}

View File

@@ -60,6 +60,23 @@ describe('session dispatch carriers', () => {
bare.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
expect(heard).toEqual(['global:turn/start'])
})
it('reuses the captured owner carrier for the paired disposal notification', async () => {
const ctx = await mount()
const owner = await mintScope(ctx, 'owner')
const other = await mintScope(ctx, 'other')
const heard: string[] = []
ctx.on('session/disposed', (session) => { heard.push(`global:${session.id}`) })
owner.ctx.on('session/disposed', (session) => { heard.push(`owner:${session.id}`) })
other.ctx.on('session/disposed', (session) => { heard.push(`other:${session.id}`) })
const session = owner.ctx.sessions.prepare()
const detach = owner.ctx.sessions.enter(session)
owner.ctx.sessions.announce(session)
detach()
expect(heard).toEqual([`global:${session.id}`, `owner:${session.id}`])
})
})
describe('sessions.flush()', () => {

View File

@@ -578,6 +578,17 @@ describe('Session', () => {
expect(session.header).not.toBe(input)
expect(Object.isFrozen(session.header)).toBe(true)
expect(Reflect.set(session.header, 'cwd', '/published-mutated')).toBe(false)
expect(Reflect.set(session, 'id', SessionId('redirected'))).toBe(false)
expect(Reflect.set(session, 'header', input)).toBe(false)
expect(Object.getOwnPropertyDescriptor(session, 'id')).toMatchObject({
configurable: false,
writable: false,
})
expect(Object.getOwnPropertyDescriptor(session, 'header')).toMatchObject({
configurable: false,
writable: false,
})
expect(session.id).toBe('header-owned')
expect(session.header.cwd).toBe('/accepted')
})
@@ -691,6 +702,10 @@ describe('SessionStore', () => {
const session = ctx.sessions.create()
expect(created).toEqual([session])
// The store-owned append observer is module-private. A JavaScript caller
// may create an unrelated property with the old implementation's name,
// but cannot suppress the durable event feed.
expect(Reflect.set(session, 'onAppend', undefined)).toBe(true)
session.append('user/message', { content: [{ type: 'text', text: 'x' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
expect(events).toHaveLength(1)
expect(events[0]![0]).toBe(session)
@@ -746,6 +761,114 @@ describe('SessionStore', () => {
expect(ctx.sessions.get(SessionId('lifecycle'))).toBeUndefined()
})
it('captures the accepted id once and prevents simultaneous attachment to two stores', async () => {
const firstCtx = new Context()
const secondCtx = new Context()
await firstCtx.plugin(SessionStore)
await secondCtx.plugin(SessionStore)
const session = new Session(SessionId('owned-key'))
const detachFirst = firstCtx.sessions.enter(session)
expect(Reflect.set(session, 'id', SessionId('redirected'))).toBe(false)
expect(() => secondCtx.sessions.enter(session)).toThrow(/already attached to a store/)
expect(firstCtx.sessions.get(SessionId('owned-key'))).toBe(session)
detachFirst()
expect(firstCtx.sessions.get(SessionId('owned-key'))).toBeUndefined()
const detachSecond = secondCtx.sessions.enter(session)
expect(secondCtx.sessions.get(SessionId('owned-key'))).toBe(session)
detachSecond()
expect(() => firstCtx.sessions.enter({ id: 42 } as unknown as Session)).toThrow(/id must be a string/)
})
it('uses an opaque one-session reservation to gate unpublished factory insertion', async () => {
const ctx = new Context()
await ctx.plugin(SessionStore)
const held = ctx.sessions.reserve(SessionId('held-session'))
expect(() => ctx.sessions.reserve(SessionId('held-session'))).toThrow(/already exists or is reserved/)
expect(() => ctx.sessions.prepare(SessionId('held-session'))).toThrow(/reserved for unpublished creation/)
expect(() => ctx.sessions.create(SessionId('held-session'))).toThrow(/reserved for unpublished creation/)
const session = held.prepare({ meta: { cwd: '/held' } })
expect(() => held.prepare()).toThrow(/already prepared/)
expect(() => ctx.sessions.enter(session)).toThrow(/reserved for unpublished creation/)
const other = ctx.sessions.reserve(SessionId('other-session'))
expect(() => ctx.sessions.enter(session, other)).toThrow(/does not own this prepared session/)
expect(() => ctx.sessions.enter(new Session(SessionId('held-session')), held))
.toThrow(/does not own this prepared session/)
const detach = ctx.sessions.enter(session, held)
ctx.sessions.announce(session)
held.release()
held.release()
expect(ctx.sessions.get(SessionId('held-session'))).toBe(session)
expect(() => ctx.sessions.reserve(SessionId('held-session'))).toThrow(/already exists or is reserved/)
detach()
other.release()
const expired = ctx.sessions.reserve(SessionId('expired-session'))
expired.release()
expect(() => expired.prepare()).toThrow(/no longer active/)
expect(() => ctx.sessions.enter(new Session(SessionId('expired-session')), expired))
.toThrow(/does not own this prepared session/)
expect(() => ctx.sessions.reserve(42 as unknown as SessionId)).toThrow(/id must be a string/)
expect(() => ctx.sessions.prepare(42 as unknown as SessionId)).toThrow(/id must be a string/)
// Auto-generated ids skip unpublished reservations just as they skip live
// store entries; no hidden collision can be published later.
const firstAuto = ctx.sessions.reserve(SessionId('session-1'))
expect(ctx.sessions.prepare().id).toBe('session-2')
firstAuto.release()
})
it('owns reservations by the calling fiber and rolls back failed ownership registration', async () => {
const ctx = new Context()
await ctx.plugin(SessionStore)
let held!: import('@deepseek-ai/dsh-session').SessionRegistrationReservation
let scopedSessions!: SessionStore
const owner = await ctx.plugin(Object.assign((inner: Context) => {
scopedSessions = inner.sessions
held = inner.sessions.reserve(SessionId('fiber-held'))
}, { inject: ['sessions'] }))
expect(() => ctx.sessions.reserve(SessionId('fiber-held'))).toThrow(/already exists or is reserved/)
await owner.dispose()
const reused = ctx.sessions.reserve(SessionId('fiber-held'))
reused.release()
held.release() // idempotent after the automatic owner-disposal release
expect(() => scopedSessions.reserve(SessionId('inactive-owner'))).toThrow(/inactive context/)
const recovered = ctx.sessions.reserve(SessionId('inactive-owner'))
recovered.release()
})
it('rejects direct and reentrant repeat announcements to preserve one lifecycle pair', async () => {
const ctx = new Context()
await ctx.plugin(SessionStore)
let created = 0
let disposed = 0
let reentrantError = ''
ctx.on('session/created', (session) => {
created += 1
try {
ctx.sessions.announce(session)
} catch (error: unknown) {
reentrantError = String(error)
}
})
ctx.on('session/disposed', () => { disposed += 1 })
const session = ctx.sessions.prepare(SessionId('once'))
const detach = ctx.sessions.enter(session)
ctx.sessions.announce(session)
expect(reentrantError).toMatch(/already announced/)
expect(() => { ctx.sessions.announce(session) }).toThrow(/already announced/)
detach()
expect({ created, disposed }).toEqual({ created: 1, disposed: 1 })
})
it('synthesizes a minimal current-version header for a bare-created session', async () => {
const ctx = new Context()
await ctx.plugin(SessionStore)
@@ -864,11 +987,13 @@ describe('SessionStore', () => {
expect(observed).toBe(0)
})
it('rolls back the session (and onAppend) when a session/created listener throws (P1-1)', async () => {
it('pairs a partial session/created announcement with disposal during rollback', async () => {
const ctx = new Context()
await ctx.plugin(SessionStore)
let threw = false
const disposed: Session[] = []
ctx.on('session/disposed', (session) => { disposed.push(session) })
ctx.on('session/created', () => {
if (!threw) { threw = true; throw new Error('boom created listener') }
})
@@ -876,9 +1001,10 @@ describe('SessionStore', () => {
// The throwing emit must roll the store entry back, not leak it.
expect(() => ctx.sessions.create(SessionId('fixed'))).toThrow('boom created listener')
expect(ctx.sessions.get(SessionId('fixed'))).toBeUndefined() // rolled back, not leaked
expect(disposed.map(session => session.id)).toEqual(['fixed'])
// A subsequent create of the SAME id succeeds (the already-exists check is
// not wedged) and its onAppend is correctly wired (events observable).
// not wedged) and its store-owned observer is correctly wired (events observable).
const events: SessionEvent[] = []
ctx.on('session/event', (_session, event) => void events.push(event))
const session = ctx.sessions.create(SessionId('fixed'))
@@ -886,6 +1012,59 @@ describe('SessionStore', () => {
session.append('user/message', { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
expect(events).toHaveLength(1)
})
it('observes async session/created rejection without rolling back or starving peers', async () => {
const ctx = new Context()
await ctx.plugin(SessionStore)
const warnings: string[] = []
ctx.logger.warn = ((message: unknown) => { warnings.push(String(message)) }) as typeof ctx.logger.warn
const heard: string[] = []
ctx.on('session/created', () => Promise.reject(new Error('late creation failure')) as never)
ctx.on('session/created', (session) => { heard.push(session.id) })
const session = ctx.sessions.create(SessionId('async-created'))
await Promise.resolve()
await Promise.resolve()
expect(ctx.sessions.get(session.id)).toBe(session)
expect(heard).toEqual(['async-created'])
expect(warnings).toEqual([
'session "async-created": session/created listener rejected: Error: late creation failure',
])
})
it('contains synchronous and async session/disposed listener failures per observer', async () => {
const ctx = new Context()
await ctx.plugin(SessionStore)
const warnings: string[] = []
ctx.logger.warn = ((message: unknown) => { warnings.push(String(message)) }) as typeof ctx.logger.warn
const hostile = { [Symbol.toPrimitive]() { throw new Error('cannot stringify') } }
const printable = { toString: () => 'printable failure' }
const heard: string[] = []
ctx.on('session/disposed', () => { throw hostile })
ctx.on('session/disposed', () => Promise.reject(new Error('async disposed')) as never)
ctx.on('session/disposed', () => { throw printable })
ctx.on('session/disposed', (session) => { heard.push(session.id) })
const unannounced = ctx.sessions.prepare(SessionId('never-announced'))
const detachUnannounced = ctx.sessions.enter(unannounced)
detachUnannounced()
expect(heard).toEqual([])
const announced = ctx.sessions.prepare(SessionId('contained-disposal'))
const detach = ctx.sessions.enter(announced)
ctx.sessions.announce(announced)
expect(() => { detach() }).not.toThrow()
await Promise.resolve()
await Promise.resolve()
expect(heard).toEqual(['contained-disposal'])
expect(warnings).toEqual([
'session "contained-disposal": session/disposed listener threw: <unrenderable thrown value>',
'session "contained-disposal": session/disposed listener threw: printable failure',
'session "contained-disposal": session/disposed listener rejected: Error: async disposed',
])
})
})
describe('todo/write event', () => {

View File

@@ -13,10 +13,10 @@ System prompt assembly registry. Plugins contribute ordered text sections, tool-
### Public API
- `ctx.systemPrompt.section(section: PromptSection): () => Promise<void> | void` Contribute a section. The registry snapshots `name`, `order`, and the text value/callback, so later caller-object mutation cannot rename a stored section. The layer is the CALLING context's scope: `agent.ctx` contributes to that agent alone, SHADOWING a same-named global section there (the per-agent persona mechanism — a scoped `deployment:persona`). Duplicate names within one layer throw, and a globally protected section name cannot be shadowed. Disposed with the calling fiber.
- `ctx.systemPrompt.tools(provider: (context: AssembleContext) => ToolProviderResult): () => Promise<void> | void` Contribute tool schemas, evaluated at each assembly with that assembly's context. `ToolProviderResult` = `{ schemas, knownNames? }`: `schemas` is the post-restriction visible set for `context.scope`; `knownNames` (defaulting to the same captured schemas' names) is the pre-restriction universe `toolOrder` validates against. Assembly reads the result, each schema field, and the optional known-name list once before detaching them, rejects non-string schema names/descriptions or known names, and uses those same accepted strings for validation and the model-visible collection. A provider must not return a schema named `TOOL_ORDER_REST`. Scoped providers are consulted only for their scope's assemblies. Disposed with the calling fiber.
- `ctx.systemPrompt.variable(name: string, provider: (context) => string | undefined): () => Promise<void> | void` Contribute a prompt variable, referenced from section text as `{{name}}`. Scoped variables (via `agent.ctx`) shadow a same-named global for that agent. Duplicate-in-layer or unreferenceable names throw; `undefined` means "no value for this assembly". Disposed with the calling fiber.
- `ctx.systemPrompt.protect(protection: PromptProtection): () => Promise<void> | void` Make named section/tool contributions authoritative after the assembly waterfall. Protection restores canonical registry/provider presence and definition; restored entries keep canonical order with one another and anchor before their first surviving later unprotected canonical neighbor (or at the end), without undoing listener reordering of unprotected entries. Canonical absence is authoritative too, so a mode-hidden tool cannot be fabricated by a listener. Calling through `agent.ctx` protects only that agent's assemblies. A global section protection additionally reserves its name against scoped shadows; registering either side of that conflict fails loudly instead of treating the shadow as canonical. Each input array is read once and snapshotted, empty protections throw, and disposal removes the protection.
- `ctx.systemPrompt.section(section: PromptSection): () => Promise<void> | void` Contribute a section. The registry reads `name`, `order`, and the text value/callback once, validates their fixed string/finite-number/string-or-function types, and stores only that accepted record; later caller-object mutation cannot rename or reshape it. The layer is the CALLING context's scope: `agent.ctx` contributes to that agent alone, SHADOWING a same-named global section there (the per-agent persona mechanism — a scoped `deployment:persona`). Duplicate names within one layer throw, and a globally protected section name cannot be shadowed. Disposed with the calling fiber.
- `ctx.systemPrompt.tools(provider: (context: AssembleContext) => ToolProviderResult): () => Promise<void> | void` Contribute tool schemas, evaluated at each assembly with that assembly's context; a non-function provider rejects before effect storage. `ToolProviderResult` = `{ schemas, knownNames? }`: `schemas` is the post-restriction visible set for `context.scope`; `knownNames` (defaulting to the same captured schemas' names) is the pre-restriction universe `toolOrder` validates against. Assembly reads the result, each schema field, and the optional known-name list once before detaching them, rejects non-string schema names/descriptions or known names, and uses those same accepted strings for validation and the model-visible collection. A provider must not return a schema named `TOOL_ORDER_REST`. Scoped providers are consulted only for their scope's assemblies. Disposed with the calling fiber.
- `ctx.systemPrompt.variable(name: string, provider: (context) => string | undefined): () => Promise<void> | void` Contribute a prompt variable, referenced from section text as `{{name}}`. The fixed string name and function provider types reject before effect storage. Scoped variables (via `agent.ctx`) shadow a same-named global for that agent. Duplicate-in-layer or unreferenceable names throw; `undefined` means "no value for this assembly". Disposed with the calling fiber.
- `ctx.systemPrompt.protect(protection: PromptProtection): () => Promise<void> | void` Make named section/tool contributions authoritative after the assembly waterfall. Protection restores canonical registry/provider presence and definition; restored entries keep canonical order with one another and anchor before their first surviving later unprotected canonical neighbor (or at the end), without undoing listener reordering of unprotected entries. Canonical absence is authoritative too, so a mode-hidden tool cannot be fabricated by a listener. Calling through `agent.ctx` protects only that agent's assemblies. A global section protection additionally reserves its name against scoped shadows; registering either side of that conflict fails loudly instead of treating the shadow as canonical. Each optional field and array slot is read once, non-array fields or non-string names reject before effect storage, and the accepted arrays are deduplicated and frozen. Finalization materializes each waterfall-produced entry name once, so a stateful getter cannot evade canonical replacement. Empty protections throw, and disposal removes the protection.
- `ctx.systemPrompt.assemble(context?: AssembleContext): Promise<PromptAssembly>` Assemble the prompt for one caller: the global layer merged with `context.scope`'s layer (scoped shadows global). Provider output becomes one coherent detached snapshot before `toolOrder` validation. Runs through the scope-filtered `system-prompt/assemble` waterfall, then restores protected contributions from the pre-waterfall canonical assembly. Rejects when a configured `toolOrder` names a tool outside the providers' `knownNames` universe (a restricted-away KNOWN tool is a normal absence), or when a provider returns the reserved rest-entry name.
### Live events

View File

@@ -234,11 +234,41 @@ function orderTools(tools: ToolSchema[], toolOrder: string[] | undefined, knownN
name === TOOL_ORDER_REST ? rest : tools.filter(tool => tool.name === name))
}
/** Snapshot one waterfall-produced named entry with a stable, own data `name`. */
function snapshotNamedEntry<T extends { name: string }>(entry: T): { entry: T; name: string } {
// Read the name exactly once before protection matching. The waterfall owns
// its output and may return accessor-backed records; retaining such an entry
// would let a getter answer "unprotected" during filtering and the protected
// name later when a consumer reads the final assembly.
const name = entry.name
const snapshot: Record<string, unknown> = {}
Object.defineProperty(snapshot, 'name', {
value: name,
enumerable: true,
configurable: true,
writable: true,
})
// Copy every other enumerable field once while deliberately skipping name.
// defineProperty keeps a literal "__proto__" extension field ordinary data.
for (const key of Object.keys(entry)) {
if (key === 'name') continue
Object.defineProperty(snapshot, key, {
value: (entry as unknown as Record<string, unknown>)[key],
enumerable: true,
configurable: true,
writable: true,
})
}
return { entry: snapshot as T, name }
}
/** Restore protected named entries from `canonical`, anchored before their next unprotected canonical neighbor. */
function restoreProtected<T extends { name: string }>(
canonical: readonly T[], result: readonly T[], protectedNames: ReadonlySet<string>,
): T[] {
const restored = result.filter(entry => !protectedNames.has(entry.name))
const restored = result
.map(snapshotNamedEntry)
.filter(record => !protectedNames.has(record.name))
for (const [index, entry] of canonical.entries()) {
if (!protectedNames.has(entry.name)) continue
// Protected entries are inserted in canonical order. Anchor each one
@@ -251,9 +281,29 @@ function restoreProtected<T extends { name: string }>(
.map(candidate => candidate.name),
)
const next = restored.findIndex(candidate => following.has(candidate.name))
restored.splice(next < 0 ? restored.length : next, 0, structuredClone(entry))
restored.splice(next < 0 ? restored.length : next, 0, {
entry: structuredClone(entry),
name: entry.name,
})
}
return restored
return restored.map(record => record.entry)
}
/** Validate and detach one protection-name array without rereading an element. */
function snapshotProtectionNames(value: unknown, field: 'sections' | 'tools'): readonly string[] {
if (!Array.isArray(value)) {
throw new TypeError(`systemPrompt.protect() ${field} must be an array of strings`)
}
const names: string[] = []
const length = value.length
for (let index = 0; index < length; index += 1) {
const name: unknown = value[index]
if (typeof name !== 'string') {
throw new TypeError(`systemPrompt.protect() ${field} must be an array of strings`)
}
names.push(name)
}
return Object.freeze([...new Set(names)])
}
/** Lexicographic (code-unit) name comparison — locale-independent, so the order is identical on every machine. */
@@ -433,9 +483,10 @@ export class SystemPrompt extends Service {
* `deployment:persona`) unless that global name is protected: global
* protection reserves its section name against scoped shadows so the
* registration owner—not a later scope—defines the canonical value. The
* registry snapshots `name`, `order`, and `text` before checking/storing, so
* later caller-object mutation cannot rename a contribution. Throws
* if the SAME layer already has the name (a
* registry reads `name`, `order`, and `text` once, validates their fixed
* string/finite-number/string-or-function types, and stores only that
* accepted record, so later caller-object mutation cannot rename or reshape
* a contribution. Throws if the SAME layer already has the name (a
* duplicate would silently double prompt text — e.g. a double-loaded tool
* plugin; the global-duplicate message names `agent.ctx` as the per-agent
* alternative). Removed when the calling fiber is disposed. Emits
@@ -446,12 +497,23 @@ export class SystemPrompt extends Service {
* yield it directly — exact identity nests the teardown in order.
*/
section(section: PromptSection): () => Promise<void> | void {
const scope = scopeOf(this.ctx)
const snapshot: PromptSection = {
name: section.name,
order: section.order,
text: section.text,
const input: unknown = section
if (typeof input !== 'object' || input === null) {
throw new TypeError('systemPrompt.section() requires a section object')
}
const accepted = input as PromptSection
const name = accepted.name
const order = accepted.order
const text = accepted.text
if (typeof name !== 'string') throw new TypeError('prompt section name must be a string')
if (typeof order !== 'number' || !Number.isFinite(order)) {
throw new TypeError(`prompt section "${name}" order must be a finite number`)
}
if (typeof text !== 'string' && typeof text !== 'function') {
throw new TypeError(`prompt section "${name}" text must be a string or function`)
}
const scope = scopeOf(this.ctx)
const snapshot: PromptSection = { name, order, text }
if (scope !== undefined && this.protections.some(record => record.sections?.includes(snapshot.name))) {
throw new Error(`prompt section "${snapshot.name}" is globally protected and cannot be shadowed in an agent scope`)
}
@@ -498,7 +560,8 @@ export class SystemPrompt extends Service {
* `schemas`/`knownNames` split). The layer is decided by the calling
* context: a scoped provider (registered through `agent.ctx`) is consulted
* only for that scope's assemblies. Removed when the calling fiber is
* disposed. A provider must not return a schema named
* disposed. A non-function provider is rejected before any effect is stored.
* A provider must not return a schema named
* {@link TOOL_ORDER_REST}; that name is reserved for
* {@link Config.toolOrder}'s rest entry and rejects the assembly. Emits
* `system-prompt/change`.
@@ -508,6 +571,9 @@ export class SystemPrompt extends Service {
* yield it directly — exact identity nests the teardown in order.
*/
tools(provider: (context: AssembleContext) => ToolProviderResult): () => Promise<void> | void {
if (typeof provider !== 'function') {
throw new TypeError('system prompt tool provider must be a function')
}
const scope = scopeOf(this.ctx)
const dispose = this.ctx.effect(function* (this: SystemPrompt) {
const layer = scope === undefined
@@ -545,10 +611,11 @@ export class SystemPrompt extends Service {
* deployment must not claim facts it does not have). The layer is decided
* by the calling context: a scoped variable (registered through
* `agent.ctx`) resolves only for that scope's assemblies and SHADOWS a
* same-named global variable there. Throws on a name that does not match
* `[a-z][a-z0-9_]*` (it could never be referenced) or one already
* registered in the SAME layer. Removed when the calling fiber is disposed;
* emits `system-prompt/change` on register/unregister.
* same-named global variable there. The fixed name and callback types are
* validated before effect storage. Throws on a name that does not match
* `[a-z][a-z0-9_]*` (it could never be referenced) or one already registered
* in the SAME layer. Removed when the calling fiber is disposed; emits
* `system-prompt/change` on register/unregister.
* @param name - the reference name (matches `[a-z][a-z0-9_]*`).
* @param provider - evaluated at every {@link assemble} for the value.
* @returns the disposer that removes the variable. The exact
@@ -556,11 +623,16 @@ export class SystemPrompt extends Service {
* yield it directly — exact identity nests the teardown in order.
*/
variable(name: string, provider: (context: AssembleContext) => string | undefined): () => Promise<void> | void {
const inputName: unknown = name
if (typeof inputName !== 'string') throw new TypeError('prompt variable name must be a string')
if (!VARIABLE_NAME.test(inputName)) {
throw new Error(`invalid prompt variable name "${inputName}" (must match ${String(VARIABLE_NAME)})`)
}
if (typeof provider !== 'function') {
throw new TypeError(`prompt variable "${inputName}" provider must be a function`)
}
const scope = scopeOf(this.ctx)
const dispose = this.ctx.effect(function* (this: SystemPrompt) {
if (!VARIABLE_NAME.test(name)) {
throw new Error(`invalid prompt variable name "${name}" (must match ${String(VARIABLE_NAME)})`)
}
const layer = scope === undefined
? this.variableProviders
: this.scopedVariableProviders.get(scope) ?? (() => {
@@ -599,9 +671,13 @@ export class SystemPrompt extends Service {
* restored AFTER the whole waterfall, so listener registration order cannot
* strip, replace, duplicate, or fabricate it. Canonical absence is restored
* too: if the protected name is intentionally absent for an assembly, a
* listener-injected entry with that name is removed. Each input array is
* read once and snapshotted; an empty protection throws because it cannot
* affect output.
* listener-injected entry with that name is removed. Each optional field and
* array slot is read once; non-array fields or non-string names reject before
* effect storage, and the accepted deduplicated arrays are frozen. During
* finalization each waterfall-produced entry name is likewise read once into
* an owned data record, so a stateful getter cannot look unprotected during
* filtering and later impersonate a protected name. An empty protection
* throws because it cannot affect output.
* Removed with the calling fiber and emits `system-prompt/change` on
* registration/unregistration. A global section protection also reserves the
* name against scoped section shadows; registering protection when such a
@@ -610,13 +686,24 @@ export class SystemPrompt extends Service {
* @returns the exact Cordis effect disposer that removes the protection.
*/
protect(protection: PromptProtection): () => Promise<void> | void {
const scope = scopeOf(this.ctx)
const sections = protection.sections
const tools = protection.tools
const snapshot: PromptProtection = {
...sections !== undefined ? { sections: [...new Set(sections)] } : {},
...tools !== undefined ? { tools: [...new Set(tools)] } : {},
const input: unknown = protection
if (typeof input !== 'object' || input === null) {
throw new TypeError('systemPrompt.protect() requires a protection object')
}
const accepted = input as PromptProtection
const inputSections = accepted.sections
const inputTools = accepted.tools
const sections = inputSections === undefined
? undefined
: snapshotProtectionNames(inputSections, 'sections')
const tools = inputTools === undefined
? undefined
: snapshotProtectionNames(inputTools, 'tools')
const scope = scopeOf(this.ctx)
const snapshot: PromptProtection = Object.freeze({
...sections !== undefined ? { sections } : {},
...tools !== undefined ? { tools } : {},
})
if ((snapshot.sections?.length ?? 0) === 0 && (snapshot.tools?.length ?? 0) === 0) {
throw new Error('systemPrompt.protect() requires at least one section or tool name')
}

View File

@@ -111,6 +111,86 @@ describe('SystemPrompt', () => {
expect(contributed(assembly).map(s => s.text)).toEqual(['first'])
})
it('rejects malformed fixed registration fields before storing an effect', async () => {
const ctx = new Context()
await ctx.plugin(SystemPrompt)
const badName = { value: 'name' }
const badText = { value: 'text' }
expect(() => ctx.systemPrompt.section(null as unknown as Parameters<typeof ctx.systemPrompt.section>[0]))
.toThrow('requires a section object')
expect(() => ctx.systemPrompt.section(1 as unknown as Parameters<typeof ctx.systemPrompt.section>[0]))
.toThrow('requires a section object')
expect(() => ctx.systemPrompt.section({ name: badName as unknown as string, order: 1, text: 'x' }))
.toThrow('prompt section name must be a string')
expect(() => ctx.systemPrompt.section({ name: 'bad-order', order: '1' as unknown as number, text: 'x' }))
.toThrow('order must be a finite number')
expect(() => ctx.systemPrompt.section({ name: 'bad-order', order: Number.NaN, text: 'x' }))
.toThrow('order must be a finite number')
expect(() => ctx.systemPrompt.section({ name: 'bad-text', order: 1, text: badText as unknown as string }))
.toThrow('text must be a string or function')
expect(() => ctx.systemPrompt.tools(1 as unknown as Parameters<typeof ctx.systemPrompt.tools>[0]))
.toThrow('tool provider must be a function')
expect(() => ctx.systemPrompt.variable({} as unknown as string, () => 'x'))
.toThrow('prompt variable name must be a string')
expect(() => ctx.systemPrompt.variable('valid', 1 as unknown as Parameters<typeof ctx.systemPrompt.variable>[1]))
.toThrow('provider must be a function')
expect(() => ctx.systemPrompt.protect(null as unknown as Parameters<typeof ctx.systemPrompt.protect>[0]))
.toThrow('requires a protection object')
expect(() => ctx.systemPrompt.protect(1 as unknown as Parameters<typeof ctx.systemPrompt.protect>[0]))
.toThrow('requires a protection object')
expect(() => ctx.systemPrompt.protect({ sections: 'x' as unknown as string[] }))
.toThrow('sections must be an array of strings')
expect(() => ctx.systemPrompt.protect({ tools: 'x' as unknown as string[] }))
.toThrow('tools must be an array of strings')
expect(() => ctx.systemPrompt.protect({ sections: ['ok', {} as unknown as string] }))
.toThrow('sections must be an array of strings')
expect(() => ctx.systemPrompt.protect({ tools: [{} as unknown as string] }))
.toThrow('tools must be an array of strings')
expect(Object.isFrozen(badName)).toBe(false)
expect(Object.isFrozen(badText)).toBe(false)
expect(contributed(await ctx.systemPrompt.assemble())).toEqual([])
})
it('reads each section field and protection-name slot once at registration', async () => {
const ctx = new Context()
await ctx.plugin(SystemPrompt)
const reads = { name: 0, order: 0, text: 0, sections: 0, item: 0 }
const section = Object.defineProperties({}, {
name: {
enumerable: true,
get: () => (++reads.name === 1 ? 'stable' : 42),
},
order: {
enumerable: true,
get: () => (++reads.order === 1 ? 10 : Number.NaN),
},
text: {
enumerable: true,
get: () => (++reads.text === 1 ? 'stable text' : null),
},
}) as unknown as Parameters<typeof ctx.systemPrompt.section>[0]
const names = new Array<string>(1)
Object.defineProperty(names, 0, {
enumerable: true,
get: () => (++reads.item === 1 ? 'stable' : 'drifted'),
})
const protection = {
get sections(): string[] {
reads.sections += 1
return reads.sections === 1 ? names : ['drifted']
},
}
ctx.systemPrompt.section(section)
ctx.systemPrompt.protect(protection)
const assembly = await ctx.systemPrompt.assemble()
expect(reads).toEqual({ name: 1, order: 1, text: 1, sections: 1, item: 1 })
expect(assembly.sections).toContainEqual({ name: 'stable', order: 10, text: 'stable text' })
})
it('rolls back a section when a system-prompt/change listener throws (P1-1)', async () => {
const ctx = new Context()
await ctx.plugin(SystemPrompt)
@@ -282,6 +362,56 @@ describe('SystemPrompt', () => {
expect(assembly.sections).toContainEqual({ name: 'protected', order: 10, text: 'canonical' })
})
it('materializes waterfall entry names once before restoring protected definitions', async () => {
const ctx = new Context()
await ctx.plugin(SystemPrompt)
ctx.systemPrompt.section({ name: 'protected', order: 10, text: 'canonical section' })
ctx.systemPrompt.tools(() => ({ schemas: [{ name: 'protected', description: 'canonical tool', parameters: {} }] }))
ctx.systemPrompt.protect({ sections: ['protected'], tools: ['protected'] })
let sectionNameReads = 0
let toolNameReads = 0
const hostileSection = {
get name(): string {
sectionNameReads += 1
return sectionNameReads === 1 ? 'impostor-section' : 'protected'
},
order: 999,
text: 'listener section',
}
const hostileTool = {
get name(): string {
toolNameReads += 1
return toolNameReads === 1 ? 'impostor-tool' : 'protected'
},
description: 'listener tool',
parameters: {},
}
ctx.on('system-prompt/assemble', async (_assembly, _context, next) => {
const result = await next()
result.sections = [
...result.sections.filter(section => section.name !== 'protected'),
hostileSection,
]
result.tools = [
...result.tools.filter(tool => tool.name !== 'protected'),
hostileTool,
]
return result
})
const assembly = await ctx.systemPrompt.assemble()
expect(sectionNameReads).toBe(1)
expect(toolNameReads).toBe(1)
expect(assembly.sections.map(section => section.name)).toEqual([
'harness:identity',
'deployment:persona',
'impostor-section',
'protected',
])
expect(assembly.tools.map(tool => tool.name)).toEqual(['impostor-tool', 'protected'])
})
it('protects canonical absence and rejects an empty protection', async () => {
const ctx = new Context()
await ctx.plugin(SystemPrompt)

View File

@@ -22,7 +22,7 @@ tools:
- `ctx.tools.knownNames(scope?: ScopeKey): string[]` The PRE-restriction end-capability name universe `restrict` validates against: a typo fails loud while a restricted-away tool stays a normal absence. Presentation providers add reserved transport names separately when validating `toolOrder`.
- `ctx.tools.schemas(scope?: ScopeKey): ToolSchema[]` Schemas of everything the scope can see (without the `execute` functions). The shipped tools' schemas are catalogued in [docs/tool-catalog.md](../../../docs/tool-catalog.md), generated by booting each tool plugin and harvesting this method (see [the tool-schema-catalog RFC](../../../docs/rfc/implemented/process/2026-07-02-tool-schema-catalog.md)).
- `ctx.tools.guard(guard: ToolGuard): () => Promise<void> | void` Register a monotonic synchronous execution guard after `tools/pre-execute`: returning a reason denies the call, while `undefined` leaves it unchanged. A plain-context guard applies globally; an `agent.ctx` guard applies only to that agent. Later waterfall listeners cannot turn a guard denial back into permission. Disposed with the calling fiber.
- `ctx.tools.execute(exec: ToolExecutionInput): Promise<ToolExecutionResult>` Read each caller-owned top-level field once, snapshot the single-use call into a pipeline-owned execution, assign its opaque correlation token, materialize `arguments` through one lossless-JSON traversal, deep-freeze them, and protect identity before running `tools/pre-execute` → guards → `tools/execute``tools/post-execute`; optional `signal` is the only operational field an around-dispatch wrapper may add, replace, or remove. After the required `callId`/`name` correlation identity is captured, the same captured optional fields build the normalized error shell if a later accessor or validation fails, so policy, dispatch, routing, and `tools/result` cannot observe different caller values. Every top-level result field is likewise captured once and the complete result or post-decision is losslessly materialized before final observation. Invalid input—including cloneable mutable exotics—and malformed or non-JSON listener/tool results normalize to `isError` outcomes rather than bypassing policy or failing later at the session log. A throwing `callId` or `name` accessor rejects because no trustworthy result identity exists yet.
- `ctx.tools.execute(exec: ToolExecutionInput): Promise<ToolExecutionResult>` Read each caller-owned top-level field once, require `callId` and `name` to yield strings, snapshot the single-use call into a pipeline-owned execution, assign its opaque correlation token, materialize `arguments` through one lossless-JSON traversal, deep-freeze them, and protect identity before running `tools/pre-execute` → guards → `tools/execute``tools/post-execute`; optional `signal` is the only operational field an around-dispatch wrapper may add, replace, or remove. After the required string correlation identity is captured, the same captured optional fields build the normalized error shell if a later accessor or validation fails, so policy, dispatch, routing, and `tools/result` cannot observe different caller values. Every top-level result field is likewise captured once and the complete result or post-decision is losslessly materialized before final observation. Invalid later input—including cloneable mutable exotics—and malformed or non-JSON listener/tool results normalize to `isError` outcomes rather than bypassing policy or failing later at the session log. A throwing accessor or non-string value in `callId` or `name` rejects before `tools/result` because no trustworthy result identity exists yet.
### Injected services
@@ -35,7 +35,7 @@ The live registry pipeline has three transformable waterfalls followed by the ow
### Key types
- `ToolDefinition``ToolSchema` + `execute(args, exec): Promise<ContentBlock[] | { content: ContentBlock[]; meta? }>` (the bare array is the model-facing content; the object form additionally attaches an opaque, JSON-serializable `meta` presentation payload persisted on the `tool/result` event and handed back to `presentResult`), plus optional `presentCall(args)` / `presentResult(args, result)` for tool-owned UI presentation (see below). It also carries an optional cooperative timeout budget `timeoutMs?: number` (ms) enforced by `@deepseek-ai/dsh-timeout-policy`, never sent to the model. Registration stores a frozen snapshot with detached JSON parameters and once-bound callback identities.
- `ToolExecutionInput` — the caller-supplied call description: `{ callId, name, arguments, agent?, parent?, signal? }`; `arguments` must be losslessly JSON-serializable, and callers may pass an enclosing execution's opaque token as `parent` but never choose the new execution's own token.
- `ToolExecutionInput` — the caller-supplied call description: `{ callId, name, arguments, agent?, parent?, signal? }`; `callId` and `name` must be strings, `arguments` must be losslessly JSON-serializable, and callers may pass an enclosing execution's opaque token as `parent` but never choose the new execution's own token.
- `ToolExecutionToken` — a frozen, property-free identity value assigned by the registry. It supports equality correlation only and exposes no live outer execution state.
- `ToolExecution` — the pipeline-owned call: immutable `{ token, callId, name, arguments, agent?, parent? }` identity plus optional operational `signal`, which an around wrapper may add, replace, remove, and restore. A nested call's `parent` is a `ToolExecutionToken`, not an execution object.
- `ToolExecutionResult` — losslessly JSON-serializable outcome: `{ callId, content, isError, error?, additionalContext?, meta? }`. The registry validates the complete post-policy value before final observation. On failure with a `HarnessError`, `error: { name, code }` carries the structured failure class alongside the model-facing text (the loop forwards it onto the `tool/result` session event for retry/sandbox plugins and replay). `additionalContext` (a `HookContext`) ferries any `tools/post-execute` context up to the loop, which buffers it and appends it as a `context/message` after all `tool/result`s in the step. `meta` is the tool's opaque presentation payload from a successful `execute` (the object return form); the loop forwards it onto the `tool/result` session event for result-card rendering.

View File

@@ -951,22 +951,33 @@ export class ToolRegistry extends Service {
* Caller-owned arguments are validated and detached in one recursive
* lossless-JSON traversal; a violation normalizes to an error before policy
* or dispatch.
* @param exec - the single-use call input; every top-level field is read once
* and that identity snapshot is protected before policy runs (and reused by
* the normalized error shell if validation fails).
* @returns the final result after every waterfall. Once the required
* `callId` and `name` correlation identity has been captured, later
* accessor, validation, listener, and tool failures resolve as `isError`
* results rather than rejections. A throwing `callId` or `name` accessor
* rejects because no trustworthy result identity exists yet.
* @param exec - the single-use call input; every top-level field is read once.
* `callId` and `name` must each yield a string before that identity snapshot
* is protected and policy begins.
* @returns the final result after every waterfall. Once the required string
* `callId` and `name` correlation identity has been captured, later accessor,
* validation, listener, and tool failures resolve as `isError` results rather
* than rejections. A throwing accessor or non-string value in either identity
* field rejects because no trustworthy result correlation exists yet.
*/
async execute(exec: ToolExecutionInput): Promise<ToolExecutionResult> {
// callId/name are the minimum correlation identity needed to construct a
// result at all. Every other caller-controlled accessor is read once
// INSIDE the normalization boundary; if one throws, the error shell uses
// the fields captured before it and never rereads the hostile record.
// result at all. Capture each once, then validate the captured scalar before
// anything can treat it as a trustworthy identity. A JavaScript/casted
// caller that supplies another type rejects at this outer boundary: an error
// result carrying the same malformed value would not satisfy the correlation
// contract and might itself fail lossless-JSON materialization. Every other
// caller-controlled accessor is read once INSIDE the normalization boundary;
// if one throws, the error shell uses the fields captured before it and never
// rereads the hostile record.
const callId = exec.callId
const name = exec.name
if (typeof callId !== 'string') {
throw new TypeError('tool execution callId must be a string')
}
if (typeof name !== 'string') {
throw new TypeError('tool execution name must be a string')
}
let agent: Agent | undefined
let parent: ToolExecutionToken | undefined
let signal: AbortSignal | undefined

View File

@@ -7,7 +7,7 @@ import ApprovalService, { type ApprovalOutcome, type ApprovalRequest } from '@de
import ToolRegistry, {
defineTool, schemaSpecToJsonSchema, validateArgs, ToolArgsError, ToolNotFoundError,
type DefineToolOptions, type InferArgs, type SchemaSpec, type PreToolDecision, type PostToolDecision,
type ToolDefinition, type ToolExecution, type ToolExecutionResult, type ToolGuard,
type ToolDefinition, type ToolExecution, type ToolExecutionInput, type ToolExecutionResult, type ToolGuard,
} from '@deepseek-ai/dsh-tools'
async function setup() {
@@ -83,6 +83,95 @@ describe('ToolRegistry', () => {
expect(result).toEqual({ callId: CallId('c1'), content: [{ type: 'text', text: 'hi' }], isError: false })
})
it.each([
{ field: 'callId', value: 1n },
{ field: 'callId', value: 123 },
{ field: 'name', value: 1n },
{ field: 'name', value: 123 },
] as const)('rejects a non-string $field before final observation', async ({ field, value }) => {
const ctx = await setup()
let observed = 0
ctx.on('tools/result', () => { observed += 1 })
const input: Record<string, unknown> = {
callId: CallId('valid-call'),
name: 'missing',
arguments: {},
}
input[field] = value
await expect(ctx.tools.execute(input as unknown as ToolExecutionInput))
.rejects.toThrow(`tool execution ${field} must be a string`)
expect(observed).toBe(0)
})
it('reads correlation accessors once and normalizes a later hostile accessor', async () => {
const ctx = await setup()
const reads = { callId: 0, name: 0, arguments: 0 }
let observed: { callId: unknown; name: unknown; isError: boolean } | undefined
ctx.on('tools/result', (exec, result) => {
observed = { callId: exec.callId, name: exec.name, isError: result.isError }
})
const input = Object.defineProperties({}, {
callId: {
enumerable: true,
get: () => {
reads.callId += 1
if (reads.callId > 1) throw new Error('callId reread')
return CallId('one-read-call')
},
},
name: {
enumerable: true,
get: () => {
reads.name += 1
if (reads.name > 1) throw new Error('name reread')
return 'missing'
},
},
arguments: {
enumerable: true,
get: () => {
reads.arguments += 1
throw new Error('arguments accessor broke')
},
},
}) as unknown as ToolExecutionInput
const result = await ctx.tools.execute(input)
expect(reads).toEqual({ callId: 1, name: 1, arguments: 1 })
expect(result).toMatchObject({ callId: CallId('one-read-call'), isError: true })
expect(result.content[0]).toMatchObject({ text: 'Error: arguments accessor broke' })
expect(observed).toEqual({ callId: CallId('one-read-call'), name: 'missing', isError: true })
})
it('reads callId once before a hostile name accessor rejects correlation', async () => {
const ctx = await setup()
const reads = { callId: 0, name: 0 }
let observed = 0
ctx.on('tools/result', () => { observed += 1 })
const input = Object.defineProperties({ arguments: {} }, {
callId: {
enumerable: true,
get: () => {
reads.callId += 1
return CallId('hostile-name')
},
},
name: {
enumerable: true,
get: () => {
reads.name += 1
throw new Error('name accessor broke')
},
},
}) as unknown as ToolExecutionInput
await expect(ctx.tools.execute(input)).rejects.toThrow('name accessor broke')
expect(reads).toEqual({ callId: 1, name: 1 })
expect(observed).toBe(0)
})
it('threads a tool-attached meta (object return form) onto the result', async () => {
const ctx = await setup()
ctx.tools.register({