From 8eb3ad586b6e2bcf8d018e94b045b51c293838fd Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot <318394648+systemfsoftware-bot@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:09:03 -0500 Subject: [PATCH 1/5] feat(agui): project the durable Thread log to AG-UI events Add `projectDurableAgUi` and `toDurableAgUiEvents` to the `./agui` export: a pure projection of a durable Thread's canonical record log (plus in-flight provisional text) into cursor-indexed AG-UI events. Settled Runs end in RUN_FINISHED or RUN_ERROR, aborted and host-halted Runs end as a stopped RUN_FINISHED (cancelled), steering transitions are emitted as `agent.steering` custom events, and structured run output travels in RUN_FINISHED.result with a typed decode extension. The projector lives in `durable/` because the `engine` layer may not import `durable`; `./agui` now targets a top-level barrel that re-exports both `engine/AgUi` and the projector, preserving the existing AG-UI helpers. --- .changeset/agui-durable.md | 15 + packages/effect-agent/package.json | 6 +- packages/effect-agent/src/AgUi.ts | 2 + .../effect-agent/src/core/ProvisionalText.ts | 26 +- .../effect-agent/src/durable/DurableAgUi.ts | 915 ++++++++++++++++++ packages/effect-agent/src/index.ts | 2 +- 6 files changed, 951 insertions(+), 15 deletions(-) create mode 100644 .changeset/agui-durable.md create mode 100644 packages/effect-agent/src/AgUi.ts create mode 100644 packages/effect-agent/src/durable/DurableAgUi.ts diff --git a/.changeset/agui-durable.md b/.changeset/agui-durable.md new file mode 100644 index 00000000..625a56fd --- /dev/null +++ b/.changeset/agui-durable.md @@ -0,0 +1,15 @@ +--- +"@systemfsoftware/agent": minor +"@systemfsoftware/agent-ai-decision": none +"@systemfsoftware/agent-platform-cloudflare": none +"@systemfsoftware/agent-platform-node": none +"@systemfsoftware/agent-pr-review": none +"@systemfsoftware/agent-storage-cloudflare": none +"@systemfsoftware/agent-storage-memory": none +"@systemfsoftware/agent-storage-postgres": none +"@systemfsoftware/agent-storage-sql": none +"@systemfsoftware/agent-storage-sqlite": none +"@systemfsoftware/agent-testing": none +--- + +Adds `projectDurableAgUi` and `toDurableAgUiEvents` to `@systemfsoftware/agent/agui`, projecting a durable Thread's canonical record log plus in-flight provisional text into cursor-indexed AG-UI events, so a reload that replays from any sequence renders the same view a live viewer saw. Settled Runs end in `RUN_FINISHED` or `RUN_ERROR`, aborted and host-halted Runs end as a stopped `RUN_FINISHED` with the `cancelled` outcome, steering transitions are emitted as `agent.steering` custom events, and a consumer's own structured run output travels in `RUN_FINISHED.result` and can be decoded and re-emitted through the typed `output` extension. diff --git a/packages/effect-agent/package.json b/packages/effect-agent/package.json index 4c8b4c8b..9d8460a3 100644 --- a/packages/effect-agent/package.json +++ b/packages/effect-agent/package.json @@ -24,7 +24,7 @@ "./agent-registration": "./src/durable/AgentRegistration.ts", "./agent-runtime": "./src/engine/AgentRuntime.ts", "./agent-updates": "./src/core/AgentUpdates.ts", - "./agui": "./src/engine/AgUi.ts", + "./agui": "./src/AgUi.ts", "./browser-use": "./src/capabilities/BrowserUse.ts", "./budget": "./src/capabilities/Budget.ts", "./code-executor": "./src/sandbox/CodeExecutor.ts", @@ -170,8 +170,8 @@ "default": "./dist/core/AgentUpdates.mjs" }, "./agui": { - "types": "./dist/engine/AgUi.d.mts", - "default": "./dist/engine/AgUi.mjs" + "types": "./dist/AgUi.d.mts", + "default": "./dist/AgUi.mjs" }, "./browser-use": { "types": "./dist/capabilities/BrowserUse.d.mts", diff --git a/packages/effect-agent/src/AgUi.ts b/packages/effect-agent/src/AgUi.ts new file mode 100644 index 00000000..70058fd2 --- /dev/null +++ b/packages/effect-agent/src/AgUi.ts @@ -0,0 +1,2 @@ +export * from './durable/DurableAgUi' +export * from './engine/AgUi' diff --git a/packages/effect-agent/src/core/ProvisionalText.ts b/packages/effect-agent/src/core/ProvisionalText.ts index d8430a90..2bdbf9c7 100644 --- a/packages/effect-agent/src/core/ProvisionalText.ts +++ b/packages/effect-agent/src/core/ProvisionalText.ts @@ -21,18 +21,22 @@ const modelIdentity = { * Best-effort text and reasoning drafts, never canonical history. Native parts omit provider metadata. * Discard retracts one generation; AttemptEnded closes every draft for that Attempt. */ +const TextEvent = Schema.TaggedStruct('Text', { + ...modelIdentity, + part: Schema.Union([ + Response.TextStartPart, + Response.TextDeltaPart, + Response.TextEndPart, + Response.ReasoningStartPart, + Response.ReasoningDeltaPart, + Response.ReasoningEndPart, + ]), +}) + +export type TextEvent = typeof TextEvent.Type + export const Event = Schema.Union([ - Schema.TaggedStruct('Text', { - ...modelIdentity, - part: Schema.Union([ - Response.TextStartPart, - Response.TextDeltaPart, - Response.TextEndPart, - Response.ReasoningStartPart, - Response.ReasoningDeltaPart, - Response.ReasoningEndPart, - ]), - }), + TextEvent, Schema.TaggedStruct('Discard', modelIdentity), Schema.TaggedStruct('AttemptEnded', attemptIdentity), ]) diff --git a/packages/effect-agent/src/durable/DurableAgUi.ts b/packages/effect-agent/src/durable/DurableAgUi.ts new file mode 100644 index 00000000..789a800c --- /dev/null +++ b/packages/effect-agent/src/durable/DurableAgUi.ts @@ -0,0 +1,915 @@ +// @effect-diagnostics experimentalApiUsage:off +import * as AgUiSchema from 'effect/ai/AgUiSchema' +import type * as Prompt from 'effect/ai/Prompt' +import type * as Response from 'effect/ai/Response' +import * as Effect from 'effect/Effect' +import * as Match from 'effect/Match' +import * as Option from 'effect/Option' +import * as Schema from 'effect/Schema' +import * as Stream from 'effect/Stream' + +import type { RunId, ThreadId } from '../core/Identifiers' +import type * as ProvisionalText from '../core/ProvisionalText' +import { + type CanonicalRecordEnvelope, + CanonicalSequence, + SettlementFailureDiagnostic, + type SettlementOutcome, +} from './Records' + +export interface DurableAgUiEvent { + readonly sequence: CanonicalSequence + readonly event: AgUiSchema.Event +} + +export interface DurableAgUiOutput { + readonly schema: Schema.Codec + readonly project: (output: Output) => ReadonlyArray +} + +export interface DurableAgUiOptions { + readonly includeSubagents?: boolean | undefined + readonly output?: DurableAgUiOutput | undefined +} + +export interface DurableAgUiInput { + readonly records: ReadonlyArray + readonly text?: ReadonlyArray | undefined +} + +interface RunState { + started: boolean + terminated: boolean + stepName: string | undefined + textMessageId: string | undefined + reasoningMessageId: string | undefined + pendingApprovals: Array + openSubagents: Array + steeringPending: Array +} + +interface DraftState { + textId: string | undefined + reasoningId: string | undefined +} + +interface DraftIdentity { + readonly runId: string + readonly turnId: string + readonly attemptId: string + readonly generation: number +} + +interface Projector { + readonly includeSubagents: boolean + readonly projectOutput: (output: ProjectionOutput) => ReadonlyArray + readonly items: Array + readonly runs: Map + readonly committedTurnIds: Set + readonly terminatedRuns: Set + readonly subagentNames: Map + readonly subagentChildRun: Map + tail: CanonicalSequence +} + +type ProjectionOutput = Schema.Json | SettlementFailureDiagnostic | undefined + +const idleRun = (): RunState => ({ + started: false, + terminated: false, + stepName: undefined, + textMessageId: undefined, + reasoningMessageId: undefined, + pendingApprovals: [], + openSubagents: [], + steeringPending: [], +}) + +const encodeJson = (value: Schema.Json): string => + Option.getOrElse(Schema.encodeOption(Schema.fromJsonString(Schema.Json))(value), () => 'null') + +const steeringEvent = ( + phase: 'queued' | 'applied' | 'not-joined', + inputId: string, + runId: RunId | undefined, +): AgUiSchema.Event => ({ + type: 'CUSTOM', + name: 'agent.steering', + value: { phase, inputId, ...(runId === undefined ? {} : { runId }) }, +}) + +const withApproval = (pending: ReadonlyArray, toolCallId: string): ReadonlyArray => + pending.includes(toolCallId) ? pending : [...pending, toolCallId] + +const withoutApproval = (pending: ReadonlyArray, toolCallId: string): ReadonlyArray => + pending.includes(toolCallId) ? pending.filter((value) => value !== toolCallId) : pending + +const emit = ( + projector: Projector, + sequence: CanonicalSequence, + ...events: ReadonlyArray +): void => { + for (const event of events) projector.items.push({ sequence, event }) +} + +const runOf = (projector: Projector, runId: RunId): RunState => { + const existing = projector.runs.get(runId) + + if (existing !== undefined) return existing + const created = idleRun() + projector.runs.set(runId, created) + return created +} + +const closeText = (projector: Projector, run: RunState, sequence: CanonicalSequence): void => { + if (run.textMessageId === undefined) return + emit(projector, sequence, { type: 'TEXT_MESSAGE_END', messageId: run.textMessageId }) + run.textMessageId = undefined +} + +const closeReasoning = (projector: Projector, run: RunState, sequence: CanonicalSequence): void => { + if (run.reasoningMessageId === undefined) return + emit( + projector, + sequence, + { type: 'REASONING_MESSAGE_END', messageId: run.reasoningMessageId }, + { type: 'REASONING_END', messageId: run.reasoningMessageId }, + ) + run.reasoningMessageId = undefined +} + +const closeContent = (projector: Projector, run: RunState, sequence: CanonicalSequence): void => { + closeText(projector, run, sequence) + closeReasoning(projector, run, sequence) +} + +const closeStep = (projector: Projector, run: RunState, sequence: CanonicalSequence): void => { + if (run.stepName === undefined) return + emit(projector, sequence, { type: 'STEP_FINISHED', stepName: run.stepName }) + run.stepName = undefined +} + +const closeOpen = (projector: Projector, run: RunState, sequence: CanonicalSequence): void => { + closeContent(projector, run, sequence) + closeStep(projector, run, sequence) +} + +const appendText = ( + projector: Projector, + run: RunState, + runId: RunId, + sequence: CanonicalSequence, + text: string, +): void => { + closeReasoning(projector, run, sequence) + + if (run.textMessageId !== undefined) { + emit(projector, sequence, { type: 'TEXT_MESSAGE_CONTENT', messageId: run.textMessageId, delta: text }) + return + } + + const messageId = `${runId}:${sequence}:text` + run.textMessageId = messageId + emit( + projector, + sequence, + { type: 'TEXT_MESSAGE_START', messageId, role: 'assistant' }, + { type: 'TEXT_MESSAGE_CONTENT', messageId, delta: text }, + ) +} + +const appendReasoning = ( + projector: Projector, + run: RunState, + runId: RunId, + sequence: CanonicalSequence, + text: string, +): void => { + closeText(projector, run, sequence) + + if (run.reasoningMessageId !== undefined) { + emit(projector, sequence, { + type: 'REASONING_MESSAGE_CONTENT', + messageId: run.reasoningMessageId, + delta: text, + }) + return + } + + const messageId = `${runId}:${sequence}:reasoning` + run.reasoningMessageId = messageId + emit( + projector, + sequence, + { type: 'REASONING_START', messageId }, + { type: 'REASONING_MESSAGE_START', messageId, role: 'reasoning' }, + { type: 'REASONING_MESSAGE_CONTENT', messageId, delta: text }, + ) +} + +const declareToolCall = ( + projector: Projector, + run: RunState, + sequence: CanonicalSequence, + toolCallId: string, + toolName: string, + parameters: Schema.Json, +): void => { + const parentMessageId = run.textMessageId + closeContent(projector, run, sequence) + emit( + projector, + sequence, + { + type: 'TOOL_CALL_START', + toolCallId, + toolCallName: toolName, + ...(parentMessageId === undefined ? {} : { parentMessageId }), + }, + { type: 'TOOL_CALL_ARGS', toolCallId, delta: encodeJson(parameters) }, + { type: 'TOOL_CALL_END', toolCallId }, + ) +} + +const isTextPart = (part: Prompt.AssistantMessagePartEncoded): part is Response.TextPartEncoded => part.type === 'text' + +const isReasoningPart = (part: Prompt.AssistantMessagePartEncoded): part is Response.ReasoningPartEncoded => + part.type === 'reasoning' + +const isLocalToolCallPart = ( + part: Prompt.AssistantMessagePartEncoded, +): part is Response.ToolCallPartEncoded => part.type === 'tool-call' && part.providerExecuted !== true + +const appendPart = ( + projector: Projector, + run: RunState, + runId: RunId, + sequence: CanonicalSequence, + part: Prompt.AssistantMessagePartEncoded, +): void => { + Match.value(part).pipe( + Match.when(isTextPart, (value) => appendText(projector, run, runId, sequence, value.text)), + Match.when(isReasoningPart, (value) => appendReasoning(projector, run, runId, sequence, value.text)), + Match.when(isLocalToolCallPart, (value) => + declareToolCall( + projector, + run, + sequence, + value.id, + value.name, + Option.getOrElse(Schema.decodeUnknownOption(Schema.Json)(value.params), () => null), + )), + Match.orElse(() => undefined), + ) +} + +const appendTextIfPresent = ( + projector: Projector, + run: RunState, + runId: RunId, + sequence: CanonicalSequence, + text: string, +): void => { + if (text.length > 0) appendText(projector, run, runId, sequence, text) +} + +const appendAssistantContent = ( + projector: Projector, + run: RunState, + runId: RunId, + sequence: CanonicalSequence, + content: string | ReadonlyArray, +): void => { + if (typeof content === 'string') { + appendTextIfPresent(projector, run, runId, sequence, content) + } else { + content.forEach((part) => appendPart(projector, run, runId, sequence, part)) + } +} + +const appendMessage = ( + projector: Projector, + run: RunState, + runId: RunId, + sequence: CanonicalSequence, + message: Prompt.MessageEncoded, +): void => { + if (message.role === 'assistant') { + appendAssistantContent(projector, run, runId, sequence, message.content) + } +} + +const appendResponse = ( + projector: Projector, + run: RunState, + runId: RunId, + sequence: CanonicalSequence, + messages: Prompt.PromptEncoded, +): void => { + messages.content.forEach((message) => appendMessage(projector, run, runId, sequence, message)) +} + +const applySteering = (projector: Projector, sequence: CanonicalSequence, run: RunState, runId: RunId): void => { + for (const inputId of run.steeringPending) emit(projector, sequence, steeringEvent('applied', inputId, runId)) + run.steeringPending = [] +} + +const closeEachSubagent = (projector: Projector, run: RunState, sequence: CanonicalSequence): void => { + for (const subagentRunId of run.openSubagents) { + emit(projector, sequence, { + type: 'SUBAGENT_ERROR', + subagentRunId, + message: 'The subagent did not finish.', + }) + } + run.openSubagents = [] +} + +const closeSubagents = (projector: Projector, run: RunState, sequence: CanonicalSequence): void => { + if (projector.includeSubagents) closeEachSubagent(projector, run, sequence) +} + +const closeTerminal = (projector: Projector, run: RunState, sequence: CanonicalSequence): void => { + closeOpen(projector, run, sequence) + closeSubagents(projector, run, sequence) + run.pendingApprovals = [] +} + +const drainUnappliedSteering = ( + projector: Projector, + run: RunState, + sequence: CanonicalSequence, + runId: RunId, +): void => { + for (const inputId of run.steeringPending) emit(projector, sequence, steeringEvent('not-joined', inputId, runId)) + run.steeringPending = [] +} + +const failureFields = (value: ProjectionOutput): { readonly code: string | undefined; readonly message: string } => { + const decoded = Schema.decodeUnknownOption(SettlementFailureDiagnostic)(value) + return Option.isSome(decoded) + ? { code: decoded.value.errorTag, message: decoded.value.message } + : { code: undefined, message: 'The run failed.' } +} + +const decodeOutput = ( + extension: DurableAgUiOutput, + output: ProjectionOutput, +): ReadonlyArray => { + const decoded = Schema.decodeUnknownOption(extension.schema)(output) + return Option.isSome(decoded) ? extension.project(decoded.value) : [] +} + +const extensionOf = ( + options: DurableAgUiOptions | undefined, +): DurableAgUiOutput | undefined => options === undefined ? undefined : options.output + +const runOutputEvents = ( + options: DurableAgUiOptions | undefined, + output: ProjectionOutput, +): ReadonlyArray => { + const extension = extensionOf(options) + return extension === undefined ? [] : decodeOutput(extension, output) +} + +const makeProjector = (options: DurableAgUiOptions | undefined): Projector => ({ + includeSubagents: options?.includeSubagents === true, + projectOutput: (output) => runOutputEvents(options, output), + items: [], + runs: new Map(), + committedTurnIds: new Set(), + terminatedRuns: new Set(), + subagentNames: new Map(), + subagentChildRun: new Map(), + tail: CanonicalSequence.make(0), +}) + +const onRunStarted = ( + projector: Projector, + threadId: ThreadId, + sequence: CanonicalSequence, + runId: RunId, +): void => { + const run = runOf(projector, runId) + if (run.started) return + run.started = true + emit(projector, sequence, { + type: 'RUN_STARTED', + threadId, + runId, + protocolVersion: AgUiSchema.protocolVersion, + }) +} + +const queueSteering = ( + projector: Projector, + sequence: CanonicalSequence, + inputId: string, + runId: RunId | undefined, +): void => { + if (runId !== undefined) runOf(projector, runId).steeringPending.push(inputId) + emit(projector, sequence, steeringEvent('queued', inputId, runId)) +} + +const handleSteering = ( + projector: Projector, + sequence: CanonicalSequence, + submissionId: string | undefined, + runId: RunId | undefined, +): void => { + if (submissionId !== undefined) queueSteering(projector, sequence, submissionId, runId) +} + +const onUserInput = ( + projector: Projector, + sequence: CanonicalSequence, + kind: 'user' | 'steering' | 'follow-up', + submissionId: string | undefined, + runId: RunId | undefined, +): void => { + if (kind === 'steering') handleSteering(projector, sequence, submissionId, runId) +} + +const onModelResponse = ( + projector: Projector, + sequence: CanonicalSequence, + runId: RunId, + turnId: string, + turn: number, + messages: Prompt.PromptEncoded, +): void => { + const run = runOf(projector, runId) + projector.committedTurnIds.add(turnId) + applySteering(projector, sequence, run, runId) + closeOpen(projector, run, sequence) + const stepName = `turn-${turn}` + run.stepName = stepName + emit(projector, sequence, { type: 'STEP_STARTED', stepName }) + appendResponse(projector, run, runId, sequence, messages) + closeOpen(projector, run, sequence) +} + +const onToolCallSettled = ( + projector: Projector, + sequence: CanonicalSequence, + runId: RunId, + toolCallId: string, + result: Schema.Json, + isFailure: boolean, +): void => { + const run = runOf(projector, runId) + run.pendingApprovals = [...withoutApproval(run.pendingApprovals, toolCallId)] + emit(projector, sequence, { + type: 'TOOL_CALL_RESULT', + messageId: `${runId}:${toolCallId}:${isFailure ? 'error' : 'result'}`, + toolCallId, + content: encodeJson(result), + role: 'tool', + }) +} + +const onApprovalRequested = ( + projector: Projector, + sequence: CanonicalSequence, + runId: RunId, + toolCallId: string, + toolName: string, +): void => { + const run = runOf(projector, runId) + run.pendingApprovals = [...withApproval(run.pendingApprovals, toolCallId)] + emit(projector, sequence, { + type: 'CUSTOM', + name: 'effect_agent.approval_requested', + value: { toolCallId, toolName }, + }) +} + +const onApprovalDecided = ( + projector: Projector, + sequence: CanonicalSequence, + runId: RunId, + toolCallId: string, + decision: string, +): void => { + const run = runOf(projector, runId) + run.pendingApprovals = [...withoutApproval(run.pendingApprovals, toolCallId)] + emit(projector, sequence, { + type: 'CUSTOM', + name: 'effect_agent.approval_decided', + value: { toolCallId, decision }, + }) +} + +const nameOrChild = (name: string | undefined, childRunId: string): string => name ?? childRunId + +const subagentFinished = (childRunId: string, completed: boolean): AgUiSchema.Event => + completed + ? { type: 'SUBAGENT_FINISHED', subagentRunId: childRunId, outcome: { type: 'success' } } + : { type: 'SUBAGENT_FINISHED', subagentRunId: childRunId } + +const onSubagentRequested = (projector: Projector, toolCallId: string, targetAgentId: string): void => { + projector.subagentNames.set(toolCallId, targetAgentId) +} + +const onSubagentStarted = ( + projector: Projector, + sequence: CanonicalSequence, + runId: RunId, + toolCallId: string, + childRunId: string, +): void => { + projector.subagentChildRun.set(toolCallId, childRunId) + if (!projector.includeSubagents) return + const run = runOf(projector, runId) + run.openSubagents.push(childRunId) + emit(projector, sequence, { + type: 'SUBAGENT_STARTED', + subagentRunId: childRunId, + name: nameOrChild(projector.subagentNames.get(toolCallId), childRunId), + parentToolCallId: toolCallId, + }) +} + +const joinSubagent = ( + projector: Projector, + sequence: CanonicalSequence, + runId: RunId, + toolCallId: string, + childOutcome: SettlementOutcome, +): void => { + const childRunId = projector.subagentChildRun.get(toolCallId) + if (childRunId === undefined) return + const run = runOf(projector, runId) + run.openSubagents = run.openSubagents.filter((value) => value !== childRunId) + emit(projector, sequence, subagentFinished(childRunId, childOutcome === 'completed')) +} + +const onSubagentJoined = ( + projector: Projector, + sequence: CanonicalSequence, + runId: RunId, + toolCallId: string, + childOutcome: SettlementOutcome, +): void => { + if (projector.includeSubagents) joinSubagent(projector, sequence, runId, toolCallId, childOutcome) +} + +const resultField = ( + result: ProjectionOutput, +): { readonly result?: Schema.Json | SettlementFailureDiagnostic } => result === undefined ? {} : { result } + +const codeField = (code: string | undefined): { readonly code?: string } => code === undefined ? {} : { code } + +const settleCompleted = ( + projector: Projector, + threadId: ThreadId, + sequence: CanonicalSequence, + runId: RunId, + result: ProjectionOutput, +): void => { + if (result !== undefined) emit(projector, sequence, ...projector.projectOutput(result)) + emit(projector, sequence, { + type: 'RUN_FINISHED', + threadId, + runId, + ...resultField(result), + outcome: { type: 'success' }, + }) +} + +const settleFailed = (projector: Projector, sequence: CanonicalSequence, result: ProjectionOutput): void => { + const failure = failureFields(result) + emit(projector, sequence, { + type: 'RUN_ERROR', + message: failure.message, + ...codeField(failure.code), + }) +} + +const settleStopped = ( + projector: Projector, + threadId: ThreadId, + sequence: CanonicalSequence, + runId: RunId, +): void => { + emit(projector, sequence, { type: 'RUN_FINISHED', threadId, runId, outcome: { type: 'cancelled' } }) +} + +const settleRun = ( + projector: Projector, + threadId: ThreadId, + sequence: CanonicalSequence, + runId: RunId, + outcome: SettlementOutcome, + result: ProjectionOutput, +): void => { + const run = runOf(projector, runId) + closeTerminal(projector, run, sequence) + drainUnappliedSteering(projector, run, sequence, runId) + Match.value(outcome).pipe( + Match.when('completed', () => settleCompleted(projector, threadId, sequence, runId, result)), + Match.when('failed', () => settleFailed(projector, sequence, result)), + Match.orElse(() => settleStopped(projector, threadId, sequence, runId)), + ) + projector.terminatedRuns.add(runId) + run.terminated = true +} + +const settleIfLive = ( + projector: Projector, + threadId: ThreadId, + sequence: CanonicalSequence, + runId: RunId, + outcome: SettlementOutcome, + result: ProjectionOutput, +): void => { + if (projector.terminatedRuns.has(runId)) return + settleRun(projector, threadId, sequence, runId, outcome, result) +} + +const onSubmissionSettled = ( + projector: Projector, + threadId: ThreadId, + sequence: CanonicalSequence, + outcome: SettlementOutcome, + runId: RunId | undefined, + result: ProjectionOutput, +): void => { + if (runId !== undefined) settleIfLive(projector, threadId, sequence, runId, outcome, result) +} + +const onRunCompleted = ( + projector: Projector, + threadId: ThreadId, + sequence: CanonicalSequence, + runId: RunId, + output: Schema.Json, +): void => { + if (projector.terminatedRuns.has(runId)) return + const run = runOf(projector, runId) + closeTerminal(projector, run, sequence) + emit(projector, sequence, ...projector.projectOutput(output)) + drainUnappliedSteering(projector, run, sequence, runId) + emit(projector, sequence, { + type: 'RUN_FINISHED', + threadId, + runId, + result: output, + outcome: { type: 'success' }, + }) + projector.terminatedRuns.add(runId) + run.terminated = true +} + +const onRunFailed = ( + projector: Projector, + sequence: CanonicalSequence, + runId: RunId, + failure: Schema.Json, +): void => { + if (projector.terminatedRuns.has(runId)) return + const run = runOf(projector, runId) + closeTerminal(projector, run, sequence) + drainUnappliedSteering(projector, run, sequence, runId) + const fields = failureFields(failure) + emit(projector, sequence, { + type: 'RUN_ERROR', + message: fields.message, + ...codeField(fields.code), + }) + projector.terminatedRuns.add(runId) + run.terminated = true +} + +const processRecord = (projector: Projector, envelope: CanonicalRecordEnvelope): void => { + const payload = envelope.record.payload + projector.tail = envelope.sequence + const sequence = envelope.sequence + const threadId = envelope.threadId + + Match.value(payload).pipe( + Match.tags({ + RunStarted: (value) => onRunStarted(projector, threadId, sequence, value.runId), + UserInputRecorded: (value) => onUserInput(projector, sequence, value.kind, value.submissionId, value.runId), + ModelResponseRecorded: (value) => + onModelResponse(projector, sequence, value.runId, value.turnId, value.turn, value.messages), + ToolCallSettled: (value) => + onToolCallSettled(projector, sequence, value.runId, value.toolCallId, value.result, value.isFailure), + ToolApprovalRequested: (value) => + onApprovalRequested(projector, sequence, value.runId, value.toolCallId, value.toolName), + ToolApprovalDecided: (value) => + onApprovalDecided(projector, sequence, value.runId, value.toolCallId, value.decision), + ModelCallAborted: (value) => + emit(projector, sequence, { + type: 'CUSTOM', + name: 'effect_agent.model_restarted', + value: { turn: value.turn, reason: value.reason }, + }), + CompactionCreated: (value) => + emit(projector, sequence, { + type: 'CUSTOM', + name: 'effect_agent.compaction_performed', + value: { turn: value.turn, kind: value.kind }, + }), + SubagentRequested: (value) => onSubagentRequested(projector, value.toolCallId, value.targetAgentId), + SubagentStarted: (value) => + onSubagentStarted(projector, sequence, value.runId, value.toolCallId, value.childRunId), + SubagentJoined: (value) => + onSubagentJoined(projector, sequence, value.runId, value.toolCallId, value.childOutcome), + RunCompleted: (value) => onRunCompleted(projector, threadId, sequence, value.runId, value.output), + RunFailed: (value) => onRunFailed(projector, sequence, value.runId, value.failure), + SubmissionSettled: (value) => + onSubmissionSettled(projector, threadId, sequence, value.outcome, value.runId, value.result), + }), + Match.orElse(() => undefined), + ) +} + +type DraftPart = ProvisionalText.TextEvent['part'] + +const isTextStart = (part: DraftPart): part is Response.TextStartPart => part.type === 'text-start' +const isTextDelta = (part: DraftPart): part is Response.TextDeltaPart => part.type === 'text-delta' +const isTextEnd = (part: DraftPart): part is Response.TextEndPart => part.type === 'text-end' +const isReasoningStart = (part: DraftPart): part is Response.ReasoningStartPart => part.type === 'reasoning-start' +const isReasoningDelta = (part: DraftPart): part is Response.ReasoningDeltaPart => part.type === 'reasoning-delta' +const isReasoningEnd = (part: DraftPart): part is Response.ReasoningEndPart => part.type === 'reasoning-end' + +const draftKey = (value: DraftIdentity): string => + `${value.runId}|${value.turnId}|${value.attemptId}|${value.generation}` + +const draftFor = (drafts: Map, key: string): DraftState => { + const existing = drafts.get(key) + + if (existing !== undefined) return existing + const created: DraftState = { textId: undefined, reasoningId: undefined } + drafts.set(key, created) + return created +} + +const closeDraftText = (projector: Projector, draft: DraftState): void => { + if (draft.textId === undefined) return + emit(projector, projector.tail, { type: 'TEXT_MESSAGE_END', messageId: draft.textId }) + draft.textId = undefined +} + +const closeDraftReasoning = (projector: Projector, draft: DraftState): void => { + if (draft.reasoningId === undefined) return + emit( + projector, + projector.tail, + { type: 'REASONING_MESSAGE_END', messageId: draft.reasoningId }, + { type: 'REASONING_END', messageId: draft.reasoningId }, + ) + draft.reasoningId = undefined +} + +const closeDraft = (projector: Projector, draft: DraftState): void => { + closeDraftText(projector, draft) + closeDraftReasoning(projector, draft) +} + +const closeWhere = ( + projector: Projector, + drafts: Map, + predicate: (key: string) => boolean, +): void => { + drafts.forEach((draft, key) => { + if (predicate(key)) closeDraft(projector, draft) + }) +} + +const isSuperseded = (projector: Projector, event: ProvisionalText.TextEvent): boolean => + projector.committedTurnIds.has(event.turnId) || projector.terminatedRuns.has(event.runId) + +const appendDraftPart = (projector: Projector, event: ProvisionalText.TextEvent, draft: DraftState): void => { + const prefix = `${event.runId}:${event.turnId}:${event.generation}` + Match.value(event.part).pipe( + Match.when(isTextStart, () => { + closeDraft(projector, draft) + const messageId = `${prefix}:text` + draft.textId = messageId + emit(projector, projector.tail, { type: 'TEXT_MESSAGE_START', messageId, role: 'assistant' }) + }), + Match.when(isTextDelta, (value) => { + const messageId = draft.textId ?? `${prefix}:text` + draft.textId = messageId + emit(projector, projector.tail, { type: 'TEXT_MESSAGE_CONTENT', messageId, delta: value.delta }) + }), + Match.when(isTextEnd, () => closeDraftText(projector, draft)), + Match.when(isReasoningStart, () => { + closeDraft(projector, draft) + const messageId = `${prefix}:reasoning` + draft.reasoningId = messageId + emit( + projector, + projector.tail, + { type: 'REASONING_START', messageId }, + { type: 'REASONING_MESSAGE_START', messageId, role: 'reasoning' }, + ) + }), + Match.when(isReasoningDelta, (value) => { + const messageId = draft.reasoningId ?? `${prefix}:reasoning` + draft.reasoningId = messageId + emit(projector, projector.tail, { type: 'REASONING_MESSAGE_CONTENT', messageId, delta: value.delta }) + }), + Match.when(isReasoningEnd, () => closeDraftReasoning(projector, draft)), + Match.orElse(() => undefined), + ) +} + +const onDraftText = ( + projector: Projector, + event: ProvisionalText.TextEvent, + drafts: Map, +): void => { + if (isSuperseded(projector, event)) return + appendDraftPart(projector, event, draftFor(drafts, draftKey(event))) +} + +const onDraftEvent = ( + projector: Projector, + event: ProvisionalText.Event, + drafts: Map, +): void => { + Match.value(event).pipe( + Match.tags({ + Text: (value) => onDraftText(projector, value, drafts), + Discard: (value) => closeWhere(projector, drafts, (key) => key === draftKey(value)), + AttemptEnded: (value) => closeWhere(projector, drafts, (key) => key.includes(`|${value.attemptId}|`)), + }), + Match.orElse(() => undefined), + ) +} + +const processText = (projector: Projector, text: ReadonlyArray): void => { + const drafts = new Map() + text.forEach((event) => onDraftEvent(projector, event, drafts)) +} + +const sortRecords = ( + records: ReadonlyArray, +): ReadonlyArray => [...records].sort((left, right) => left.sequence - right.sequence) + +const projectOf = ( + input: DurableAgUiInput, + options: DurableAgUiOptions | undefined, +): ReadonlyArray => { + const projector = makeProjector(options) + sortRecords(input.records).forEach((envelope) => processRecord(projector, envelope)) + if (input.text !== undefined) processText(projector, input.text) + return projector.items +} + +const isInput = ( + value: DurableAgUiInput | DurableAgUiOptions | undefined, +): value is DurableAgUiInput => value !== undefined && 'records' in value + +const streamOf = ( + records: Stream.Stream, + options: DurableAgUiOptions | undefined, +): Stream.Stream => + records.pipe( + Stream.mapAccumEffect( + () => makeProjector(options), + (projector, envelope) => + Effect.sync((): readonly [Projector, ReadonlyArray] => { + const start = projector.items.length + processRecord(projector, envelope) + return [projector, projector.items.slice(start)] + }), + ), + ) + +export function projectDurableAgUi( + input: DurableAgUiInput, + options?: DurableAgUiOptions, +): ReadonlyArray +export function projectDurableAgUi( + options?: DurableAgUiOptions, +): (input: DurableAgUiInput) => ReadonlyArray +export function projectDurableAgUi( + first?: DurableAgUiInput | DurableAgUiOptions, + options?: DurableAgUiOptions, +): + | ReadonlyArray + | ((input: DurableAgUiInput) => ReadonlyArray) +{ + return isInput(first) ? projectOf(first, options) : (input: DurableAgUiInput) => projectOf(input, first) +} + +export function toDurableAgUiEvents( + records: Stream.Stream, + options?: DurableAgUiOptions, +): Stream.Stream +export function toDurableAgUiEvents( + options?: DurableAgUiOptions, +): (records: Stream.Stream) => Stream.Stream +export function toDurableAgUiEvents( + first?: Stream.Stream | DurableAgUiOptions, + options?: DurableAgUiOptions, +): + | Stream.Stream + | ((records: Stream.Stream) => Stream.Stream) +{ + return Stream.isStream(first) ? streamOf(first, options) : (records) => streamOf(records, first) +} diff --git a/packages/effect-agent/src/index.ts b/packages/effect-agent/src/index.ts index f470da39..280e52df 100644 --- a/packages/effect-agent/src/index.ts +++ b/packages/effect-agent/src/index.ts @@ -1,3 +1,4 @@ +export * as AgUi from './AgUi' export * as BrowserUse from './capabilities/BrowserUse' export * as Budget from './capabilities/Budget' export * as CodeMode from './capabilities/CodeMode' @@ -79,7 +80,6 @@ export * as WakeScheduler from './durable/WakeScheduler' export * as WorkerAdmission from './durable/WorkerAdmission' export * as WorkerHost from './durable/WorkerHost' export * as AgentRuntime from './engine/AgentRuntime' -export * as AgUi from './engine/AgUi' export * as Compaction from './engine/Compaction' export * as ContextCompactor from './engine/ContextCompactor' export * as ContextHistory from './engine/ContextHistory' From 12fc1243fc7a085232777e604d5e132d7a20a015 Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot <318394648+systemfsoftware-bot@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:20:52 -0500 Subject: [PATCH 2/5] fix(agui): fold full history for cursor state and keep ./agui bundle neutral Address review findings on the durable projector: fold every supplied record so a cursor replay rebuilds steering, subagent and committed-turn state and emits only sequences after `afterSequence`; dedupe repeated envelopes in the streaming fold; unify committed and draft message ids per Run/Turn so a live render and a reload agree; emit tool calls for provider-executed tools and `TOOL_CALL_RESULT` for inline tool results; map failed and interrupted subagents to `SUBAGENT_ERROR`/suspended rather than success; open a draft message before emitting content; emit `RUN_STARTED` before a terminal when a projection starts mid-Run; and make the projector's `Records` imports type-only so `./agui` no longer pulls durable record schemas into browser bundles. --- .../effect-agent/src/durable/DurableAgUi.ts | 428 +++++++++++------- 1 file changed, 258 insertions(+), 170 deletions(-) diff --git a/packages/effect-agent/src/durable/DurableAgUi.ts b/packages/effect-agent/src/durable/DurableAgUi.ts index 789a800c..9a1aa679 100644 --- a/packages/effect-agent/src/durable/DurableAgUi.ts +++ b/packages/effect-agent/src/durable/DurableAgUi.ts @@ -10,15 +10,10 @@ import * as Stream from 'effect/Stream' import type { RunId, ThreadId } from '../core/Identifiers' import type * as ProvisionalText from '../core/ProvisionalText' -import { - type CanonicalRecordEnvelope, - CanonicalSequence, - SettlementFailureDiagnostic, - type SettlementOutcome, -} from './Records' +import type { CanonicalRecordEnvelope, SettlementFailureDiagnostic, SettlementOutcome } from './Records' export interface DurableAgUiEvent { - readonly sequence: CanonicalSequence + readonly sequence: number readonly event: AgUiSchema.Event } @@ -32,11 +27,19 @@ export interface DurableAgUiOptions { readonly output?: DurableAgUiOutput | undefined } +export interface DurableAgUiStreamOptions { + readonly includeSubagents?: boolean | undefined +} + export interface DurableAgUiInput { readonly records: ReadonlyArray readonly text?: ReadonlyArray | undefined + /** Emit only events derived from records after this sequence; the log below it is still folded for state. */ + readonly afterSequence?: number | undefined } +type ProjectionOutput = Schema.Json | SettlementFailureDiagnostic | undefined + interface RunState { started: boolean terminated: boolean @@ -69,11 +72,9 @@ interface Projector { readonly terminatedRuns: Set readonly subagentNames: Map readonly subagentChildRun: Map - tail: CanonicalSequence + tail: number } -type ProjectionOutput = Schema.Json | SettlementFailureDiagnostic | undefined - const idleRun = (): RunState => ({ started: false, terminated: false, @@ -88,6 +89,29 @@ const idleRun = (): RunState => ({ const encodeJson = (value: Schema.Json): string => Option.getOrElse(Schema.encodeOption(Schema.fromJsonString(Schema.Json))(value), () => 'null') +const jsonOf = (value: ProjectionOutput): Schema.Json => + Option.getOrElse(Schema.decodeUnknownOption(Schema.Json)(value), () => null) + +const isObjectLike = (value: Schema.Json): boolean => typeof value === 'object' && value !== null + +const isJsonObject = (value: Schema.Json): value is { readonly [key: string]: Schema.Json } => + isObjectLike(value) && !Array.isArray(value) + +const stringOrUndefined = (value: Schema.Json): string | undefined => typeof value === 'string' ? value : undefined + +const asString = (value: Schema.Json | undefined): string | undefined => + value === undefined ? undefined : stringOrUndefined(value) + +const failureMessage = (json: { readonly [key: string]: Schema.Json }): string => + asString(json['message']) ?? 'The run failed.' + +const failureFields = (value: ProjectionOutput): { readonly code: string | undefined; readonly message: string } => { + const json = jsonOf(value) + return isJsonObject(json) + ? { code: asString(json['errorTag']), message: failureMessage(json) } + : { code: undefined, message: 'The run failed.' } +} + const steeringEvent = ( phase: 'queued' | 'applied' | 'not-joined', inputId: string, @@ -98,6 +122,8 @@ const steeringEvent = ( value: { phase, inputId, ...(runId === undefined ? {} : { runId }) }, }) +const toolResultEvent = (sequence: number, event: AgUiSchema.Event): DurableAgUiEvent => ({ sequence, event }) + const withApproval = (pending: ReadonlyArray, toolCallId: string): ReadonlyArray => pending.includes(toolCallId) ? pending : [...pending, toolCallId] @@ -106,10 +132,10 @@ const withoutApproval = (pending: ReadonlyArray, toolCallId: string): Re const emit = ( projector: Projector, - sequence: CanonicalSequence, + sequence: number, ...events: ReadonlyArray ): void => { - for (const event of events) projector.items.push({ sequence, event }) + for (const event of events) projector.items.push(toolResultEvent(sequence, event)) } const runOf = (projector: Projector, runId: RunId): RunState => { @@ -121,13 +147,30 @@ const runOf = (projector: Projector, runId: RunId): RunState => { return created } -const closeText = (projector: Projector, run: RunState, sequence: CanonicalSequence): void => { +const markStarted = ( + projector: Projector, + threadId: ThreadId, + sequence: number, + runId: RunId, + run: RunState, +): void => { + if (run.started) return + run.started = true + emit(projector, sequence, { + type: 'RUN_STARTED', + threadId, + runId, + protocolVersion: AgUiSchema.protocolVersion, + }) +} + +const closeText = (projector: Projector, run: RunState, sequence: number): void => { if (run.textMessageId === undefined) return emit(projector, sequence, { type: 'TEXT_MESSAGE_END', messageId: run.textMessageId }) run.textMessageId = undefined } -const closeReasoning = (projector: Projector, run: RunState, sequence: CanonicalSequence): void => { +const closeReasoning = (projector: Projector, run: RunState, sequence: number): void => { if (run.reasoningMessageId === undefined) return emit( projector, @@ -138,18 +181,18 @@ const closeReasoning = (projector: Projector, run: RunState, sequence: Canonical run.reasoningMessageId = undefined } -const closeContent = (projector: Projector, run: RunState, sequence: CanonicalSequence): void => { +const closeContent = (projector: Projector, run: RunState, sequence: number): void => { closeText(projector, run, sequence) closeReasoning(projector, run, sequence) } -const closeStep = (projector: Projector, run: RunState, sequence: CanonicalSequence): void => { +const closeStep = (projector: Projector, run: RunState, sequence: number): void => { if (run.stepName === undefined) return emit(projector, sequence, { type: 'STEP_FINISHED', stepName: run.stepName }) run.stepName = undefined } -const closeOpen = (projector: Projector, run: RunState, sequence: CanonicalSequence): void => { +const closeOpen = (projector: Projector, run: RunState, sequence: number): void => { closeContent(projector, run, sequence) closeStep(projector, run, sequence) } @@ -158,59 +201,51 @@ const appendText = ( projector: Projector, run: RunState, runId: RunId, - sequence: CanonicalSequence, + turnId: string, + sequence: number, text: string, ): void => { closeReasoning(projector, run, sequence) - if (run.textMessageId !== undefined) { - emit(projector, sequence, { type: 'TEXT_MESSAGE_CONTENT', messageId: run.textMessageId, delta: text }) - return + if (run.textMessageId === undefined) { + const messageId = `${runId}:${turnId}:text` + run.textMessageId = messageId + emit(projector, sequence, { type: 'TEXT_MESSAGE_START', messageId, role: 'assistant' }) } - - const messageId = `${runId}:${sequence}:text` - run.textMessageId = messageId - emit( - projector, - sequence, - { type: 'TEXT_MESSAGE_START', messageId, role: 'assistant' }, - { type: 'TEXT_MESSAGE_CONTENT', messageId, delta: text }, - ) + emit(projector, sequence, { type: 'TEXT_MESSAGE_CONTENT', messageId: run.textMessageId, delta: text }) } const appendReasoning = ( projector: Projector, run: RunState, runId: RunId, - sequence: CanonicalSequence, + turnId: string, + sequence: number, text: string, ): void => { closeText(projector, run, sequence) - if (run.reasoningMessageId !== undefined) { - emit(projector, sequence, { - type: 'REASONING_MESSAGE_CONTENT', - messageId: run.reasoningMessageId, - delta: text, - }) - return + if (run.reasoningMessageId === undefined) { + const messageId = `${runId}:${turnId}:reasoning` + run.reasoningMessageId = messageId + emit( + projector, + sequence, + { type: 'REASONING_START', messageId }, + { type: 'REASONING_MESSAGE_START', messageId, role: 'reasoning' }, + ) } - - const messageId = `${runId}:${sequence}:reasoning` - run.reasoningMessageId = messageId - emit( - projector, - sequence, - { type: 'REASONING_START', messageId }, - { type: 'REASONING_MESSAGE_START', messageId, role: 'reasoning' }, - { type: 'REASONING_MESSAGE_CONTENT', messageId, delta: text }, - ) + emit(projector, sequence, { + type: 'REASONING_MESSAGE_CONTENT', + messageId: run.reasoningMessageId, + delta: text, + }) } const declareToolCall = ( projector: Projector, run: RunState, - sequence: CanonicalSequence, + sequence: number, toolCallId: string, toolName: string, parameters: Schema.Json, @@ -231,26 +266,46 @@ const declareToolCall = ( ) } +const emitToolResult = ( + projector: Projector, + sequence: number, + runId: RunId, + toolCallId: string, + isFailure: boolean, + result: Schema.Json, +): void => { + emit(projector, sequence, { + type: 'TOOL_CALL_RESULT', + messageId: `${runId}:${toolCallId}:${isFailure ? 'error' : 'result'}`, + toolCallId, + content: encodeJson(result), + role: 'tool', + }) +} + const isTextPart = (part: Prompt.AssistantMessagePartEncoded): part is Response.TextPartEncoded => part.type === 'text' const isReasoningPart = (part: Prompt.AssistantMessagePartEncoded): part is Response.ReasoningPartEncoded => part.type === 'reasoning' -const isLocalToolCallPart = ( - part: Prompt.AssistantMessagePartEncoded, -): part is Response.ToolCallPartEncoded => part.type === 'tool-call' && part.providerExecuted !== true +const isToolCallPart = (part: Prompt.AssistantMessagePartEncoded): part is Response.ToolCallPartEncoded => + part.type === 'tool-call' + +const isToolResultPart = (part: Prompt.AssistantMessagePartEncoded): part is Response.ToolResultPartEncoded => + part.type === 'tool-result' const appendPart = ( projector: Projector, run: RunState, runId: RunId, - sequence: CanonicalSequence, + turnId: string, + sequence: number, part: Prompt.AssistantMessagePartEncoded, ): void => { Match.value(part).pipe( - Match.when(isTextPart, (value) => appendText(projector, run, runId, sequence, value.text)), - Match.when(isReasoningPart, (value) => appendReasoning(projector, run, runId, sequence, value.text)), - Match.when(isLocalToolCallPart, (value) => + Match.when(isTextPart, (value) => appendText(projector, run, runId, turnId, sequence, value.text)), + Match.when(isReasoningPart, (value) => appendReasoning(projector, run, runId, turnId, sequence, value.text)), + Match.when(isToolCallPart, (value) => declareToolCall( projector, run, @@ -259,6 +314,15 @@ const appendPart = ( value.name, Option.getOrElse(Schema.decodeUnknownOption(Schema.Json)(value.params), () => null), )), + Match.when(isToolResultPart, (value) => + emitToolResult( + projector, + sequence, + runId, + value.id, + value.isFailure, + Option.getOrElse(Schema.decodeUnknownOption(Schema.Json)(value.result), () => null), + )), Match.orElse(() => undefined), ) } @@ -267,23 +331,25 @@ const appendTextIfPresent = ( projector: Projector, run: RunState, runId: RunId, - sequence: CanonicalSequence, + turnId: string, + sequence: number, text: string, ): void => { - if (text.length > 0) appendText(projector, run, runId, sequence, text) + if (text.length > 0) appendText(projector, run, runId, turnId, sequence, text) } const appendAssistantContent = ( projector: Projector, run: RunState, runId: RunId, - sequence: CanonicalSequence, + turnId: string, + sequence: number, content: string | ReadonlyArray, ): void => { if (typeof content === 'string') { - appendTextIfPresent(projector, run, runId, sequence, content) + appendTextIfPresent(projector, run, runId, turnId, sequence, content) } else { - content.forEach((part) => appendPart(projector, run, runId, sequence, part)) + content.forEach((part) => appendPart(projector, run, runId, turnId, sequence, part)) } } @@ -291,11 +357,12 @@ const appendMessage = ( projector: Projector, run: RunState, runId: RunId, - sequence: CanonicalSequence, + turnId: string, + sequence: number, message: Prompt.MessageEncoded, ): void => { if (message.role === 'assistant') { - appendAssistantContent(projector, run, runId, sequence, message.content) + appendAssistantContent(projector, run, runId, turnId, sequence, message.content) } } @@ -303,55 +370,40 @@ const appendResponse = ( projector: Projector, run: RunState, runId: RunId, - sequence: CanonicalSequence, + turnId: string, + sequence: number, messages: Prompt.PromptEncoded, ): void => { - messages.content.forEach((message) => appendMessage(projector, run, runId, sequence, message)) + messages.content.forEach((message) => appendMessage(projector, run, runId, turnId, sequence, message)) } -const applySteering = (projector: Projector, sequence: CanonicalSequence, run: RunState, runId: RunId): void => { +const applySteering = (projector: Projector, sequence: number, run: RunState, runId: RunId): void => { for (const inputId of run.steeringPending) emit(projector, sequence, steeringEvent('applied', inputId, runId)) run.steeringPending = [] } -const closeEachSubagent = (projector: Projector, run: RunState, sequence: CanonicalSequence): void => { +const closeEachSubagent = (projector: Projector, run: RunState, sequence: number): void => { for (const subagentRunId of run.openSubagents) { - emit(projector, sequence, { - type: 'SUBAGENT_ERROR', - subagentRunId, - message: 'The subagent did not finish.', - }) + emit(projector, sequence, { type: 'SUBAGENT_ERROR', subagentRunId, message: 'The subagent did not finish.' }) } run.openSubagents = [] } -const closeSubagents = (projector: Projector, run: RunState, sequence: CanonicalSequence): void => { +const closeSubagents = (projector: Projector, run: RunState, sequence: number): void => { if (projector.includeSubagents) closeEachSubagent(projector, run, sequence) } -const closeTerminal = (projector: Projector, run: RunState, sequence: CanonicalSequence): void => { +const closeTerminal = (projector: Projector, run: RunState, sequence: number): void => { closeOpen(projector, run, sequence) closeSubagents(projector, run, sequence) run.pendingApprovals = [] } -const drainUnappliedSteering = ( - projector: Projector, - run: RunState, - sequence: CanonicalSequence, - runId: RunId, -): void => { +const drainUnappliedSteering = (projector: Projector, run: RunState, sequence: number, runId: RunId): void => { for (const inputId of run.steeringPending) emit(projector, sequence, steeringEvent('not-joined', inputId, runId)) run.steeringPending = [] } -const failureFields = (value: ProjectionOutput): { readonly code: string | undefined; readonly message: string } => { - const decoded = Schema.decodeUnknownOption(SettlementFailureDiagnostic)(value) - return Option.isSome(decoded) - ? { code: decoded.value.errorTag, message: decoded.value.message } - : { code: undefined, message: 'The run failed.' } -} - const decodeOutput = ( extension: DurableAgUiOutput, output: ProjectionOutput, @@ -381,101 +433,120 @@ const makeProjector = (options: DurableAgUiOptions | undefined): terminatedRuns: new Set(), subagentNames: new Map(), subagentChildRun: new Map(), - tail: CanonicalSequence.make(0), + tail: 0, }) +const subagentKey = (runId: RunId, toolCallId: string): string => `${runId}|${toolCallId}` + +const subagentEvent = (childRunId: string, outcome: SettlementOutcome): AgUiSchema.Event => + outcome === 'completed' ? subagentFinished(childRunId) : subagentNotCompleted(childRunId, outcome) + +const subagentFinished = (childRunId: string): AgUiSchema.Event => ({ + type: 'SUBAGENT_FINISHED', + subagentRunId: childRunId, + outcome: { type: 'success' }, +}) + +const subagentNotCompleted = (childRunId: string, outcome: SettlementOutcome): AgUiSchema.Event => + outcome === 'failed' + ? { type: 'SUBAGENT_ERROR', subagentRunId: childRunId, message: 'The subagent failed.' } + : { type: 'SUBAGENT_FINISHED', subagentRunId: childRunId, outcome: { type: 'suspended' } } + const onRunStarted = ( projector: Projector, threadId: ThreadId, - sequence: CanonicalSequence, + sequence: number, + runId: RunId, +): void => { + markStarted(projector, threadId, sequence, runId, runOf(projector, runId)) +} + +const queueForRun = ( + projector: Projector, + sequence: number, + inputId: string, runId: RunId, ): void => { const run = runOf(projector, runId) - if (run.started) return - run.started = true - emit(projector, sequence, { - type: 'RUN_STARTED', - threadId, - runId, - protocolVersion: AgUiSchema.protocolVersion, - }) + if (run.terminated) { + emit(projector, sequence, steeringEvent('not-joined', inputId, runId)) + return + } + run.steeringPending.push(inputId) + emit(projector, sequence, steeringEvent('queued', inputId, runId)) } -const queueSteering = ( +const steerWithRun = ( projector: Projector, - sequence: CanonicalSequence, + sequence: number, inputId: string, runId: RunId | undefined, ): void => { - if (runId !== undefined) runOf(projector, runId).steeringPending.push(inputId) - emit(projector, sequence, steeringEvent('queued', inputId, runId)) + if (runId !== undefined) queueForRun(projector, sequence, inputId, runId) } -const handleSteering = ( +const onSteering = ( projector: Projector, - sequence: CanonicalSequence, + sequence: number, submissionId: string | undefined, runId: RunId | undefined, ): void => { - if (submissionId !== undefined) queueSteering(projector, sequence, submissionId, runId) + if (submissionId !== undefined) steerWithRun(projector, sequence, submissionId, runId) } const onUserInput = ( projector: Projector, - sequence: CanonicalSequence, + sequence: number, kind: 'user' | 'steering' | 'follow-up', submissionId: string | undefined, runId: RunId | undefined, ): void => { - if (kind === 'steering') handleSteering(projector, sequence, submissionId, runId) + if (kind === 'steering') onSteering(projector, sequence, submissionId, runId) } const onModelResponse = ( projector: Projector, - sequence: CanonicalSequence, + sequence: number, runId: RunId, turnId: string, turn: number, messages: Prompt.PromptEncoded, ): void => { const run = runOf(projector, runId) + if (run.terminated) return projector.committedTurnIds.add(turnId) applySteering(projector, sequence, run, runId) closeOpen(projector, run, sequence) const stepName = `turn-${turn}` run.stepName = stepName emit(projector, sequence, { type: 'STEP_STARTED', stepName }) - appendResponse(projector, run, runId, sequence, messages) + appendResponse(projector, run, runId, turnId, sequence, messages) closeOpen(projector, run, sequence) } const onToolCallSettled = ( projector: Projector, - sequence: CanonicalSequence, + sequence: number, runId: RunId, toolCallId: string, result: Schema.Json, isFailure: boolean, ): void => { const run = runOf(projector, runId) + if (run.terminated) return run.pendingApprovals = [...withoutApproval(run.pendingApprovals, toolCallId)] - emit(projector, sequence, { - type: 'TOOL_CALL_RESULT', - messageId: `${runId}:${toolCallId}:${isFailure ? 'error' : 'result'}`, - toolCallId, - content: encodeJson(result), - role: 'tool', - }) + emitToolResult(projector, sequence, runId, toolCallId, isFailure, result) } const onApprovalRequested = ( projector: Projector, - sequence: CanonicalSequence, + sequence: number, runId: RunId, toolCallId: string, toolName: string, ): void => { const run = runOf(projector, runId) + if (run.terminated) return run.pendingApprovals = [...withApproval(run.pendingApprovals, toolCallId)] emit(projector, sequence, { type: 'CUSTOM', @@ -486,7 +557,7 @@ const onApprovalRequested = ( const onApprovalDecided = ( projector: Projector, - sequence: CanonicalSequence, + sequence: number, runId: RunId, toolCallId: string, decision: string, @@ -500,53 +571,53 @@ const onApprovalDecided = ( }) } -const nameOrChild = (name: string | undefined, childRunId: string): string => name ?? childRunId - -const subagentFinished = (childRunId: string, completed: boolean): AgUiSchema.Event => - completed - ? { type: 'SUBAGENT_FINISHED', subagentRunId: childRunId, outcome: { type: 'success' } } - : { type: 'SUBAGENT_FINISHED', subagentRunId: childRunId } - -const onSubagentRequested = (projector: Projector, toolCallId: string, targetAgentId: string): void => { - projector.subagentNames.set(toolCallId, targetAgentId) +const onSubagentRequested = ( + projector: Projector, + runId: RunId, + toolCallId: string, + targetAgentId: string, +): void => { + projector.subagentNames.set(subagentKey(runId, toolCallId), targetAgentId) } +const nameOrChild = (name: string | undefined, childRunId: string): string => name ?? childRunId + const onSubagentStarted = ( projector: Projector, - sequence: CanonicalSequence, + sequence: number, runId: RunId, toolCallId: string, childRunId: string, ): void => { - projector.subagentChildRun.set(toolCallId, childRunId) + projector.subagentChildRun.set(subagentKey(runId, toolCallId), childRunId) if (!projector.includeSubagents) return const run = runOf(projector, runId) run.openSubagents.push(childRunId) emit(projector, sequence, { type: 'SUBAGENT_STARTED', subagentRunId: childRunId, - name: nameOrChild(projector.subagentNames.get(toolCallId), childRunId), + name: nameOrChild(projector.subagentNames.get(subagentKey(runId, toolCallId)), childRunId), parentToolCallId: toolCallId, }) } const joinSubagent = ( projector: Projector, - sequence: CanonicalSequence, + sequence: number, runId: RunId, toolCallId: string, childOutcome: SettlementOutcome, ): void => { - const childRunId = projector.subagentChildRun.get(toolCallId) + const childRunId = projector.subagentChildRun.get(subagentKey(runId, toolCallId)) if (childRunId === undefined) return const run = runOf(projector, runId) run.openSubagents = run.openSubagents.filter((value) => value !== childRunId) - emit(projector, sequence, subagentFinished(childRunId, childOutcome === 'completed')) + emit(projector, sequence, subagentEvent(childRunId, childOutcome)) } const onSubagentJoined = ( projector: Projector, - sequence: CanonicalSequence, + sequence: number, runId: RunId, toolCallId: string, childOutcome: SettlementOutcome, @@ -563,7 +634,7 @@ const codeField = (code: string | undefined): { readonly code?: string } => code const settleCompleted = ( projector: Projector, threadId: ThreadId, - sequence: CanonicalSequence, + sequence: number, runId: RunId, result: ProjectionOutput, ): void => { @@ -577,7 +648,7 @@ const settleCompleted = ( }) } -const settleFailed = (projector: Projector, sequence: CanonicalSequence, result: ProjectionOutput): void => { +const settleFailed = (projector: Projector, sequence: number, result: ProjectionOutput): void => { const failure = failureFields(result) emit(projector, sequence, { type: 'RUN_ERROR', @@ -589,7 +660,7 @@ const settleFailed = (projector: Projector, sequence: CanonicalSequence, result: const settleStopped = ( projector: Projector, threadId: ThreadId, - sequence: CanonicalSequence, + sequence: number, runId: RunId, ): void => { emit(projector, sequence, { type: 'RUN_FINISHED', threadId, runId, outcome: { type: 'cancelled' } }) @@ -598,12 +669,13 @@ const settleStopped = ( const settleRun = ( projector: Projector, threadId: ThreadId, - sequence: CanonicalSequence, + sequence: number, runId: RunId, outcome: SettlementOutcome, result: ProjectionOutput, ): void => { const run = runOf(projector, runId) + markStarted(projector, threadId, sequence, runId, run) closeTerminal(projector, run, sequence) drainUnappliedSteering(projector, run, sequence, runId) Match.value(outcome).pipe( @@ -618,7 +690,7 @@ const settleRun = ( const settleIfLive = ( projector: Projector, threadId: ThreadId, - sequence: CanonicalSequence, + sequence: number, runId: RunId, outcome: SettlementOutcome, result: ProjectionOutput, @@ -630,7 +702,7 @@ const settleIfLive = ( const onSubmissionSettled = ( projector: Projector, threadId: ThreadId, - sequence: CanonicalSequence, + sequence: number, outcome: SettlementOutcome, runId: RunId | undefined, result: ProjectionOutput, @@ -641,15 +713,16 @@ const onSubmissionSettled = ( const onRunCompleted = ( projector: Projector, threadId: ThreadId, - sequence: CanonicalSequence, + sequence: number, runId: RunId, output: Schema.Json, ): void => { if (projector.terminatedRuns.has(runId)) return const run = runOf(projector, runId) + markStarted(projector, threadId, sequence, runId, run) closeTerminal(projector, run, sequence) - emit(projector, sequence, ...projector.projectOutput(output)) drainUnappliedSteering(projector, run, sequence, runId) + emit(projector, sequence, ...projector.projectOutput(output)) emit(projector, sequence, { type: 'RUN_FINISHED', threadId, @@ -663,12 +736,14 @@ const onRunCompleted = ( const onRunFailed = ( projector: Projector, - sequence: CanonicalSequence, + threadId: ThreadId, + sequence: number, runId: RunId, failure: Schema.Json, ): void => { if (projector.terminatedRuns.has(runId)) return const run = runOf(projector, runId) + markStarted(projector, threadId, sequence, runId, run) closeTerminal(projector, run, sequence) drainUnappliedSteering(projector, run, sequence, runId) const fields = failureFields(failure) @@ -682,6 +757,7 @@ const onRunFailed = ( } const processRecord = (projector: Projector, envelope: CanonicalRecordEnvelope): void => { + if (envelope.sequence <= projector.tail) return const payload = envelope.record.payload projector.tail = envelope.sequence const sequence = envelope.sequence @@ -711,13 +787,13 @@ const processRecord = (projector: Projector, envelope: CanonicalRecordEnvelope): name: 'effect_agent.compaction_performed', value: { turn: value.turn, kind: value.kind }, }), - SubagentRequested: (value) => onSubagentRequested(projector, value.toolCallId, value.targetAgentId), + SubagentRequested: (value) => onSubagentRequested(projector, value.runId, value.toolCallId, value.targetAgentId), SubagentStarted: (value) => onSubagentStarted(projector, sequence, value.runId, value.toolCallId, value.childRunId), SubagentJoined: (value) => onSubagentJoined(projector, sequence, value.runId, value.toolCallId, value.childOutcome), RunCompleted: (value) => onRunCompleted(projector, threadId, sequence, value.runId, value.output), - RunFailed: (value) => onRunFailed(projector, sequence, value.runId, value.failure), + RunFailed: (value) => onRunFailed(projector, threadId, sequence, value.runId, value.failure), SubmissionSettled: (value) => onSubmissionSettled(projector, threadId, sequence, value.outcome, value.runId, value.result), }), @@ -781,36 +857,43 @@ const closeWhere = ( const isSuperseded = (projector: Projector, event: ProvisionalText.TextEvent): boolean => projector.committedTurnIds.has(event.turnId) || projector.terminatedRuns.has(event.runId) +const ensureDraftText = (projector: Projector, draft: DraftState, messageId: string): void => { + if (draft.textId !== undefined) return + draft.textId = messageId + emit(projector, projector.tail, { type: 'TEXT_MESSAGE_START', messageId, role: 'assistant' }) +} + +const ensureDraftReasoning = (projector: Projector, draft: DraftState, messageId: string): void => { + if (draft.reasoningId !== undefined) return + draft.reasoningId = messageId + emit( + projector, + projector.tail, + { type: 'REASONING_START', messageId }, + { type: 'REASONING_MESSAGE_START', messageId, role: 'reasoning' }, + ) +} + const appendDraftPart = (projector: Projector, event: ProvisionalText.TextEvent, draft: DraftState): void => { - const prefix = `${event.runId}:${event.turnId}:${event.generation}` + const textId = `${event.runId}:${event.turnId}:text` + const reasoningId = `${event.runId}:${event.turnId}:reasoning` Match.value(event.part).pipe( Match.when(isTextStart, () => { closeDraft(projector, draft) - const messageId = `${prefix}:text` - draft.textId = messageId - emit(projector, projector.tail, { type: 'TEXT_MESSAGE_START', messageId, role: 'assistant' }) + ensureDraftText(projector, draft, textId) }), Match.when(isTextDelta, (value) => { - const messageId = draft.textId ?? `${prefix}:text` - draft.textId = messageId - emit(projector, projector.tail, { type: 'TEXT_MESSAGE_CONTENT', messageId, delta: value.delta }) + ensureDraftText(projector, draft, textId) + emit(projector, projector.tail, { type: 'TEXT_MESSAGE_CONTENT', messageId: textId, delta: value.delta }) }), Match.when(isTextEnd, () => closeDraftText(projector, draft)), Match.when(isReasoningStart, () => { closeDraft(projector, draft) - const messageId = `${prefix}:reasoning` - draft.reasoningId = messageId - emit( - projector, - projector.tail, - { type: 'REASONING_START', messageId }, - { type: 'REASONING_MESSAGE_START', messageId, role: 'reasoning' }, - ) + ensureDraftReasoning(projector, draft, reasoningId) }), Match.when(isReasoningDelta, (value) => { - const messageId = draft.reasoningId ?? `${prefix}:reasoning` - draft.reasoningId = messageId - emit(projector, projector.tail, { type: 'REASONING_MESSAGE_CONTENT', messageId, delta: value.delta }) + ensureDraftReasoning(projector, draft, reasoningId) + emit(projector, projector.tail, { type: 'REASONING_MESSAGE_CONTENT', messageId: reasoningId, delta: value.delta }) }), Match.when(isReasoningEnd, () => closeDraftReasoning(projector, draft)), Match.orElse(() => undefined), @@ -850,6 +933,11 @@ const sortRecords = ( records: ReadonlyArray, ): ReadonlyArray => [...records].sort((left, right) => left.sequence - right.sequence) +const restrictFrom = ( + items: ReadonlyArray, + from: number | undefined, +): ReadonlyArray => from === undefined ? items : items.filter((item) => item.sequence > from) + const projectOf = ( input: DurableAgUiInput, options: DurableAgUiOptions | undefined, @@ -857,7 +945,7 @@ const projectOf = ( const projector = makeProjector(options) sortRecords(input.records).forEach((envelope) => processRecord(projector, envelope)) if (input.text !== undefined) processText(projector, input.text) - return projector.items + return restrictFrom(projector.items, input.afterSequence) } const isInput = ( @@ -866,7 +954,7 @@ const isInput = ( const streamOf = ( records: Stream.Stream, - options: DurableAgUiOptions | undefined, + options: DurableAgUiStreamOptions | undefined, ): Stream.Stream => records.pipe( Stream.mapAccumEffect( @@ -899,17 +987,17 @@ export function projectDurableAgUi( export function toDurableAgUiEvents( records: Stream.Stream, - options?: DurableAgUiOptions, + options?: DurableAgUiStreamOptions, ): Stream.Stream export function toDurableAgUiEvents( - options?: DurableAgUiOptions, + options?: DurableAgUiStreamOptions, ): (records: Stream.Stream) => Stream.Stream export function toDurableAgUiEvents( - first?: Stream.Stream | DurableAgUiOptions, - options?: DurableAgUiOptions, + first?: Stream.Stream | DurableAgUiStreamOptions, + options?: DurableAgUiStreamOptions, ): | Stream.Stream - | ((records: Stream.Stream) => Stream.Stream) + | ((records: Stream.Stream) => Stream.Stream) { return Stream.isStream(first) ? streamOf(first, options) : (records) => streamOf(records, first) } From 9ea4963c1545df3022c243fba9d5fe289476cb3f Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot <318394648+systemfsoftware-bot@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:23:08 -0500 Subject: [PATCH 3/5] refactor(agui): shape a failed tool result as {error, code} like the reference mapper --- packages/effect-agent/src/durable/DurableAgUi.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/effect-agent/src/durable/DurableAgUi.ts b/packages/effect-agent/src/durable/DurableAgUi.ts index 9a1aa679..99e4fc25 100644 --- a/packages/effect-agent/src/durable/DurableAgUi.ts +++ b/packages/effect-agent/src/durable/DurableAgUi.ts @@ -524,6 +524,14 @@ const onModelResponse = ( closeOpen(projector, run, sequence) } +const withCode = (fields: { readonly code: string | undefined; readonly message: string }): Schema.Json => + fields.code === undefined ? { error: fields.message } : { error: fields.message, code: fields.code } + +const failedToolContent = (result: Schema.Json): Schema.Json => withCode(failureFields(result)) + +const toolResultContent = (result: Schema.Json, isFailure: boolean): Schema.Json => + isFailure ? failedToolContent(result) : result + const onToolCallSettled = ( projector: Projector, sequence: number, @@ -535,7 +543,7 @@ const onToolCallSettled = ( const run = runOf(projector, runId) if (run.terminated) return run.pendingApprovals = [...withoutApproval(run.pendingApprovals, toolCallId)] - emitToolResult(projector, sequence, runId, toolCallId, isFailure, result) + emitToolResult(projector, sequence, runId, toolCallId, isFailure, toolResultContent(result, isFailure)) } const onApprovalRequested = ( From 8dfdca1e7d6c7306f33f06772ba67f9c03704af8 Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot <318394648+systemfsoftware-bot@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:32:45 -0500 Subject: [PATCH 4/5] fix(agui): keep live drafts live and start Runs before their events Round-2 review fixes: (1) provisional text events are no longer filtered by afterSequence, so a cursor at the last committed sequence still streams live drafts while record-derived events stay cursor-filtered; (2) every run-scoped record marks the Run started before emitting, so a projection that begins mid-Run emits RUN_STARTED ahead of STEP/TEXT/TOOL events; (3) approval-decided, subagent-started/joined, model-aborted and compaction handlers now honor run termination; (4) a draft delta closes the opposite modality so text and reasoning blocks cannot stay interleaved. The streaming form stays the record-only fold with a non-generic options type (the typed output extension remains on the pure projector): a generic stream options type is rejected by the repository's missing-pipeable-signature lint when the generic is not reflected in the returned function, and moving it outward would break pipe inference for errorful streams. --- .../effect-agent/src/durable/DurableAgUi.ts | 147 +++++++++++++----- 1 file changed, 104 insertions(+), 43 deletions(-) diff --git a/packages/effect-agent/src/durable/DurableAgUi.ts b/packages/effect-agent/src/durable/DurableAgUi.ts index 99e4fc25..20f80742 100644 --- a/packages/effect-agent/src/durable/DurableAgUi.ts +++ b/packages/effect-agent/src/durable/DurableAgUi.ts @@ -72,6 +72,7 @@ interface Projector { readonly terminatedRuns: Set readonly subagentNames: Map readonly subagentChildRun: Map + threadId: ThreadId | undefined tail: number } @@ -147,14 +148,14 @@ const runOf = (projector: Projector, runId: RunId): RunState => { return created } -const markStarted = ( +const markStartedWithThread = ( projector: Projector, - threadId: ThreadId, sequence: number, runId: RunId, run: RunState, ): void => { - if (run.started) return + const threadId = projector.threadId + if (threadId === undefined) return run.started = true emit(projector, sequence, { type: 'RUN_STARTED', @@ -164,6 +165,16 @@ const markStarted = ( }) } +const markStarted = (projector: Projector, sequence: number, runId: RunId, run: RunState): void => + run.started ? undefined : markStartedWithThread(projector, sequence, runId, run) + +const liveRun = (projector: Projector, sequence: number, runId: RunId): RunState | undefined => { + const run = runOf(projector, runId) + if (run.terminated) return undefined + markStarted(projector, sequence, runId, run) + return run +} + const closeText = (projector: Projector, run: RunState, sequence: number): void => { if (run.textMessageId === undefined) return emit(projector, sequence, { type: 'TEXT_MESSAGE_END', messageId: run.textMessageId }) @@ -433,6 +444,7 @@ const makeProjector = (options: DurableAgUiOptions | undefined): terminatedRuns: new Set(), subagentNames: new Map(), subagentChildRun: new Map(), + threadId: undefined, tail: 0, }) @@ -452,13 +464,8 @@ const subagentNotCompleted = (childRunId: string, outcome: SettlementOutcome): A ? { type: 'SUBAGENT_ERROR', subagentRunId: childRunId, message: 'The subagent failed.' } : { type: 'SUBAGENT_FINISHED', subagentRunId: childRunId, outcome: { type: 'suspended' } } -const onRunStarted = ( - projector: Projector, - threadId: ThreadId, - sequence: number, - runId: RunId, -): void => { - markStarted(projector, threadId, sequence, runId, runOf(projector, runId)) +const onRunStarted = (projector: Projector, sequence: number, runId: RunId): void => { + markStarted(projector, sequence, runId, runOf(projector, runId)) } const queueForRun = ( @@ -512,8 +519,8 @@ const onModelResponse = ( turn: number, messages: Prompt.PromptEncoded, ): void => { - const run = runOf(projector, runId) - if (run.terminated) return + const run = liveRun(projector, sequence, runId) + if (run === undefined) return projector.committedTurnIds.add(turnId) applySteering(projector, sequence, run, runId) closeOpen(projector, run, sequence) @@ -540,8 +547,8 @@ const onToolCallSettled = ( result: Schema.Json, isFailure: boolean, ): void => { - const run = runOf(projector, runId) - if (run.terminated) return + const run = liveRun(projector, sequence, runId) + if (run === undefined) return run.pendingApprovals = [...withoutApproval(run.pendingApprovals, toolCallId)] emitToolResult(projector, sequence, runId, toolCallId, isFailure, toolResultContent(result, isFailure)) } @@ -553,8 +560,8 @@ const onApprovalRequested = ( toolCallId: string, toolName: string, ): void => { - const run = runOf(projector, runId) - if (run.terminated) return + const run = liveRun(projector, sequence, runId) + if (run === undefined) return run.pendingApprovals = [...withApproval(run.pendingApprovals, toolCallId)] emit(projector, sequence, { type: 'CUSTOM', @@ -570,7 +577,8 @@ const onApprovalDecided = ( toolCallId: string, decision: string, ): void => { - const run = runOf(projector, runId) + const run = liveRun(projector, sequence, runId) + if (run === undefined) return run.pendingApprovals = [...withoutApproval(run.pendingApprovals, toolCallId)] emit(projector, sequence, { type: 'CUSTOM', @@ -590,16 +598,14 @@ const onSubagentRequested = ( const nameOrChild = (name: string | undefined, childRunId: string): string => name ?? childRunId -const onSubagentStarted = ( +const startSubagent = ( projector: Projector, sequence: number, + run: RunState, runId: RunId, toolCallId: string, childRunId: string, ): void => { - projector.subagentChildRun.set(subagentKey(runId, toolCallId), childRunId) - if (!projector.includeSubagents) return - const run = runOf(projector, runId) run.openSubagents.push(childRunId) emit(projector, sequence, { type: 'SUBAGENT_STARTED', @@ -609,20 +615,55 @@ const onSubagentStarted = ( }) } -const joinSubagent = ( +const recordSubagentStart = ( projector: Projector, sequence: number, + run: RunState, + runId: RunId, + toolCallId: string, + childRunId: string, +): void => { + projector.subagentChildRun.set(subagentKey(runId, toolCallId), childRunId) + if (projector.includeSubagents) startSubagent(projector, sequence, run, runId, toolCallId, childRunId) +} + +const onSubagentStarted = ( + projector: Projector, + sequence: number, + runId: RunId, + toolCallId: string, + childRunId: string, +): void => { + const run = liveRun(projector, sequence, runId) + if (run === undefined) return + recordSubagentStart(projector, sequence, run, runId, toolCallId, childRunId) +} + +const joinOpenSubagent = ( + projector: Projector, + sequence: number, + run: RunState, runId: RunId, toolCallId: string, childOutcome: SettlementOutcome, ): void => { const childRunId = projector.subagentChildRun.get(subagentKey(runId, toolCallId)) if (childRunId === undefined) return - const run = runOf(projector, runId) run.openSubagents = run.openSubagents.filter((value) => value !== childRunId) emit(projector, sequence, subagentEvent(childRunId, childOutcome)) } +const joinSubagent = ( + projector: Projector, + sequence: number, + run: RunState, + runId: RunId, + toolCallId: string, + childOutcome: SettlementOutcome, +): void => { + if (projector.includeSubagents) joinOpenSubagent(projector, sequence, run, runId, toolCallId, childOutcome) +} + const onSubagentJoined = ( projector: Projector, sequence: number, @@ -630,7 +671,9 @@ const onSubagentJoined = ( toolCallId: string, childOutcome: SettlementOutcome, ): void => { - if (projector.includeSubagents) joinSubagent(projector, sequence, runId, toolCallId, childOutcome) + const run = liveRun(projector, sequence, runId) + if (run === undefined) return + joinSubagent(projector, sequence, run, runId, toolCallId, childOutcome) } const resultField = ( @@ -683,7 +726,7 @@ const settleRun = ( result: ProjectionOutput, ): void => { const run = runOf(projector, runId) - markStarted(projector, threadId, sequence, runId, run) + markStarted(projector, sequence, runId, run) closeTerminal(projector, run, sequence) drainUnappliedSteering(projector, run, sequence, runId) Match.value(outcome).pipe( @@ -727,7 +770,7 @@ const onRunCompleted = ( ): void => { if (projector.terminatedRuns.has(runId)) return const run = runOf(projector, runId) - markStarted(projector, threadId, sequence, runId, run) + markStarted(projector, sequence, runId, run) closeTerminal(projector, run, sequence) drainUnappliedSteering(projector, run, sequence, runId) emit(projector, sequence, ...projector.projectOutput(output)) @@ -744,14 +787,13 @@ const onRunCompleted = ( const onRunFailed = ( projector: Projector, - threadId: ThreadId, sequence: number, runId: RunId, failure: Schema.Json, ): void => { if (projector.terminatedRuns.has(runId)) return const run = runOf(projector, runId) - markStarted(projector, threadId, sequence, runId, run) + markStarted(projector, sequence, runId, run) closeTerminal(projector, run, sequence) drainUnappliedSteering(projector, run, sequence, runId) const fields = failureFields(failure) @@ -764,16 +806,41 @@ const onRunFailed = ( run.terminated = true } +const onModelCallAborted = ( + projector: Projector, + sequence: number, + runId: RunId, + turn: number, + reason: string, +): void => { + const run = liveRun(projector, sequence, runId) + if (run === undefined) return + emit(projector, sequence, { type: 'CUSTOM', name: 'effect_agent.model_restarted', value: { turn, reason } }) +} + +const onCompactionCreated = ( + projector: Projector, + sequence: number, + runId: RunId, + turn: number, + kind: string, +): void => { + const run = liveRun(projector, sequence, runId) + if (run === undefined) return + emit(projector, sequence, { type: 'CUSTOM', name: 'effect_agent.compaction_performed', value: { turn, kind } }) +} + const processRecord = (projector: Projector, envelope: CanonicalRecordEnvelope): void => { if (envelope.sequence <= projector.tail) return const payload = envelope.record.payload projector.tail = envelope.sequence const sequence = envelope.sequence const threadId = envelope.threadId + projector.threadId = threadId Match.value(payload).pipe( Match.tags({ - RunStarted: (value) => onRunStarted(projector, threadId, sequence, value.runId), + RunStarted: (value) => onRunStarted(projector, sequence, value.runId), UserInputRecorded: (value) => onUserInput(projector, sequence, value.kind, value.submissionId, value.runId), ModelResponseRecorded: (value) => onModelResponse(projector, sequence, value.runId, value.turnId, value.turn, value.messages), @@ -783,25 +850,15 @@ const processRecord = (projector: Projector, envelope: CanonicalRecordEnvelope): onApprovalRequested(projector, sequence, value.runId, value.toolCallId, value.toolName), ToolApprovalDecided: (value) => onApprovalDecided(projector, sequence, value.runId, value.toolCallId, value.decision), - ModelCallAborted: (value) => - emit(projector, sequence, { - type: 'CUSTOM', - name: 'effect_agent.model_restarted', - value: { turn: value.turn, reason: value.reason }, - }), - CompactionCreated: (value) => - emit(projector, sequence, { - type: 'CUSTOM', - name: 'effect_agent.compaction_performed', - value: { turn: value.turn, kind: value.kind }, - }), + ModelCallAborted: (value) => onModelCallAborted(projector, sequence, value.runId, value.turn, value.reason), + CompactionCreated: (value) => onCompactionCreated(projector, sequence, value.runId, value.turn, value.kind), SubagentRequested: (value) => onSubagentRequested(projector, value.runId, value.toolCallId, value.targetAgentId), SubagentStarted: (value) => onSubagentStarted(projector, sequence, value.runId, value.toolCallId, value.childRunId), SubagentJoined: (value) => onSubagentJoined(projector, sequence, value.runId, value.toolCallId, value.childOutcome), RunCompleted: (value) => onRunCompleted(projector, threadId, sequence, value.runId, value.output), - RunFailed: (value) => onRunFailed(projector, threadId, sequence, value.runId, value.failure), + RunFailed: (value) => onRunFailed(projector, sequence, value.runId, value.failure), SubmissionSettled: (value) => onSubmissionSettled(projector, threadId, sequence, value.outcome, value.runId, value.result), }), @@ -891,6 +948,7 @@ const appendDraftPart = (projector: Projector, event: ProvisionalText.TextEvent, ensureDraftText(projector, draft, textId) }), Match.when(isTextDelta, (value) => { + closeDraftReasoning(projector, draft) ensureDraftText(projector, draft, textId) emit(projector, projector.tail, { type: 'TEXT_MESSAGE_CONTENT', messageId: textId, delta: value.delta }) }), @@ -900,6 +958,7 @@ const appendDraftPart = (projector: Projector, event: ProvisionalText.TextEvent, ensureDraftReasoning(projector, draft, reasoningId) }), Match.when(isReasoningDelta, (value) => { + closeDraftText(projector, draft) ensureDraftReasoning(projector, draft, reasoningId) emit(projector, projector.tail, { type: 'REASONING_MESSAGE_CONTENT', messageId: reasoningId, delta: value.delta }) }), @@ -952,8 +1011,10 @@ const projectOf = ( ): ReadonlyArray => { const projector = makeProjector(options) sortRecords(input.records).forEach((envelope) => processRecord(projector, envelope)) + const recordItems = restrictFrom(projector.items, input.afterSequence) + const textStart = projector.items.length if (input.text !== undefined) processText(projector, input.text) - return restrictFrom(projector.items, input.afterSequence) + return [...recordItems, ...projector.items.slice(textStart)] } const isInput = ( From 9152c2d20e6009d3bf80109ea9b410ffbb28db39 Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot <318394648+systemfsoftware-bot@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:41:29 -0500 Subject: [PATCH 5/5] fix(agui): drain streamed projections, start a run before queueing steering, shape inline failed tool results The durable AG-UI stream kept every projected event in one projector for the stream's whole life; each record's events now leave the projector as they are emitted. A steering input recorded for a run whose start the slice never saw queued before RUN_STARTED; it now goes through the same live-run path as other run events, and a finished run still answers not-joined. An inline tool-result part that failed was emitted without the { error, code } shape the settled-call path gives it. --- packages/effect-agent/src/durable/DurableAgUi.ts | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/packages/effect-agent/src/durable/DurableAgUi.ts b/packages/effect-agent/src/durable/DurableAgUi.ts index 20f80742..dc1e1141 100644 --- a/packages/effect-agent/src/durable/DurableAgUi.ts +++ b/packages/effect-agent/src/durable/DurableAgUi.ts @@ -332,7 +332,10 @@ const appendPart = ( runId, value.id, value.isFailure, - Option.getOrElse(Schema.decodeUnknownOption(Schema.Json)(value.result), () => null), + toolResultContent( + Option.getOrElse(Schema.decodeUnknownOption(Schema.Json)(value.result), () => null), + value.isFailure, + ), )), Match.orElse(() => undefined), ) @@ -474,8 +477,8 @@ const queueForRun = ( inputId: string, runId: RunId, ): void => { - const run = runOf(projector, runId) - if (run.terminated) { + const run = liveRun(projector, sequence, runId) + if (run === undefined) { emit(projector, sequence, steeringEvent('not-joined', inputId, runId)) return } @@ -1030,9 +1033,8 @@ const streamOf = ( () => makeProjector(options), (projector, envelope) => Effect.sync((): readonly [Projector, ReadonlyArray] => { - const start = projector.items.length processRecord(projector, envelope) - return [projector, projector.items.slice(start)] + return [projector, projector.items.splice(0)] }), ), )