refactor(events): remove the turn boundary mirror events

Complete the boundary-mirror removal begun with the step mirrors: drop
`agent/turn-start` and `agent/turn-end` from the agent event taxonomy. Turn and
step boundaries are now read exclusively off the durable `session/event` feed
(`turn/start`/`turn/end`/`step/start`/`step/end`) — there is no `agent/*` mirror
for any boundary.

- loop.ts: delete both turn emits; `closeTurn` loses its `emit` parameter and
  its now-unreachable idempotency guard (it is called exactly once per turn, on
  mutually exclusive normal/catch paths); `failTurn` loses the dead post-close
  branch that only a throwing turn-end LISTENER could reach.
- ui-stdio: render turn boundaries from `session/event`, recovering the short
  agent label from an `agent/created`→id map (the `turn/start` event carries only
  the turn number, and the session id is not reliably the agent id). ui-stdio is
  a disposable test REPL, so this migration retires the sole justification the
  event-domain-semantics RFC gave for KEEPING the turn mirrors.
- Tests: reason/turn-number collectors and the boundary-ordering test now read
  `session/event`; the throwing-turn-boundary-LISTENER tests are deleted (that
  code path no longer exists). A new test covers the outer-catch disposed branch
  via a pre-step listener that disposes-then-throws (the surviving real path).
- Docs: promote the "remove agent boundary mirror events" RFC to implemented
  (amended/narrowed — `agent/steering` is RETAINED, not a boundary mirror);
  update the event-domain-semantics + turn-enclosure RFCs, architecture.md, the
  cookbook, the ACP/agent/ui-stdio prose, and regenerate the cordis catalog.

`agent/steering` and `agent/stream-chunk` are explicitly out of scope (not
durable-boundary mirrors). ACP is unaffected — it already settles from the log's
`turn/end` + `agent/status`; snapshot goldens are byte-unchanged.
This commit is contained in:
Tianyi Cui
2026-07-02 03:26:45 +08:00
parent bdf390679b
commit 140f818a42
20 changed files with 282 additions and 441 deletions

View File

@@ -145,7 +145,7 @@ export interface LoopHandle {
* forever:
* wait for queued messages (idle)
* TURN (error-contained — a throwing plugin ends the turn, never the loop):
* drain queued → 'turn/start' → session('user/message'…) → emit agent/turn-start
* drain queued → 'turn/start' → session('user/message'…) ⟵ durable turn boundary (no agent/* mirror)
* STEP loop:
* drain steering → session('steering/message') ⟵ catches late steering
* assembly = ctx.systemPrompt.assemble() ⟵ waterfall system-prompt/assemble
@@ -165,7 +165,7 @@ export interface LoopHandle {
* cont = waterfall agent/turn-continuation(default = hadToolCalls || steered)
* if !cont && steering arrived from step/end session-event/continuation listeners: cont = true
* if !cont: break
* session('turn/end'); emit agent/turn-end
* session('turn/end') ⟵ durable turn boundary (no agent/* mirror)
* await ctx.parallel('session/flush', session) ⟵ durability checkpoint
* re-enqueue leftover steering as queued ⟵ steering is never stranded
* idle (emit agent/status) unless more queued
@@ -277,7 +277,6 @@ async function runTurn(ctx: Context, agent: ReactLoopAgent, handle: LoopHandle,
let reason: TurnEndReason = { kind: 'completed' }
let step = 0
let turnEnded = false
let stepOpen = false
let errorReported = false
@@ -320,47 +319,38 @@ async function runTurn(ctx: Context, agent: ReactLoopAgent, handle: LoopHandle,
const failTurn = (err: CodedError): void => {
if (errorReported) return
errorReported = true
// Set the error reason ONLY while the turn is still open — closeTurn appends
// turn/end with it. If the turn has already ended (the only way here: a
// throwing agent/turn-end listener after closeTurn(true) already appended
// turn/end), the reason can no longer affect the durable log, so log the late
// throw directly instead — otherwise the listener exception would vanish.
if (!turnEnded) {
reason = { kind: 'error', step, ...errorData(err) }
} else {
ctx.logger.warn(`agent "${agent.id}": agent/turn-end listener threw after turn ${turn} closed: ${err.message}`)
}
// The turn is always still open here: the only failure that can reach
// failTurn once turn/end is appended would be a throwing turn-boundary
// listener, and turn boundaries are durable session events with no agent/*
// mirror to throw. A throwing `turn/end` session-event listener is already
// contained inside closeTurn (append pushes before notifying, so the
// boundary is durable). So set the error reason for closeTurn to append.
reason = { kind: 'error', step, ...errorData(err) }
try {
ctx.emit('agent/error', agent, turn, step, err)
} catch {
// contained: the error is already captured (on `reason`, or via the logger
// above); a throwing agent/error listener must not prevent the turn from
// closing.
// contained: the error is already captured on `reason`; a throwing
// agent/error listener must not prevent the turn from closing.
}
}
// Close the turn exactly once (idempotent via turnEnded). `emit` is false on
// the error path (the failure was already surfaced via agent/error) and true
// on the normal/inline-error path. A throwing agent/turn-end listener on the
// normal path escapes to the outer catch, which surfaces it via failTurn —
// turn/end is already appended, so balance holds either way.
const closeTurn = (emit: boolean): void => {
if (turnEnded) return
turnEnded = true
// Close the turn. Called exactly once per turn — the normal loop exit and the
// outer catch are mutually exclusive paths, and this never throws (the append
// is contained below), so there is no re-entry to guard against (unlike
// closeStep, which the cancel branches and the outer catch can both reach).
// Turn boundaries are durable session events only — there is no agent/* turn
// emit to mirror them (see the agent event-domain rule).
const closeTurn = (): void => {
// Session.append pushes turn/end BEFORE notifying session/event listeners,
// so a throwing listener leaves turn/end in the log (the turn is balanced)
// but would otherwise escape — from the outer catch's closeTurn(false) it
// would propagate to the runLoop backstop, and from the normal-path
// closeTurn(true) it would skip the agent/turn-end emit. Contain it: the
// boundary is durable either way, and finalization must not abort on a bad
// listener. (On the normal path the outer catch also re-runs closeTurn,
// which is an idempotent no-op once turnEnded is set.)
// but would otherwise escape — from the outer catch it would propagate to
// the runLoop backstop. Contain it: the boundary is durable either way, and
// finalization must not abort on a bad listener.
try {
session.append('turn/end', { turn, reason })
} catch (error: unknown) {
ctx.logger.warn(`agent "${agent.id}": session/event listener threw on turn/end at turn ${turn}: ${toError(error).message}`)
}
if (emit) ctx.emit('agent/turn-end', agent, turn, reason)
}
try {
@@ -375,13 +365,12 @@ async function runTurn(ctx: Context, agent: ReactLoopAgent, handle: LoopHandle,
for (const message of queued) {
session.append('user/message', { content: message.content, source: message.source }, { surfaceOp: 'append' })
}
ctx.emit('agent/turn-start', agent, turn)
while (true) {
step += 1
// Steering from the previous round's continuation listeners (or
// turn-start listeners on the first step) joins before the request.
// Steering from the previous round's continuation listeners joins before
// the request.
drainSteering(ctx, agent, turn)
// The step's AbortController exists BEFORE any async pre-step work so a
@@ -530,8 +519,8 @@ async function runTurn(ctx: Context, agent: ReactLoopAgent, handle: LoopHandle,
}
}
// Normal / inline-error loop exit: close the turn and notify.
closeTurn(true)
// Normal / inline-error loop exit: close the turn.
closeTurn()
} catch (error: unknown) {
// Decide whether this turn was ever opened from the LOG, not a flag.
// Session.append pushes the event BEFORE notifying session/event listeners,
@@ -550,18 +539,16 @@ async function runTurn(ctx: Context, agent: ReactLoopAgent, handle: LoopHandle,
closeStep()
// Choose the close reason. Disposal wins only if no error was already
// reported: a turn disposed mid-step sets reason=disposed in the step-error
// branch (without reporting an error), and if closeTurn(true)'s turn-end
// emit then throws, we land here and must PRESERVE disposed rather than
// overwrite it with the listener's throw. Otherwise a boundary-emit throw
// on a live agent is a real failure → failTurn. (errorReported is mutated
// only inside the failTurn closure, which the analyzer can't follow, hence
// the inline lint-disable.)
// branch (without reporting an error), so preserve disposed rather than
// overwrite it. Otherwise a mid-step throw on a live agent is a real
// failure → failTurn. (errorReported is mutated only inside the failTurn
// closure, which the analyzer can't follow, hence the inline lint-disable.)
if (handle.isDisposed() && !errorReported) { // eslint-disable-line @typescript-eslint/no-unnecessary-condition
reason = { kind: 'disposed' }
} else {
failTurn(toError(error))
}
closeTurn(false)
closeTurn()
}
// Durability checkpoint: persistence plugins drain write-behind buffers.

View File

@@ -117,7 +117,7 @@ describe('Agent.cancel()', () => {
const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
const reasons: TurnEndReason[] = []
ctx.on('agent/turn-end', (_a, _t, reason) => void reasons.push(reason))
ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
send(agent, 'go')
await new Promise(r => setTimeout(r, 30))
@@ -134,7 +134,7 @@ describe('Agent.cancel()', () => {
const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
const reasons: TurnEndReason[] = []
ctx.on('agent/turn-end', (_a, _t, reason) => void reasons.push(reason))
ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
send(agent, 'go')
await new Promise(r => setTimeout(r, 30))
@@ -166,22 +166,23 @@ describe('Agent.cancel()', () => {
expect(reasons.length).toBe(2)
})
it('cancel from a synchronous agent/turn-start listener drops the step (step-start window)', async () => {
it('cancel from a synchronous turn/start session-event listener drops the step (step-start window)', async () => {
const adapter = new MockAdapter([textResponse('should not stream')])
const ctx = await harness(adapter)
const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
// A turn-start listener fires BEFORE any AbortController is installed for the
// step. Cancelling there must still drop the step (the turn-scoped marker,
// not the step AbortController, is what catches this) — no model step runs.
// A turn/start listener fires right after turn/start is appended, BEFORE any
// AbortController is installed for the step. Cancelling there must still drop
// the step (the turn-scoped marker, not the step AbortController, is what
// catches this) — no model step runs.
let streamed = false
ctx.on('agent/stream-chunk', () => { streamed = true })
const dispose = ctx.on('agent/turn-start', (subject) => {
if (subject === agent) agent.cancel('from turn-start')
const dispose = ctx.on('session/event', (session, event) => {
if (session === agent.session && event.type === 'turn/start') agent.cancel('from turn-start')
})
const reasons: TurnEndReason[] = []
ctx.on('agent/turn-end', (_a, _t, reason) => void reasons.push(reason))
ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
send(agent, 'go')
await waitForIdle(ctx, agent)
@@ -210,7 +211,7 @@ describe('Agent.cancel()', () => {
})
const reasons: TurnEndReason[] = []
ctx.on('agent/turn-end', (_a, _t, reason) => void reasons.push(reason))
ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
send(agent, 'go')
await waitForIdle(ctx, agent)
@@ -271,9 +272,11 @@ describe('Agent.cancel()', () => {
const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
let steps = 0
ctx.on('session/event', (_session, event) => { if (event.type === 'step/start') steps += 1 })
const reasons: TurnEndReason[] = []
ctx.on('agent/turn-end', (_a, _t, reason) => void reasons.push(reason))
ctx.on('session/event', (_session, event) => {
if (event.type === 'step/start') steps += 1
if (event.type === 'turn/end') reasons.push(event.data.reason)
})
let continued = false
ctx.on('agent/turn-continuation', async (subject, _turn, _default, next) => {

View File

@@ -36,69 +36,6 @@ function send(agent: ReactLoopAgent, text: string) {
}
describe('turn boundary listener throws (handled in-turn, loop survives)', () => {
it('a throwing agent/turn-start listener surfaces via agent/error and the loop survives', async () => {
// The agent/turn-start emit happens AFTER turn/start is appended to the log,
// so a throwing listener is handled inside runTurn (the turn is balanced and
// closed via failTurn → agent/error), NOT rethrown to the runLoop backstop.
// The second turn should proceed normally and consume the first script entry.
const adapter = new MockAdapter([textResponse('turn 2')])
const ctx = await harness(adapter)
const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
let threwOnce = false
ctx.on('agent/turn-start', () => {
if (!threwOnce) {
threwOnce = true
throw new Error('broken turn-start listener')
}
})
const errors: Error[] = []
ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
send(agent, 'first')
await waitForIdle(ctx, agent)
expect(errors.map(e => e.message)).toEqual(['broken turn-start listener'])
// The turn is balanced: its turn/start was logged, so a turn/end was owed
// and appended (decided from the log, not a flag).
expect(agent.session.events.at(-1)?.type).toBe('turn/end')
// loop survives: second turn works fine and makes the model call
send(agent, 'second')
await waitForIdle(ctx, agent)
expect(adapter.requests).toHaveLength(1)
expect(adapter.requests[0]!.messages.some(m => m.content.some(b => 'text' in b && b.text === 'second'))).toBe(true)
})
it('a throwing agent/turn-end listener surfaces via agent/error and the loop survives', async () => {
const adapter = new MockAdapter([textResponse('turn 1'), textResponse('turn 2')])
const ctx = await harness(adapter)
const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
let threwOnce = false
ctx.on('agent/turn-end', () => {
if (!threwOnce) {
threwOnce = true
throw new Error('broken turn-end listener')
}
})
const errors: Error[] = []
ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
send(agent, 'first')
await waitForIdle(ctx, agent)
// The turn-end throw happens after the model call is complete, so turn 1's
// request is consumed. turn/end is already in the log (append pushes before
// notifying), so the turn is balanced; the error is surfaced via agent/error.
expect(errors.map(e => e.message)).toEqual(['broken turn-end listener'])
// loop survives: second turn works fine
send(agent, 'second')
await waitForIdle(ctx, agent)
expect(adapter.requests).toHaveLength(2)
})
it('a pre-push turn/start failure (non-serializable source) is rethrown to the runLoop backstop', async () => {
// A non-serializable message source makes the turn/start append throw BEFORE
// the event is pushed (Session.append validates before push), so turn/start
@@ -192,14 +129,14 @@ describe('tool JSON parse', () => {
})
describe('toError normalization', () => {
it('normalizes non-Error throws from turn-start listeners via toError', async () => {
it('normalizes non-Error throws from a turn/start session-event listener via toError', async () => {
const adapter = new MockAdapter([textResponse('ok')])
const ctx = await harness(adapter)
const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
let threwOnce = false
ctx.on('agent/turn-start', () => {
if (!threwOnce) {
ctx.on('session/event', (_session, event) => {
if (event.type === 'turn/start' && !threwOnce) {
threwOnce = true
throw 'naked string error' // non-Error throw, normalized via toError
}
@@ -287,7 +224,7 @@ describe('disposed vs aborted branching', () => {
}, { inject: ['agentLoop'] }))
const reasons: TurnEndReason[] = []
ctx.on('agent/turn-end', (_agent, _turn, reason) => void reasons.push(reason))
ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
send(agent, 'go')
await new Promise(r => setTimeout(r, 30))

View File

@@ -46,21 +46,20 @@ describe('agent loop', () => {
const ctx = await harness(adapter)
const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
// Turn boundaries are live agent/* emits; step boundaries are durable
// session events only (no agent/* mirror). Interleave both feeds in fire
// order to assert the full boundary nesting.
// All boundaries — turn and step — are durable session events on the
// session/event feed (no agent/* mirror). Record them in fire order to
// assert the full boundary nesting.
const order: string[] = []
for (const name of ['agent/turn-start', 'agent/turn-end'] as const) {
ctx.on(name, () => void order.push(name))
}
ctx.on('session/event', (_session, event) => {
if (event.type === 'step/start' || event.type === 'step/end') order.push(event.type)
if (event.type === 'turn/start' || event.type === 'step/start' || event.type === 'step/end' || event.type === 'turn/end') {
order.push(event.type)
}
})
send(agent, 'hi')
await waitForIdle(ctx, agent)
expect(order).toEqual(['agent/turn-start', 'step/start', 'step/end', 'agent/turn-end'])
expect(order).toEqual(['turn/start', 'step/start', 'step/end', 'turn/end'])
const types = agent.session.events.map(e => e.type)
// turn/start opens the turn, THEN the queued user message is recorded inside
@@ -436,7 +435,7 @@ describe('agent loop', () => {
const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
const reasons: TurnEndReason[] = []
ctx.on('agent/turn-end', (_agent, _turn, reason) => void reasons.push(reason))
ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
send(agent, 'go')
// wait until the stream is hanging, then cancel
@@ -456,7 +455,7 @@ describe('agent loop', () => {
const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
const reasons: TurnEndReason[] = []
ctx.on('agent/turn-end', (_agent, _turn, reason) => void reasons.push(reason))
ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
send(agent, 'go')
await waitForIdle(ctx, agent)
@@ -490,7 +489,7 @@ describe('agent loop', () => {
})
const reasons: TurnEndReason[] = []
ctx.on('agent/turn-end', (_agent, _turn, reason) => void reasons.push(reason))
ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
send(agent, 'go')
await waitForIdle(ctx, agent)
@@ -512,7 +511,7 @@ describe('agent loop', () => {
const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
const reasons: TurnEndReason[] = []
ctx.on('agent/turn-end', (_agent, _turn, reason) => void reasons.push(reason))
ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
send(agent, 'first')
await waitForIdle(ctx, agent)
@@ -545,7 +544,7 @@ describe('agent loop', () => {
const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
const reasons: TurnEndReason[] = []
ctx.on('agent/turn-end', (_agent, _turn, reason) => void reasons.push(reason))
ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
send(agent, 'go')
await waitForIdle(ctx, agent)
@@ -587,7 +586,7 @@ describe('agent loop', () => {
const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
const reasons: TurnEndReason[] = []
ctx.on('agent/turn-end', (_agent, _turn, reason) => void reasons.push(reason))
ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
send(agent, 'go')
await waitForIdle(ctx, agent)
@@ -606,7 +605,7 @@ describe('agent loop', () => {
const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
const reasons: TurnEndReason[] = []
ctx.on('agent/turn-end', (_agent, _turn, reason) => void reasons.push(reason))
ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
send(agent, 'go')
await waitForIdle(ctx, agent)
@@ -683,7 +682,7 @@ describe('agent loop', () => {
const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
const turns: number[] = []
ctx.on('agent/turn-start', (_agent, turn) => void turns.push(turn))
ctx.on('session/event', (_s, event) => { if (event.type === 'turn/start') turns.push(event.data.turn) })
// queue two messages while idle — first starts turn 1 immediately;
// queue the second during turn 1 via a stream-chunk hook
@@ -730,7 +729,7 @@ describe('agent loop', () => {
const errors: Error[] = []
const reasons: TurnEndReason[] = []
ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
ctx.on('agent/turn-end', (_agent, _turn, reason) => void reasons.push(reason))
ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
send(agent, 'hi')
await waitForIdle(ctx, agent)

View File

@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from 'vitest'
import { describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import LlmService, { CallId, MessageSource, StreamChunk } from '@deepseek-ai/dsh-llm'
import SessionStore, { Session, SessionEvent, SessionId, TurnEndReason } from '@deepseek-ai/dsh-session'
@@ -132,7 +132,7 @@ describe('HIGH: abort during tool execution ends the turn', () => {
}))
const reasons: TurnEndReason[] = []
ctx.on('agent/turn-end', (_agent, _turn, reason) => void reasons.push(reason))
ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
send(agent, 'go')
await waitForIdle(ctx, agent)
@@ -217,20 +217,21 @@ describe('HIGH: steering from late extension points is never stranded', () => {
expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('goal reminder from step/end')
})
it('steer() from an agent/turn-end listener becomes a queued message for the next turn', async () => {
it('steer() from a turn/end session-event listener becomes a queued message for the next turn', async () => {
const adapter = new MockAdapter([textResponse('turn 1'), textResponse('turn 2')])
const ctx = await harness(adapter)
const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
let steeredOnce = false
ctx.on('agent/turn-end', () => {
if (steeredOnce) return
steeredOnce = true
agent.steer([{ type: 'text', text: 'too late for this turn' }])
})
const turns: number[] = []
ctx.on('agent/turn-start', (_agent, turn) => void turns.push(turn))
let steeredOnce = false
ctx.on('session/event', (subject, event) => {
if (subject !== agent.session) return
if (event.type === 'turn/start') turns.push(event.data.turn)
if (event.type === 'turn/end' && !steeredOnce) {
steeredOnce = true
agent.steer([{ type: 'text', text: 'too late for this turn' }])
}
})
send(agent, 'go')
await waitForIdle(ctx, agent)
@@ -332,7 +333,7 @@ describe('MEDIUM: disposed status is part of the agent/status contract', () => {
const statuses: string[] = []
const reasons: TurnEndReason[] = []
ctx.on('agent/status', (_agent, status) => void statuses.push(status))
ctx.on('agent/turn-end', (_agent, _turn, reason) => void reasons.push(reason))
ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
send(agent, 'go')
await new Promise(r => setTimeout(r, 30))
@@ -461,7 +462,7 @@ describe('MEDIUM: turn numbering continues across seeded (forked) sessions', ()
ctx2.effect(() => forked.start())
const turns: number[] = []
ctx2.on('agent/turn-start', (_agent, turn) => void turns.push(turn))
ctx2.on('session/event', (_s, event) => { if (event.type === 'turn/start') turns.push(event.data.turn) })
forked.send([{ type: 'text', text: 'continue' }])
await new Promise<void>((resolve) => {
ctx2.on('agent/status', (subject, status) => {
@@ -505,7 +506,7 @@ describe('HIGH: a finish-error stream chunk ends the turn as error, not complete
const agent = ctx.agentLoop.create(AgentId('a-finish-error'), { model: 'mock' })
const reasons: TurnEndReason[] = []
ctx.on('agent/turn-end', (_agent, _turn, reason) => void reasons.push(reason))
ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
send(agent, 'go')
await waitForIdle(ctx, agent)
@@ -530,7 +531,7 @@ describe('HIGH: a finish-error stream chunk ends the turn as error, not complete
const agent = ctx.agentLoop.create(AgentId('a-finish-aborted'), { model: 'mock' })
const reasons: TurnEndReason[] = []
ctx.on('agent/turn-end', (_agent, _turn, reason) => void reasons.push(reason))
ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
send(agent, 'go')
await waitForIdle(ctx, agent)
@@ -548,7 +549,7 @@ describe('HIGH: a finish-error stream chunk ends the turn as error, not complete
const agent = ctx.agentLoop.create(AgentId('a-finish-error-nocode'), { model: 'mock' })
const reasons: TurnEndReason[] = []
ctx.on('agent/turn-end', (_agent, _turn, reason) => void reasons.push(reason))
ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
send(agent, 'go')
await waitForIdle(ctx, agent)
@@ -619,28 +620,6 @@ describe('P1-5: a started turn (and any open step) is always closed on a boundar
}
}
it('a throwing agent/turn-start listener still closes the turn with exactly one error and one turn/end, no step', async () => {
const adapter = new MockAdapter([textResponse('never reached')])
const ctx = await balancedHarness(adapter)
const agent = ctx.agentLoop.create(AgentId('a-turnstart'), { model: 'mock' })
let threw = false
ctx.on('agent/turn-start', () => { if (!threw) { threw = true; throw new Error('boom turn-start') } })
const errors: Error[] = []
ctx.on('agent/error', (_a, _t, _s, error) => void errors.push(error))
send(agent, 'go')
await waitForIdle(ctx, agent)
const c = boundaryCounts(agent)
// turn opened and closed; no step ran; exactly one error turn-end + emitted.
expect(c).toMatchObject({ turnStart: 1, turnEnd: 1, stepStart: 0, stepEnd: 0, errors: 1 })
expect(errors.map(e => e.message)).toEqual(['boom turn-start'])
expect(c.lastTurnEnd?.type === 'turn/end' && c.lastTurnEnd.data.reason).toEqual({ kind: 'error', step: 0, message: 'boom turn-start' })
// model was never called (we threw before the step's request).
expect(adapter.requests).toHaveLength(0)
})
it('a throwing step/start session-event listener closes the open step then the turn (step/end before turn/end)', async () => {
const adapter = new MockAdapter([textResponse('never reached')])
const ctx = await balancedHarness(adapter)
@@ -720,7 +699,7 @@ describe('P1-5: a started turn (and any open step) is always closed on a boundar
}, { inject: ['agentLoop'] }))
const reasons: TurnEndReason[] = []
ctx.on('agent/turn-end', (_a, _t, reason) => void reasons.push(reason))
ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
send(agent, 'go')
await new Promise(r => setTimeout(r, 30))
@@ -737,46 +716,46 @@ describe('P1-5: a started turn (and any open step) is always closed on a boundar
expect(e.some(x => x.type === 'turn/end' && x.data.reason.kind === 'error')).toBe(false)
})
it('preserves reason disposed when the turn-end emit throws during disposal (outer-catch disposed branch)', async () => {
// Dispose mid-step → the step-error branch sets reason=disposed (no error
// reported). closeTurn(true) then emits agent/turn-end, whose listener
// throws → control reaches the outer catch with isDisposed() && !errorReported,
// which must PRESERVE disposed rather than overwrite it with the listener's
// throw. This is the only path that exercises that catch sub-branch.
const adapter = new MockAdapter(['hang'])
it('preserves reason disposed when a pre-step listener disposes then throws (outer-catch disposed branch)', async () => {
// Reach the OUTER catch while disposed: an `agent/pre-step` listener requests
// disposal AND throws. The throw escapes the pre-step `await` (line ~419) to
// the loop's outer catch — BEFORE the post-pre-step disposal check at ~422
// gets to run — so the catch sees `isDisposed() && !errorReported` and must
// PRESERVE reason=disposed rather than overwrite it with the listener's throw
// (disposal is not a failure). This is the surviving path to that sub-branch
// now that there is no turn-boundary emit to throw from.
const adapter = new MockAdapter([textResponse('never reached')])
const ctx = await balancedHarness(adapter)
let agent!: ReactLoopAgent
const fiber = await ctx.plugin(Object.assign((inner: Context) => {
agent = inner.agentLoop.create(AgentId('a-dispose-emit-throw'), { model: 'mock' })
agent = inner.agentLoop.create(AgentId('a-prestep-dispose-throw'), { model: 'mock' })
}, { inject: ['agentLoop'] }))
// The FIRST agent/turn-end emit throws (the disposal-driven turn end).
let threw = false
ctx.on('agent/turn-end', () => { if (!threw) { threw = true; throw new Error('boom turn-end during disposal') } })
// Collect agent/error emissions to prove none is surfaced through that
// channel either (the listener throw must be fully contained).
ctx.on('agent/pre-step', () => {
if (threw) return
threw = true
// Request disposal, then throw in the same synchronous tick: status flips
// to 'disposed' (the disposer aborts the step controller) and the throw
// drives control into the outer catch with isDisposed() already true.
void fiber.dispose()
throw new Error('boom pre-step during disposal')
})
const errorEmits: Error[] = []
ctx.on('agent/error', (_a, _t, _s, error) => void errorEmits.push(error))
send(agent, 'go')
await new Promise(r => setTimeout(r, 30))
await fiber.dispose() // dispose during the hanging step
await agent.done
// The throwing turn-end listener actually fired — proving the outer-catch
// path was exercised, not skipped.
expect(threw).toBe(true)
const e = [...agent.session.events]
// Exactly one turn/start and one turn/end (balanced); the turn/end carries
// the disposed reason, NOT an error reason from the throwing listener.
// Balanced: one turn/start, one turn/end carrying disposed (NOT error).
expect(e.filter(x => x.type === 'turn/start')).toHaveLength(1)
const turnEnd = e.findLast(x => x.type === 'turn/end')
expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'disposed' })
// The throwing turn-end listener is contained: the turn/end carries the
// disposed reason (not an error) and no agent/error is emitted (disposal is
// not a failure; the throw is swallowed).
expect(e.some(x => x.type === 'turn/end' && x.data.reason.kind === 'error')).toBe(false)
// No step opened (the throw was before step/start) and disposal is not a
// failure, so no agent/error for the contained throw.
expect(e.some(x => x.type === 'step/start')).toBe(false)
expect(errorEmits).toHaveLength(0)
})
@@ -822,43 +801,6 @@ describe('P1-5: a started turn (and any open step) is always closed on a boundar
expect(adapter.requests).toHaveLength(1)
})
it('a throwing turn-end listener on a SUCCESSFUL turn leaves no event after turn/end (loadable log)', async () => {
// Regression: a normal turn completes, closeTurn(true) appends turn/end and
// emits agent/turn-end whose listener throws. The error must NOT be appended
// as a session event after turn/end — that would sit past the commit
// boundary and be dropped as a crash tail on resume (the turn-enclosure RFC). It is
// surfaced via agent/error instead, and the log's last event is turn/end.
const adapter = new MockAdapter([textResponse('done'), textResponse('next ok')])
const ctx = await balancedHarness(adapter)
const agent = ctx.agentLoop.create(AgentId('a-tend'), { model: 'mock' })
let threw = false
ctx.on('agent/turn-end', () => { if (!threw) { threw = true; throw new Error('boom turn-end') } })
const errors: Error[] = []
ctx.on('agent/error', (_a, _t, _s, error) => void errors.push(error))
const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
send(agent, 'go')
await waitForIdle(ctx, agent)
const c = boundaryCounts(agent)
expect(c.turnEnd).toBe(1)
expect(c.errors).toBe(0) // NO session error event (it would be post-turn/end)
expect(agent.session.events.at(-1)?.type).toBe('turn/end') // last event is the boundary
expect(errors.map(e => e.message)).toEqual(['boom turn-end']) // surfaced via agent/error
// The late throw is also logged directly: failTurn's turn-already-ended
// branch warns so a throwing turn-end listener after turn/end never vanishes.
expect(warn).toHaveBeenCalledWith(expect.stringContaining('agent/turn-end listener threw after turn 1 closed'))
// The whole log is loadable (nothing dropped): a fresh replay sees the turn.
const replay = new Session(SessionId('replay'), [...agent.session.events])
expect(replay.deriveMessages().map(m => m.role)).toEqual(['user', 'assistant'])
// loop survives.
send(agent, 'again')
await waitForIdle(ctx, agent)
expect(boundaryCounts(agent).turnEnd).toBe(2)
})
it('a throwing step/end session-event listener during a successful step ends the turn as error, not completed', async () => {
// closeStep() must surface a throwing step/end listener via failTurn so the
// turn ends with reason error, not a silent "completed" with the throw
@@ -902,39 +844,6 @@ describe('P1-5: a started turn (and any open step) is always closed on a boundar
expect(c2.stepStart).toBe(c2.stepEnd)
})
it('a step error followed by a throwing turn-end listener logs the error exactly once (no double-report)', async () => {
// The step fails (finish-error) → failTurn records ONE error and sets the
// error reason. closeTurn(true) then appends turn/end and emits
// agent/turn-end, whose listener throws → the outer catch calls failTurn
// again, but its errorReported guard makes it a no-op. Trap #1: exactly one
// error, the turn stays balanced.
const errorStream: StreamChunk[] = [{ type: 'finish', reason: { kind: 'error', message: 'provider down' } }]
const adapter = new MockAdapter([errorStream, textResponse('turn 2 ok')])
const ctx = await balancedHarness(adapter)
const agent = ctx.agentLoop.create(AgentId('a-double'), { model: 'mock' })
let threw = false
ctx.on('agent/turn-end', () => { if (!threw) { threw = true; throw new Error('boom turn-end') } })
const errors: Error[] = []
ctx.on('agent/error', (_a, _t, _s, error) => void errors.push(error))
send(agent, 'go')
await waitForIdle(ctx, agent)
const c = boundaryCounts(agent)
// exactly one error turn-end + one agent/error emit, despite two failTurn calls.
expect(c.errors).toBe(1)
expect(errors.map(e => e.message)).toEqual(['provider down'])
expect(c.turnStart).toBe(1)
expect(c.turnEnd).toBe(1) // single turn/end, balanced
expect(c.lastTurnEnd?.type === 'turn/end' && c.lastTurnEnd.data.reason).toMatchObject({ kind: 'error', step: 1, message: 'provider down' })
// loop survives the compound failure.
send(agent, 'again')
await waitForIdle(ctx, agent)
expect(boundaryCounts(agent).turnEnd).toBe(2)
})
it('a throwing session/event listener on step/end during finalization still appends turn/end', async () => {
// A finish-error stream opens a step then fails it, driving finalization
// through closeStep() with the step open. closeStep appends step/end; a
@@ -974,11 +883,10 @@ describe('P1-5: a started turn (and any open step) is always closed on a boundar
it('a throwing session/event listener on turn/end is contained (turn still balanced, loop survives)', async () => {
// closeTurn appends turn/end; Session.append pushes it BEFORE notifying
// session/event listeners, so a throwing listener leaves turn/end in the log
// (the turn is balanced) but must not escape — from the normal-path
// closeTurn(true) it would otherwise propagate; the append is contained so
// the turn/end emit + loop continue. (A throwing agent/turn-end LISTENER is
// a separate, already-tested path; here the session/event append notify is
// what throws.)
// (the turn is balanced) but must not escape — from the normal-path closeTurn
// it would otherwise propagate; the append is contained so the loop continues.
// Turn boundaries are durable session events only (no agent/* mirror), so this
// session/event append-notify throw is the sole turn-end-listener failure path.
const adapter = new MockAdapter([textResponse('turn 1'), textResponse('turn 2')])
const ctx = await harness(adapter)
const agent = ctx.agentLoop.create(AgentId('a-turnendappend'), { model: 'mock' })
@@ -1117,7 +1025,7 @@ describe('disposal/cancel honored during pre-step assembly (P1-1)', () => {
}, { inject: ['agentLoop'] }))
const reasons: TurnEndReason[] = []
ctx.on('agent/turn-end', (_a, _t, reason) => void reasons.push(reason))
ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
send(agent, 'go')
// Give the loop time to enter the step and reach assemble().
@@ -1143,10 +1051,8 @@ describe('disposal/cancel honored during pre-step assembly (P1-1)', () => {
// No step was opened, no LLM call was made.
expect(e.some(x => x.type === 'step/start')).toBe(false)
expect(e.some(x => x.type === 'assistant/chunk')).toBe(false)
// agent/turn-end may not fire when disposal happens during assembly: the
// fiber's disposer (stop→status=disposed) runs before closeTurn(true)'s
// emit, and the LIFO chain disposes effects in reverse registration order.
// The turn/end durable record is the one that matters.
// The durable turn/end record is the authoritative turn-boundary signal
// (turn boundaries have no agent/* mirror), so this asserts on the log.
})
it('cancel during system-prompt assembly drops the about-to-start step as aborted', { timeout: 30000 }, async () => {
@@ -1175,7 +1081,7 @@ describe('disposal/cancel honored during pre-step assembly (P1-1)', () => {
}, { inject: ['agentLoop'] }))
const reasons: TurnEndReason[] = []
ctx.on('agent/turn-end', (_a, _t, reason) => void reasons.push(reason))
ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
send(agent, 'go')
await new Promise(r => setTimeout(r, 50))
@@ -1230,7 +1136,7 @@ describe('disposal/cancel honored during pre-step assembly (P1-1)', () => {
}, { inject: ['agentLoop'] }))
const reasons: TurnEndReason[] = []
ctx.on('agent/turn-end', (_a, _t, reason) => void reasons.push(reason))
ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
send(agent, 'go')
await new Promise(r => setTimeout(r, 50))
@@ -1251,9 +1157,8 @@ describe('disposal/cancel honored during pre-step assembly (P1-1)', () => {
expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'disposed' })
expect(e.some(x => x.type === 'step/start')).toBe(false)
expect(e.some(x => x.type === 'assistant/chunk')).toBe(false)
// agent/turn-end may not fire when disposal happens during pre-step: the
// fiber's disposer runs before closeTurn(true)'s emit. The durable turn/end
// is the authoritative record.
// The durable turn/end record is the authoritative turn-boundary signal
// (turn boundaries have no agent/* mirror).
})
it('cancel during agent/pre-step seam ends the turn aborted', { timeout: 15000 }, async () => {
@@ -1283,7 +1188,7 @@ describe('disposal/cancel honored during pre-step assembly (P1-1)', () => {
}, { inject: ['agentLoop'] }))
const reasons: TurnEndReason[] = []
ctx.on('agent/turn-end', (_a, _t, reason) => void reasons.push(reason))
ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
send(agent, 'go')
await new Promise(r => setTimeout(r, 30))
@@ -1348,7 +1253,7 @@ describe('disposal/cancel honored during pre-step assembly (P1-1)', () => {
expect(e.some(x => x.type === 'assistant/chunk')).toBe(false)
expect(e.some(x => x.type === 'assistant/message')).toBe(false)
expect(adapter.requests).toHaveLength(0)
// The durable turn/end reason is the authoritative record; agent/turn-end
// may not fire when disposal interleaves with closeTurn(true)'s emit.
// The durable turn/end reason is the authoritative turn-boundary record
// (turn boundaries have no agent/* mirror).
})
})

View File

@@ -32,11 +32,9 @@ The full `agent/*` event taxonomy is declared via declaration merging in `dsh-ag
- `agent/status` — idle / running / disposed transition
- `agent/queued` — message entered inbox (source-resolved, steering flag)
#### Turn boundaries (emit)
#### Boundaries are durable session events, not `agent/*` emits
- `agent/turn-start`, `agent/turn-end` (carries `TurnEndReason`)
Step boundaries are NOT mirrored as `agent/*` emits: a consumer that needs per-step boundaries reads the durable `step/start`/`step/end` session events (the session log is the live boundary feed). The turn boundaries stay as `agent/*` emits because the stdio UI needs the `Agent` handle (`agent.id`) at the boundary, which the session event does not carry. See [the event-domain-semantics RFC](../../../docs/rfc/implemented/architecture/2026-06-30-event-domain-semantics.md).
Turn and step boundaries are NOT mirrored as `agent/*` emits: a consumer that needs them reads the durable `turn/start`/`turn/end`/`step/start`/`step/end` events off the `session/event` feed (the session log is the live boundary feed, carrying the `Session` — the turn/step numbers and reasons ride on the event data). See [the event-domain-semantics RFC](../../../docs/rfc/implemented/architecture/2026-06-30-event-domain-semantics.md) and [the remove-boundary-mirror-events RFC](../../../docs/rfc/implemented/simplification/2026-06-20-remove-agent-boundary-mirror-events.md).
#### Interception seams

View File

@@ -26,13 +26,12 @@
*
* **The rule:** a durable, replayable fact is a SessionEvent; a live
* interception or a transient/live-object signal is an `agent`/`tools` Cordis
* event. A datum that is BOTH (a turn/step boundary) lives in the session log,
* and is mirrored as an `agent/*` emit ONLY where a live consumer provably
* needs the `Agent` handle at that instant. Turn boundaries are so mirrored
* (the stdio UI labels output by `agent.id`); step boundaries are NOT (no live
* consumer needs them — read `step/start`/`step/end` from the session log).
* event. A turn/step boundary is a durable fact: it lives in the session log
* and is read off the `session/event` feed — it is NOT mirrored as an `agent/*`
* emit. A consumer that needs the `Agent` handle (or its short id) at a boundary
* keeps a session-id→agent map from `agent/created`/`agent/disposed`.
* See `docs/rfc/implemented/architecture/2026-06-11-microkernel-event-taxonomy.md`
* and the related `docs/rfc/proposed/simplification/2026-06-20-remove-agent-boundary-mirror-events.md`.
* and `docs/rfc/implemented/simplification/2026-06-20-remove-agent-boundary-mirror-events.md`.
*
* @module @deepseek-ai/dsh-agent/types
*/
@@ -47,7 +46,7 @@ export type AgentId = Branded<'AgentId'>
export function AgentId(id: string): AgentId {
return id as AgentId
}
import type { Session, TurnEndReason } from '@deepseek-ai/dsh-session'
import type { Session } from '@deepseek-ai/dsh-session'
/**
* Options an agent is created with.
@@ -183,26 +182,11 @@ declare module 'cordis' {
*/
'agent/queued'(agent: Agent, content: ContentBlock[], info: { source: MessageSource; steering: boolean }): void
// ---- turn boundaries (emit) — the live boundary surface ----
// Step boundaries are NOT mirrored here: a consumer that needs per-step
// boundaries reads the durable `step/start`/`step/end` session events (the
// session log is the live transcript feed). The TURN boundaries stay as
// agent/* emits because the only live consumer (the stdio UI) needs the
// `Agent` handle at the boundary to label output, which the session event
// does not carry. See the module doc's three-domain rule.
/**
* A turn began. `turn` is the 1-based turn number within the session.
* @mode emit
*/
'agent/turn-start'(agent: Agent, turn: number): void
/**
* A turn ended. `reason` distinguishes a clean stop from a truncated,
* aborted, failed, disposed, or crash-interrupted one (`completed` |
* `aborted` | `error` | `disposed` | `max-tokens` | `interrupted`); the
* reason union is merge-extensible, so a plugin can add further variants.
* @mode emit
*/
'agent/turn-end'(agent: Agent, turn: number, reason: TurnEndReason): void
// Turn and step boundaries are NOT mirrored as agent/* emits: a consumer
// that needs them reads the durable `turn/start`/`turn/end`/`step/start`/
// `step/end` session events off the `session/event` feed (the session log is
// the live transcript feed). See the module doc's three-domain rule and the
// "remove agent boundary mirror events" RFC.
// ---- step/request extension seams (serial + waterfall) ----
/**

View File

@@ -1,6 +1,8 @@
# @deepseek-ai/dsh-ui-stdio
A minimal stdio (readline) UI, as a plugin. It reads lines from stdin and feeds them to an agent (`send` when idle, `steer` while a turn is running), and renders that agent's streamed output and tool activity to stdout. A UI is "just a plugin" here — it only consumes the `agent/*` event taxonomy plus the `agents` service (`inject: ['agents']`), so the same plugin drives any example or product surface.
A minimal stdio (readline) UI, as a plugin. It reads lines from stdin and feeds them to an agent (`send` when idle, `steer` while a turn is running), and renders that agent's streamed output and tool activity to stdout. A UI is "just a plugin" here — it consumes the `session/event` transcript feed plus a few `agent/*` control events (`agent/stream-chunk`, `agent/status`, `agent/created`/`agent/disposed`) and the `agents` service (`inject: ['agents']`), so the same plugin drives any example or product surface.
This is a **convenience REPL for local testing and the demos, not a product surface** — its observable behavior is free to change. It is deliberately NOT treated as a load-bearing consumer when weighing whether a live event/API must exist: the boundary mirror events were removed precisely because "ui-stdio renders from them" is not a product constraint (it was migrated to `session/event`). The real product surfaces are the ACP bridge (`dsh-acp`) and the app packages.
This package consolidates what were two near-identical copies under `examples/echo-agent` and `examples/coding-agent`. The coding copy was a superset; this package IS that superset — dimmed chain-of-thought rendering plus robust piped-stdin EOF handling — with the per-consumer differences moved into `Config`.
@@ -23,8 +25,7 @@ This package consolidates what were two near-identical copies under `examples/ec
Rendering is **global** — every agent's events are written to stdout, not just `config.agent`'s. `config.agent` scopes only *input* (which agent stdin drives) and the EOF-exit gate; the single-agent demos this serves have just one agent, so the distinction is moot for them. (A multi-agent UI that needs per-agent panes would filter these handlers by the agent argument — deliberately out of scope here.)
- `agent/stream-chunk``text-delta` is written verbatim; `reasoning-delta` is wrapped in the dim SGR (`\x1B[2m … \x1B[0m`) so the chain-of-thought is visually subordinate to the answer. Reasoning rendering is inert when no `reasoning-delta` chunks arrive (e.g. a mock model), so it is always on.
- `agent/turn-start` / `agent/turn-end` — a `[<agent> turn N]` header and a trailing `> ` prompt.
- `session/event``tool/call` renders `[tool call] name(args)`; `tool/result` renders the joined text blocks as `[tool result] …`.
- `session/event` — the durable transcript feed drives all boundary and content rendering: `turn/start` prints a `[<agent> turn N]` header (the short agent label comes from an `agent/created`→id map, since the turn event carries only the turn number), `turn/end` prints the trailing `> ` prompt, `tool/call` renders `[tool call] name(args)`, `tool/result` renders the joined text blocks as `[tool result] …`, and `todo/write` renders a glyphed checklist.
## The I/O seam

View File

@@ -76,6 +76,15 @@ export function createStdioChat(ctx: Context, config: Config, runtime: StdioRunt
const agentId = AgentId(config.agent ?? 'main')
const { input, output, exit } = runtime
// Render label lookup: the `turn/start` session event carries only the turn
// number, so to print the short agent id (`[main turn 1]`) we map the
// session's id to its agent's id. The session id is not reliably the agent id
// (a session can be created with an explicit/client-supplied id), so build the
// map from `agent/created` rather than parsing the id string.
const labelBySession = new Map<string, string>()
ctx.on('agent/created', (agent) => { labelBySession.set(agent.session.header.id, agent.id) })
ctx.on('agent/disposed', (agent) => { labelBySession.delete(agent.session.header.id) })
let inReasoning = false
ctx.on('agent/stream-chunk', (_agent, _turn, _step, chunk) => {
if (chunk.type === 'reasoning-delta') {
@@ -90,18 +99,18 @@ export function createStdioChat(ctx: Context, config: Config, runtime: StdioRunt
}
})
ctx.on('agent/turn-start', (agent, turn) => {
output.write(`\n[${agent.id} turn ${turn}] `)
})
ctx.on('agent/turn-end', () => {
if (inReasoning) output.write('\x1B[0m')
inReasoning = false
output.write('\n> ')
})
ctx.on('session/event', (_session, event) => {
if (event.type === 'tool/call') {
// Transcript rendering off the durable `session/event` feed — turn/step
// boundaries, tool activity, and todos all come from the one canonical stream
// (no agent/* boundary mirrors).
ctx.on('session/event', (session, event) => {
if (event.type === 'turn/start') {
const label = labelBySession.get(session.header.id) ?? session.header.id
output.write(`\n[${label} turn ${event.data.turn}] `)
} else if (event.type === 'turn/end') {
if (inReasoning) output.write('\x1B[0m')
inReasoning = false
output.write('\n> ')
} else if (event.type === 'tool/call') {
const { name: toolName, arguments: args } = event.data
if (inReasoning) output.write('\x1B[0m')
inReasoning = false

View File

@@ -56,11 +56,19 @@ function makeAgent(id: string, status: AgentStatus = 'idle'): Agent & {
status,
sent,
steered,
// A minimal session stub: the UI reads only `session.header.id` (to map the
// session back to its agent id for the turn-boundary label).
session: { header: { id: `${id}-session` } },
send: (content: ContentBlock[]) => void sent.push(content),
steer: (content: ContentBlock[]) => void steered.push(content),
} as never
}
/** A session stub whose `header.id` matches an agent's, for `session/event` emits. */
function makeSession(agentId: string): Session {
return { header: { id: `${agentId}-session` } } as Session
}
const CONFIG: Config = { welcome: 'hi there', agent: 'main' }
async function setup(config: Config = CONFIG, runtimeOver: Partial<StdioRuntime> = {}) {
@@ -116,23 +124,54 @@ describe('createStdioChat rendering', () => {
expect(out.text()).toBe(before)
})
it('renders turn-start and turn-end markers', async () => {
it('renders turn/start and turn/end markers from the session feed', async () => {
const { ctx, out } = await setup()
const agent = makeAgent('main')
ctx.emit('agent/turn-start', agent, 3)
// agent/created populates the session-id → agent-id label map.
ctx.emit('agent/created', agent)
const session = makeSession('main')
ctx.emit('session/event', session, {
type: 'turn/start', seq: 1, time: 0, data: { turn: 3, trigger: { kind: 'message' } },
} as SessionEvent)
expect(out.text()).toContain('[main turn 3] ')
ctx.emit('agent/turn-end', agent, 3, { kind: 'completed' })
ctx.emit('session/event', session, {
type: 'turn/end', seq: 2, time: 0, data: { turn: 3, reason: { kind: 'completed' } },
} as SessionEvent)
expect(out.text()).toContain('\n> ')
})
it('resets dim styling at turn-end if a turn ends mid-reasoning', async () => {
it('falls back to the session id as the label when no agent is mapped', async () => {
const { ctx, out } = await setup()
// No agent/created emitted, so the label map is empty — the header id shows.
ctx.emit('session/event', makeSession('orphan'), {
type: 'turn/start', seq: 1, time: 0, data: { turn: 1, trigger: { kind: 'message' } },
} as SessionEvent)
expect(out.text()).toContain('[orphan-session turn 1] ')
})
it('resets dim styling at turn/end if a turn ends mid-reasoning', async () => {
const { ctx, out } = await setup()
const agent = makeAgent('main')
ctx.emit('agent/stream-chunk', agent, 1, 0, { type: 'reasoning-delta', index: 0, text: 'mid' })
ctx.emit('agent/turn-end', agent, 1, { kind: 'completed' })
ctx.emit('session/event', makeSession('main'), {
type: 'turn/end', seq: 1, time: 0, data: { turn: 1, reason: { kind: 'completed' } },
} as SessionEvent)
expect(out.text()).toContain('\x1B[2mmid\x1B[0m')
})
it('drops the label mapping on agent/disposed', async () => {
const { ctx, out } = await setup()
const agent = makeAgent('main')
ctx.emit('agent/created', agent)
ctx.emit('agent/disposed', agent)
// After disposal the map no longer resolves the agent id — fall back to the
// session header id.
ctx.emit('session/event', makeSession('main'), {
type: 'turn/start', seq: 1, time: 0, data: { turn: 1, trigger: { kind: 'message' } },
} as SessionEvent)
expect(out.text()).toContain('[main-session turn 1] ')
})
it('renders tool/call and tool/result session events', async () => {
const { ctx, out } = await setup()
const session = {} as Session
@@ -196,7 +235,8 @@ describe('createStdioChat rendering', () => {
const { ctx, out } = await setup()
const before = out.text()
ctx.emit('session/event', {} as Session, {
type: 'turn/start', seq: 1, time: 0, data: { turn: 1, trigger: { kind: 'continuation' } },
type: 'user/message', seq: 1, time: 0,
data: { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } },
} as SessionEvent)
expect(out.text()).toBe(before)
})

View File

@@ -57,7 +57,7 @@ When the client does NOT advertise the capability, none of the `_meta`/terminal
## Settle-exactly-once
A `session/prompt` resolves (or rejects) exactly once, keyed off the canonical session log (the `session/event` stream), NOT the `agent/turn-start`/`agent/turn-end` events. One listener captures the prompt's owning turn from the log's `turn/start` and settles on the matching `turn/end` — the one signal that always fires (`closeTurn` appends it unconditionally, even when a boundary emit throws and the `agent/turn-end` EVENT is skipped). A prompt settles only on ITS OWN turn (`inflight.turn === turn/end.turn`), so a stale `turn/end` for a previously-cancelled turn whose end arrives late can never settle the wrong prompt. A turn that ends `error` REJECTS the RPC with an internal error carrying the failure message (ACP has no error stop reason); every other reason resolves via the codec. As a fallback, when the agent settles to `idle`/`disposed` with a prompt still pending — e.g. a `session/event` listener registered before the bridge threw and starved the bridge's listener — an `agent/status` handler reconciles the prompt from the log (the owning turn's `turn/end`, or `cancelled` if the turn was torn down without one). An empty/whitespace prompt is rejected up front — it would queue no work, so no turn would start and the RPC would hang.
A `session/prompt` resolves (or rejects) exactly once, keyed off the canonical session log (the `session/event` stream). One listener captures the prompt's owning turn from the log's `turn/start` and settles on the matching `turn/end` — the durable boundary event (`closeTurn` appends it unconditionally; there is no `agent/*` turn mirror). A prompt settles only on ITS OWN turn (`inflight.turn === turn/end.turn`), so a stale `turn/end` for a previously-cancelled turn whose end arrives late can never settle the wrong prompt. A turn that ends `error` REJECTS the RPC with an internal error carrying the failure message (ACP has no error stop reason); every other reason resolves via the codec. As a fallback, when the agent settles to `idle`/`disposed` with a prompt still pending — e.g. a peer `session/event` listener registered before the bridge threw and starved the bridge's listener — an `agent/status` handler reconciles the prompt from the log (the owning turn's `turn/end`, or `cancelled` if the turn was torn down without one). An empty/whitespace prompt is rejected up front — it would queue no work, so no turn would start and the RPC would hang.
## Disposal & disconnect

View File

@@ -199,13 +199,14 @@ interface SessionRecord {
}
/**
* Drive the in-flight prompt's settle from the harness event stream. A turn
* can end three ways the bridge must all handle (AGENTS.md "honor cross-seam
* contracts on BOTH sides"): the normal `agent/turn-end` event; a `turn/end`
* session event WITHOUT the agent event (a boundary emit threw inside the loop,
* which still appends `turn/end`); or the agent erroring/settling to idle. The
* first of these to fire settles the prompt; `settle` is then cleared so the
* others are no-ops (settle-exactly-once).
* Drive the in-flight prompt's settle from the harness event stream. The bridge
* settles off the durable log: the `turn/end` session event on the
* `session/event` feed for the prompt's own turn, with the agent
* erroring/settling to idle as a fallback (AGENTS.md "honor cross-seam contracts
* on BOTH sides") for the case where a throwing peer `session/event` listener
* starved the bridge's listener before it saw the boundary. The first of these
* to fire settles the prompt; `settle` is then cleared so the others are no-ops
* (settle-exactly-once).
*/
export function apply(ctx: Context, config: AcpConfig): void {
// TODO(double-default): these literals duplicate the Config schema defaults
@@ -318,15 +319,14 @@ export function apply(ctx: Context, config: AcpConfig): void {
// the canonical log: every assistant/chunk and tool/call/result is logged, so
// translating from the log makes live streaming and `session/load` replay
// share the identical path (streamSessionEventUpdate). Both the owning-turn
// capture and the settle key off the log's own `turn/start`/`turn/end` — NOT
// the `agent/turn-start`/`agent/turn-end` EVENTS, which a throwing PEER
// listener (cordis `emit` stops at the first throw) or a boundary-emit failure
// can skip. `closeTurn` appends `turn/end` to the log unconditionally, and
// `turn/start` is appended before any step runs, so within this one listener
// we always see the prompt's turn-start (tag `inflight.turn`) then its
// turn-end (settle). A `turn/end` settles the prompt ONLY when it is the
// prompt's OWN turn (`inflight.turn === event.data.turn`) — a previous,
// already-cancelled turn whose end arrives late is ignored (see
// capture and the settle key off the log's own `turn/start`/`turn/end` — the
// durable boundary events (there is no agent/* turn mirror). `closeTurn`
// appends `turn/end` to the log unconditionally, and `turn/start` is appended
// before any step runs, so within this one listener we always see the
// prompt's turn-start (tag `inflight.turn`) then its turn-end (settle). A
// `turn/end` settles the prompt ONLY when it is the prompt's OWN turn
// (`inflight.turn === event.data.turn`) — a previous, already-cancelled turn
// whose end arrives late is ignored (see
// SessionRecord.inflight). A turn that ends `error` REJECTS the prompt (ACP
// has no error stop reason); other reasons resolve via the codec. Demux
// strictly by session id: a `session/event` is routed to its own record, so