From 12c88330cbbd894436b4f76f636ef3e0b7e2f25a Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot <318394648+systemfsoftware-bot@users.noreply.github.com> Date: Thu, 26 Nov 2026 07:27:25 -0500 Subject: [PATCH 1/5] feat(observability): use Effect AI Telemetry for model and tool spans Compose `Telemetry.CurrentSpanTransformer` around each model call, running a host-provided transformer first, so model spans keep Effect AI's span name and the library identity is written through `addGenAIAnnotations` and `addSpanAttributes`. Build tool attributes once and apply the same map to the canonical Tool span and its terminal log, dropping duplicated unprefixed keys. --- .changeset/native-model-telemetry.md | 14 ++ .../src/engine/internal/agent-runtime.ts | 151 +++++++++--------- .../test/engine/join-restart.test.ts | 2 +- 3 files changed, 89 insertions(+), 78 deletions(-) create mode 100644 .changeset/native-model-telemetry.md diff --git a/.changeset/native-model-telemetry.md b/.changeset/native-model-telemetry.md new file mode 100644 index 00000000..9cc2b5c4 --- /dev/null +++ b/.changeset/native-model-telemetry.md @@ -0,0 +1,14 @@ +--- +"@systemfsoftware/agent": patch +"@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 +--- +BEHAVIOR CHANGE: Model spans keep Effect AI's `LanguageModel.streamText` name instead of `chat `, and every span and terminal Tool log writes identity through the pinned `effect/ai/Telemetry` helpers. Read the `gen_ai.*` and `effect_agent.*` attributes instead of the removed unprefixed `agentId`, `threadId`, `runId`, `turnId`, `toolCallId`, `toolName`, `parentToolCallId`, `sequenceIndex`, `toolExecutionClass`, and `toolOutcome` keys. diff --git a/packages/effect-agent/src/engine/internal/agent-runtime.ts b/packages/effect-agent/src/engine/internal/agent-runtime.ts index a444cd4e..0a7a9ae7 100644 --- a/packages/effect-agent/src/engine/internal/agent-runtime.ts +++ b/packages/effect-agent/src/engine/internal/agent-runtime.ts @@ -4,6 +4,7 @@ import * as Model from 'effect/ai/Model' import * as Prompt from 'effect/ai/Prompt' import * as Response from 'effect/ai/Response' import * as ResponseIdTracker from 'effect/ai/ResponseIdTracker' +import * as Telemetry from 'effect/ai/Telemetry' import * as Tool from 'effect/ai/Tool' import * as Toolkit from 'effect/ai/Toolkit' import * as Arr from 'effect/Array' @@ -31,8 +32,9 @@ import * as SchemaAST from 'effect/SchemaAST' import * as Scope from 'effect/Scope' import * as Semaphore from 'effect/Semaphore' import * as Stream from 'effect/Stream' +import * as EffectString from 'effect/String' import type * as Take from 'effect/Take' -import * as Tracer from 'effect/Tracer' +import type * as Tracer from 'effect/Tracer' import type * as Agent from '../../core/Agent' import { @@ -1975,84 +1977,87 @@ interface ToolTelemetryDescriptor { readonly sequenceIndex?: number | undefined } +type TelemetryAttributeValue = string | number | boolean + +type TelemetryAttributes = Readonly> + +const addGenAiSpanAttributes = Telemetry.addSpanAttributes('gen_ai', EffectString.camelToSnake) +const addEffectAgentSpanAttributes = Telemetry.addSpanAttributes('effect_agent', EffectString.camelToSnake) + +const writeTelemetryAttributes = (span: Tracer.Span, attributes: TelemetryAttributes): void => { + for (const prefix of ['gen_ai', 'effect_agent'] as const) { + const head = `${prefix}.` + const projected: Record = {} + for (const [name, value] of Object.entries(attributes)) { + if (name.startsWith(head)) projected[name.slice(head.length)] = value + } + if (prefix === 'gen_ai') addGenAiSpanAttributes(span, projected) + else addEffectAgentSpanAttributes(span, projected) + } +} + /** A definition names the agent; its Thread identifies the continuing instance and conversation. */ -const agentTelemetryAttributes = (context: RunContext) => ({ +const agentTelemetryAttributes = (context: RunContext, turnId?: TurnId): TelemetryAttributes => ({ 'gen_ai.agent.name': context.agentId, 'gen_ai.agent.id': context.threadId, 'gen_ai.conversation.id': context.threadId, + 'effect_agent.run.id': context.runId, + 'effect_agent.thread.id': context.threadId, + ...(turnId === undefined ? {} : { 'effect_agent.turn.id': turnId }), }) -/** Label Effect AI's existing span, preserving provider usage, sampling and host async context. */ -const modelTelemetryTracer = Effect.fnUntraced(function*( +const modelSpanTransformer = ( context: RunContext, - turnId?: TurnId, - onSpan?: (span: Tracer.Span) => void, -) { - const delegate = yield* Tracer.Tracer - const model = yield* Model.ModelName - const provider = yield* Model.ProviderName - - return Tracer.make({ - span(options) { - if (options.name !== 'LanguageModel.streamText') return delegate.span(options) - - const span = delegate.span({ ...options, name: `chat ${model}` }) - - onSpan?.(span) - - const attributes = { - ...agentTelemetryAttributes(context), - 'gen_ai.operation.name': 'chat', - 'gen_ai.request.model': model, - 'gen_ai.provider.name': provider, - agentId: context.agentId, - threadId: context.threadId, - runId: context.runId, - ...(turnId === undefined ? {} : { turnId }), - } - - for (const [key, value] of Object.entries(attributes)) span.attribute(key, value) - - return span - }, - ...(delegate.context === undefined ? {} : { context: delegate.context.bind(delegate) }), + turnId: TurnId | undefined, + onFinish?: (span: Tracer.Span) => void, +): Effect.Effect => + Effect.gen(function*() { + const host = yield* Effect.serviceOption(Telemetry.CurrentSpanTransformer) + const model = yield* Model.ModelName + const provider = yield* Model.ProviderName + + return (options) => { + if (Option.isSome(host)) host.value(options) + Telemetry.addGenAIAnnotations(options.span, { + operation: { name: 'chat' }, + request: { model }, + provider: { name: provider }, + }) + writeTelemetryAttributes(options.span, agentTelemetryAttributes(context, turnId)) + onFinish?.(options.span) + } }) -}) /** One bounded identity surface shared by canonical Tool spans and terminal logs. */ -const toolTelemetryAttributes = (descriptor: ToolTelemetryDescriptor) => ({ - ...agentTelemetryAttributes(descriptor.context), +const toolTelemetryAttributes = (descriptor: ToolTelemetryDescriptor): TelemetryAttributes => ({ + ...agentTelemetryAttributes(descriptor.context, descriptor.turnId), 'gen_ai.operation.name': 'execute_tool', 'gen_ai.tool.name': descriptor.toolName, 'gen_ai.tool.type': 'function', - ...(descriptor.toolCallId === undefined - ? {} - : { - 'gen_ai.tool.call.id': descriptor.toolCallId, - toolCallId: descriptor.toolCallId, - }), + ...(descriptor.toolCallId === undefined ? {} : { 'gen_ai.tool.call.id': descriptor.toolCallId }), 'effect_agent.tool.execution_class': descriptor.executionClass, 'effect_agent.tool.invocation_kind': descriptor.invocationKind, 'effect_agent.tool.failure_mode': descriptor.failureMode, ...(descriptor.parentToolCallId === undefined ? {} - : { - 'effect_agent.tool.parent_call.id': descriptor.parentToolCallId, - parentToolCallId: descriptor.parentToolCallId, - }), + : { 'effect_agent.tool.parent_call.id': descriptor.parentToolCallId }), ...(descriptor.sequenceIndex === undefined ? {} - : { - 'effect_agent.tool.sequence_index': descriptor.sequenceIndex, - sequenceIndex: descriptor.sequenceIndex, - }), - agentId: descriptor.context.agentId, - threadId: descriptor.context.threadId, - runId: descriptor.context.runId, - turnId: descriptor.turnId, - toolName: descriptor.toolName, + : { 'effect_agent.tool.sequence_index': descriptor.sequenceIndex }), }) +const withToolSpan = + (name: string, attributes: TelemetryAttributes) => + (effect: Effect.Effect): Effect.Effect => + Effect.currentSpan.pipe( + Effect.catchNoSuchElement, + Effect.flatMap((span) => { + if (Option.isSome(span)) writeTelemetryAttributes(span.value, attributes) + return effect + }), + Effect.withSpan(name, { kind: 'internal' }), + ) + /** Canonical content-free terminal signal for any application Tool handler attempt. */ const terminalToolTelemetry = ( descriptor: ToolTelemetryDescriptor, @@ -2076,8 +2081,6 @@ const terminalToolTelemetry = ( ...(failureHandling === undefined ? {} : { 'effect_agent.tool.failure_handling': failureHandling }), - toolExecutionClass: descriptor.executionClass, - toolOutcome: outcome, }), ), ), @@ -2399,10 +2402,7 @@ const executePreparedToolCall = Effect.fnUntraced(function*< return failTerminalResult(toolCause) }), - Effect.withSpan(`execute_tool ${call.name}`, { - kind: 'internal', - attributes: toolTelemetryAttributes(telemetryDescriptor), - }), + withToolSpan(`execute_tool ${call.name}`, toolTelemetryAttributes(telemetryDescriptor)), ) const telemetry = yield* ToolSpanTelemetry @@ -4362,7 +4362,10 @@ const compactContext = ownModelResponsePart( part, @@ -5842,7 +5845,6 @@ const makeTurn = < let restartRequested = false let responseStarted = false - let activeModelSpan: Tracer.Span | undefined let activeProvisionalText: ProvisionalTextModelHandle | undefined const trace: TurnTrace = { @@ -6613,9 +6615,12 @@ const makeTurn = < ) : stream, Stream.provideServiceEffect( - Tracer.Tracer, - modelTelemetryTracer(context, turnId, (span) => { - activeModelSpan = span + Telemetry.CurrentSpanTransformer, + modelSpanTransformer(context, turnId, (span) => { + if (restartRequested) { + span.attribute('effect_agent.model.outcome', 'aborted') + span.attribute('effect_agent.model.abort_reason', 'joined-input') + } }), ), Stream.onStart( @@ -7529,8 +7534,6 @@ const makeTurn = < Effect.sync(() => { restartRequested = true activeProvisionalText?.discard() - activeModelSpan?.attribute('effect_agent.model.outcome', 'aborted') - activeModelSpan?.attribute('effect_agent.model.abort_reason', 'joined-input') }) ), Effect.raceFirst( @@ -9267,9 +9270,6 @@ function executeWithCompletion< attributes: { ...agentTelemetryAttributes(context), 'gen_ai.operation.name': 'invoke_agent', - agentId: context.agentId, - threadId: context.threadId, - runId: context.runId, }, }), Effect.provide(engineToolServices), @@ -9896,10 +9896,7 @@ const measureProgrammaticToolCall = ( ), ) }), - Effect.withSpan(`execute_tool ${descriptor.toolName}`, { - kind: 'internal', - attributes: toolTelemetryAttributes(descriptor), - }), + withToolSpan(`execute_tool ${descriptor.toolName}`, toolTelemetryAttributes(descriptor)), ) return telemetry.isolateEffectSpanLifecycle(measured).pipe( diff --git a/packages/effect-agent/test/engine/join-restart.test.ts b/packages/effect-agent/test/engine/join-restart.test.ts index 2073c85c..39229773 100644 --- a/packages/effect-agent/test/engine/join-restart.test.ts +++ b/packages/effect-agent/test/engine/join-restart.test.ts @@ -170,7 +170,7 @@ it.live('restarts disposable calls twice, discards their drafts and then drains expect(completed).toMatchObject({ usage: { modelCalls: 4, inputTokens: 40, outputTokens: 8 }, }) - const chats = spans.filter((span) => span.name === 'chat join-restart') + const chats = spans.filter((span) => span.name === 'LanguageModel.streamText') expect( chats.slice(0, 2).map((span) => span.attributes.get('effect_agent.model.abort_reason')), From 86726e8c8e7c53cad7ebd1e8704eb84f6001161b Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot <318394648+systemfsoftware-bot@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:10:18 -0500 Subject: [PATCH 2/5] fix(observability): keep tool span creation at the operation boundary The package exports check requires `Effect.withSpan` at an allowlisted operation boundary. Create each `execute_tool` span at its call site and let a separate helper annotate the current span through `addSpanAttributes`, so the shared attribute map still reaches the Tool span. --- .../src/engine/internal/agent-runtime.ts | 35 +++++++++++-------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/packages/effect-agent/src/engine/internal/agent-runtime.ts b/packages/effect-agent/src/engine/internal/agent-runtime.ts index 0a7a9ae7..b6f03e33 100644 --- a/packages/effect-agent/src/engine/internal/agent-runtime.ts +++ b/packages/effect-agent/src/engine/internal/agent-runtime.ts @@ -2046,17 +2046,15 @@ const toolTelemetryAttributes = (descriptor: ToolTelemetryDescriptor): Telemetry : { 'effect_agent.tool.sequence_index': descriptor.sequenceIndex }), }) -const withToolSpan = - (name: string, attributes: TelemetryAttributes) => - (effect: Effect.Effect): Effect.Effect => - Effect.currentSpan.pipe( - Effect.catchNoSuchElement, - Effect.flatMap((span) => { - if (Option.isSome(span)) writeTelemetryAttributes(span.value, attributes) - return effect - }), - Effect.withSpan(name, { kind: 'internal' }), - ) +const annotateToolSpan = (attributes: TelemetryAttributes): Effect.Effect => + Effect.currentSpan.pipe( + Effect.catchNoSuchElement, + Effect.flatMap((span) => + Option.isSome(span) + ? Effect.sync(() => writeTelemetryAttributes(span.value, attributes)) + : Effect.void + ), + ) /** Canonical content-free terminal signal for any application Tool handler attempt. */ const terminalToolTelemetry = ( @@ -2372,7 +2370,8 @@ const executePreparedToolCall = Effect.fnUntraced(function*< return yield* failureMarker() }) - const measured = started.pipe( + const measured = annotateToolSpan(toolTelemetryAttributes(telemetryDescriptor)).pipe( + Effect.andThen(started), Effect.andThen(results), Effect.andThen(commitTerminalResult), Effect.catchCause((cause) => { @@ -2402,7 +2401,7 @@ const executePreparedToolCall = Effect.fnUntraced(function*< return failTerminalResult(toolCause) }), - withToolSpan(`execute_tool ${call.name}`, toolTelemetryAttributes(telemetryDescriptor)), + Effect.withSpan(`execute_tool ${call.name}`, { kind: 'internal' }), ) const telemetry = yield* ToolSpanTelemetry @@ -9864,7 +9863,7 @@ const measureProgrammaticToolCall = ( let terminalResult: ProgrammaticCallOutcome | undefined let propagatedFailure: Cause.Cause | undefined - const measured: Effect.Effect = Effect.exit( + const body: Effect.Effect = Effect.exit( effect, ).pipe( Effect.flatMap((exit): Effect.Effect => { @@ -9896,7 +9895,13 @@ const measureProgrammaticToolCall = ( ), ) }), - withToolSpan(`execute_tool ${descriptor.toolName}`, toolTelemetryAttributes(descriptor)), + ) + + const measured: Effect.Effect = annotateToolSpan( + toolTelemetryAttributes(descriptor), + ).pipe( + Effect.andThen(body), + Effect.withSpan(`execute_tool ${descriptor.toolName}`, { kind: 'internal' }), ) return telemetry.isolateEffectSpanLifecycle(measured).pipe( From 6b355b49e57f1400bc84c27a58854596b97ff127 Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot <318394648+systemfsoftware-bot@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:34:48 -0500 Subject: [PATCH 3/5] feat(agui): add an AG-UI event mapper over effect/ai --- .changeset/agui-effect.md | 14 + packages/effect-agent/package.json | 5 + packages/effect-agent/src/engine/AgUi.ts | 497 +++++++++++++++++++++++ packages/effect-agent/src/index.ts | 1 + 4 files changed, 517 insertions(+) create mode 100644 .changeset/agui-effect.md create mode 100644 packages/effect-agent/src/engine/AgUi.ts diff --git a/.changeset/agui-effect.md b/.changeset/agui-effect.md new file mode 100644 index 00000000..b1113719 --- /dev/null +++ b/.changeset/agui-effect.md @@ -0,0 +1,14 @@ +--- +"@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 `@systemfsoftware/agent/agui`: `toAgUiEvents` maps a Run's semantic event stream to AG-UI events with Run lifecycle handling, `fromAgUiInput` adapts an AG-UI run input into a Prompt, and `makeAgUiHandler` builds the AG-UI HTTP handler over a durable Run. Suspended and interrupted Runs end with AG-UI `RunFinished` outcomes instead of `RunError`, state snapshots are not emitted, and subagent events are omitted unless `includeSubagents` is set. diff --git a/packages/effect-agent/package.json b/packages/effect-agent/package.json index ee573b32..1c4eed38 100644 --- a/packages/effect-agent/package.json +++ b/packages/effect-agent/package.json @@ -24,6 +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", "./browser-use": "./src/capabilities/BrowserUse.ts", "./budget": "./src/capabilities/Budget.ts", "./code-executor": "./src/sandbox/CodeExecutor.ts", @@ -168,6 +169,10 @@ "types": "./dist/core/AgentUpdates.d.mts", "default": "./dist/core/AgentUpdates.mjs" }, + "./agui": { + "types": "./dist/engine/AgUi.d.mts", + "default": "./dist/engine/AgUi.mjs" + }, "./browser-use": { "types": "./dist/capabilities/BrowserUse.d.mts", "default": "./dist/capabilities/BrowserUse.mjs" diff --git a/packages/effect-agent/src/engine/AgUi.ts b/packages/effect-agent/src/engine/AgUi.ts new file mode 100644 index 00000000..09a41091 --- /dev/null +++ b/packages/effect-agent/src/engine/AgUi.ts @@ -0,0 +1,497 @@ +// @effect-diagnostics experimentalApiUsage:off +import * as AgUi from 'effect/ai/AgUi' +import * as AgUiSchema from 'effect/ai/AgUiSchema' +import * as AgUiServer from 'effect/ai/AgUiServer' +import type * as Prompt from 'effect/ai/Prompt' +import * as Effect from 'effect/Effect' +import * as Match from 'effect/Match' +import * as Schema from 'effect/Schema' +import * as Stream from 'effect/Stream' +import type { + AgentUpdateEmitted, + ApprovalRequested, + BudgetWarning, + CompactionPerformed, + ModelRestarted, + ModelStarted, + ReasoningDelta, + RunCompleted, + RunEvent, + RunFailed, + RunInterrupted, + RunStarted, + RunSuspended, + SteeringApplied, + SubagentCompleted, + SubagentFailed, + SubagentInterrupted, + SubagentJoined, + SubagentProgress, + SubagentRequested, + SubagentStarted, + TextDelta, + ToolCallDeclared, + ToolCallFailed, + ToolCallStarted, + ToolCallSucceeded, + ToolProgress, + TurnCompleted, + TurnStarted, +} from '../core/RunEvent' +import type { RunTotals } from '../core/Usage' + +interface AgUiEventOptions { + readonly includeSubagents?: boolean | undefined +} + +interface MapperState { + readonly textMessageId: string | undefined + readonly reasoningMessageId: string | undefined + readonly stepName: string | undefined +} + +type Mapped = readonly [MapperState, ReadonlyArray] + +const initialState: MapperState = { + textMessageId: undefined, + reasoningMessageId: undefined, + stepName: undefined, +} + +const encodeJsonEvent = Schema.encodeEffect(Schema.fromJsonString(Schema.Json)) + +const encodeJson = (value: Schema.Json): Effect.Effect => encodeJsonEvent(value).pipe(Effect.orDie) + +const mapped = (value: Mapped): Effect.Effect => Effect.succeed(value) + +const subagentUsage = (usage: RunTotals | undefined): ReadonlyArray => tokenUsage(usage) ?? [] + +const tokenUsage = (usage: RunTotals | undefined): ReadonlyArray | undefined => + usage === undefined + ? undefined + : [ + { + inputTokens: usage.inputTokens, + outputTokens: usage.outputTokens, + totalTokens: usage.inputTokens + usage.outputTokens, + }, + ] + +const closeText = (state: MapperState): Mapped => + state.textMessageId === undefined + ? [state, []] + : [ + { ...state, textMessageId: undefined }, + [{ type: 'TEXT_MESSAGE_END', messageId: state.textMessageId }], + ] + +const closeReasoning = (state: MapperState): Mapped => + state.reasoningMessageId === undefined + ? [state, []] + : [ + { ...state, reasoningMessageId: undefined }, + [ + { type: 'REASONING_MESSAGE_END', messageId: state.reasoningMessageId }, + { type: 'REASONING_END', messageId: state.reasoningMessageId }, + ], + ] + +const closeStep = (state: MapperState): Mapped => + state.stepName === undefined + ? [state, []] + : [{ ...state, stepName: undefined }, [{ type: 'STEP_FINISHED', stepName: state.stepName }]] + +const closeOpen = (state: MapperState): Mapped => { + const [afterText, textEvents] = closeText(state) + const [afterReasoning, reasoningEvents] = closeReasoning(afterText) + const [afterStep, stepEvents] = closeStep(afterReasoning) + return [afterStep, [...textEvents, ...reasoningEvents, ...stepEvents]] +} + +const appendText = (state: MapperState, event: TextDelta): Mapped => { + if (state.textMessageId !== undefined) { + return [state, [{ type: 'TEXT_MESSAGE_CONTENT', messageId: state.textMessageId, delta: event.text }]] + } + + const messageId = `${event.runId}:${event.sequence}:text` + + return [ + { ...state, textMessageId: messageId }, + [ + { type: 'TEXT_MESSAGE_START', messageId, role: 'assistant' }, + { type: 'TEXT_MESSAGE_CONTENT', messageId, delta: event.text }, + ], + ] +} + +const appendReasoning = (state: MapperState, event: ReasoningDelta): Mapped => { + if (state.reasoningMessageId !== undefined) { + return [ + state, + [{ type: 'REASONING_MESSAGE_CONTENT', messageId: state.reasoningMessageId, delta: event.text }], + ] + } + + const messageId = `${event.runId}:${event.sequence}:reasoning` + + return [ + { ...state, reasoningMessageId: messageId }, + [ + { type: 'REASONING_START', messageId }, + { type: 'REASONING_MESSAGE_START', messageId, role: 'reasoning' }, + { type: 'REASONING_MESSAGE_CONTENT', messageId, delta: event.text }, + ], + ] +} + +const mapEvent = ( + state: MapperState, + event: RunEvent, + includeSubagents: boolean, +): Effect.Effect => + Match.value(event).pipe( + Match.tagsExhaustive({ + RunStarted: (event: RunStarted) => + mapped([ + initialState, + [ + { + type: 'RUN_STARTED', + threadId: event.threadId, + runId: event.runId, + protocolVersion: AgUiSchema.protocolVersion, + }, + ], + ]), + TurnStarted: (event: TurnStarted) => { + const [closed, closing] = closeOpen(state) + const stepName = `turn-${event.turn}` + return mapped([{ ...closed, stepName }, [...closing, { type: 'STEP_STARTED', stepName }]]) + }, + ModelStarted: (_event: ModelStarted) => mapped([state, []]), + ModelRestarted: (event: ModelRestarted) => + mapped([ + state, + [ + { + type: 'CUSTOM', + name: 'effect_agent.model_restarted', + value: { turn: event.turn, reason: event.reason }, + }, + ], + ]), + SteeringApplied: (event: SteeringApplied) => + mapped([ + state, + [ + { + type: 'CUSTOM', + name: 'effect_agent.steering_applied', + value: { inputIds: [...event.inputIds] }, + }, + ], + ]), + TextDelta: (event: TextDelta) => mapped(appendText(state, event)), + ReasoningDelta: (event: ReasoningDelta) => mapped(appendReasoning(state, event)), + ToolCallDeclared: (event: ToolCallDeclared) => + Effect.map(encodeJson(event.parameters), (delta): Mapped => [ + state, + [ + { + type: 'TOOL_CALL_START', + toolCallId: event.toolCallId, + toolCallName: event.toolName, + ...(state.textMessageId === undefined ? {} : { parentMessageId: state.textMessageId }), + }, + { type: 'TOOL_CALL_ARGS', toolCallId: event.toolCallId, delta }, + { type: 'TOOL_CALL_END', toolCallId: event.toolCallId }, + ], + ]), + ToolCallStarted: (_event: ToolCallStarted) => mapped([state, []]), + ToolProgress: (_event: ToolProgress) => mapped([state, []]), + ToolCallSucceeded: (event: ToolCallSucceeded) => + Effect.map(encodeJson(event.result), (content): Mapped => [ + state, + [ + { + type: 'TOOL_CALL_RESULT', + messageId: `${event.runId}:${event.toolCallId}:result`, + toolCallId: event.toolCallId, + content, + role: 'tool', + }, + ], + ]), + ToolCallFailed: (event: ToolCallFailed) => + mapped([ + state, + [ + { + type: 'TOOL_CALL_RESULT', + messageId: `${event.runId}:${event.toolCallId}:error`, + toolCallId: event.toolCallId, + content: event.message, + role: 'tool', + }, + ], + ]), + ApprovalRequested: (event: ApprovalRequested) => + mapped([ + state, + [ + { + type: 'CUSTOM', + name: 'effect_agent.approval_requested', + value: { toolCallId: event.toolCallId, toolName: event.toolName }, + }, + ], + ]), + TurnCompleted: (_event: TurnCompleted) => mapped(closeOpen(state)), + BudgetWarning: (event: BudgetWarning) => + mapped([ + state, + [ + { + type: 'CUSTOM', + name: 'effect_agent.budget_warning', + value: { limit: event.limit, consumed: event.consumed, limitValue: event.limitValue }, + }, + ], + ]), + CompactionPerformed: (event: CompactionPerformed) => + mapped([ + state, + [ + { + type: 'CUSTOM', + name: 'effect_agent.compaction_performed', + value: { + turn: event.turn, + kind: event.kind, + tokensBefore: event.tokensBeforeEstimate, + tokensAfter: event.tokensAfterEstimate, + }, + }, + ], + ]), + AgentUpdateEmitted: (_event: AgentUpdateEmitted) => mapped([state, []]), + RunCompleted: (event: RunCompleted) => { + const [closed, closing] = closeOpen(state) + const usage = tokenUsage(event.usage) + return mapped([ + closed, + [ + ...closing, + { + type: 'RUN_FINISHED', + threadId: event.threadId, + runId: event.runId, + result: event.output, + outcome: { type: 'success' }, + ...(usage === undefined ? {} : { usage }), + }, + ], + ]) + }, + RunFailed: (event: RunFailed) => { + const [closed, closing] = closeOpen(state) + const usage = tokenUsage(event.usage) + return mapped([ + closed, + [ + ...closing, + { + type: 'RUN_ERROR', + message: event.message, + code: event.errorTag, + ...(usage === undefined ? {} : { usage }), + }, + ], + ]) + }, + RunInterrupted: (event: RunInterrupted) => { + const [closed, closing] = closeOpen(state) + return mapped([ + closed, + [ + ...closing, + { type: 'CUSTOM', name: 'effect_agent.run_interrupted', value: { message: event.message } }, + { + type: 'RUN_FINISHED', + threadId: event.threadId, + runId: event.runId, + outcome: { type: 'cancelled' }, + }, + ], + ]) + }, + RunSuspended: (event: RunSuspended) => { + const [closed, closing] = closeOpen(state) + const usage = tokenUsage(event.usage) + return mapped([ + closed, + [ + ...closing, + { type: 'CUSTOM', name: 'effect_agent.run_suspended', value: { reason: event.reason } }, + { + type: 'RUN_FINISHED', + threadId: event.threadId, + runId: event.runId, + outcome: { + type: 'interrupt', + interrupts: [{ id: `${event.runId}:suspended`, reason: event.reason }], + }, + ...(usage === undefined ? {} : { usage }), + }, + ], + ]) + }, + SubagentRequested: (_event: SubagentRequested) => mapped([state, []]), + SubagentStarted: (event: SubagentStarted) => + mapped( + includeSubagents + ? [ + state, + [ + { + type: 'SUBAGENT_STARTED', + subagentRunId: event.childRunId, + name: event.targetAgentId, + parentToolCallId: event.toolCallId, + }, + ], + ] + : [state, []], + ), + SubagentProgress: (event: SubagentProgress) => + mapped( + includeSubagents + ? [ + state, + [ + { + type: 'CUSTOM', + name: 'effect_agent.subagent_progress', + value: { summary: event.summary }, + subagentRunId: event.childRunId, + }, + ], + ] + : [state, []], + ), + SubagentCompleted: (event: SubagentCompleted) => + mapped( + includeSubagents + ? [ + state, + [ + { + type: 'SUBAGENT_FINISHED', + subagentRunId: event.childRunId, + outcome: { type: 'success' }, + }, + ], + ] + : [state, []], + ), + SubagentFailed: (event: SubagentFailed) => + mapped( + includeSubagents + ? [ + state, + [ + { + type: 'SUBAGENT_ERROR', + subagentRunId: event.childRunId, + message: event.message, + code: event.errorTag, + }, + ], + ] + : [state, []], + ), + SubagentInterrupted: (event: SubagentInterrupted) => + mapped( + includeSubagents + ? [ + state, + [ + { + type: 'CUSTOM', + name: 'effect_agent.subagent_interrupted', + value: { reason: event.reason }, + subagentRunId: event.childRunId, + }, + { + type: 'SUBAGENT_FINISHED', + subagentRunId: event.childRunId, + outcome: { type: 'suspended' }, + }, + ], + ] + : [state, []], + ), + SubagentJoined: (event: SubagentJoined) => + mapped( + includeSubagents + ? [ + state, + [ + { + type: 'CUSTOM', + name: 'effect_agent.subagent_joined', + value: { usage: subagentUsage(event.usage) }, + subagentRunId: event.childRunId, + }, + ], + ] + : [state, []], + ), + }), + ) + +const toAgUiEventsOf = ( + events: Stream.Stream, + options: AgUiEventOptions | undefined, +): Stream.Stream => + events.pipe( + Stream.mapAccumEffect( + () => initialState, + (state, event) => mapEvent(state, event, options?.includeSubagents === true), + ), + ) + +const isRunEventStream = ( + value: Stream.Stream | AgUiEventOptions | undefined, +): value is Stream.Stream => Stream.isStream(value) + +export function toAgUiEvents( + events: Stream.Stream, + options?: AgUiEventOptions, +): Stream.Stream +export function toAgUiEvents( + options?: AgUiEventOptions, +): (events: Stream.Stream) => Stream.Stream +export function toAgUiEvents( + first?: Stream.Stream | AgUiEventOptions, + options?: AgUiEventOptions, +): + | Stream.Stream + | ((events: Stream.Stream) => Stream.Stream) +{ + return isRunEventStream(first) + ? toAgUiEventsOf(first, options) + : (events) => toAgUiEventsOf(events, first) +} + +export const fromAgUiInput = (input: AgUiSchema.RunAgentInput): Prompt.Prompt => AgUi.toPrompt(input) + +interface AgUiHandlerConfig { + readonly run: (input: AgUiSchema.RunAgentInput) => Stream.Stream + readonly includeSubagents?: boolean | undefined +} + +export const makeAgUiHandler = (config: AgUiHandlerConfig) => + AgUiServer.handler((input: AgUiSchema.RunAgentInput) => + toAgUiEventsOf(config.run(input), { includeSubagents: config.includeSubagents }) + ) diff --git a/packages/effect-agent/src/index.ts b/packages/effect-agent/src/index.ts index 0259ae3a..f470da39 100644 --- a/packages/effect-agent/src/index.ts +++ b/packages/effect-agent/src/index.ts @@ -79,6 +79,7 @@ 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 53ea0b12d2cea33113ba5a11064243667c77b350 Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot <318394648+systemfsoftware-bot@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:45:13 -0500 Subject: [PATCH 4/5] fix(agui): close interleaved content, correlate suspensions, encode failures --- .changeset/agui-effect.md | 2 +- packages/effect-agent/src/engine/AgUi.ts | 126 +++++++++++++++++------ 2 files changed, 96 insertions(+), 32 deletions(-) diff --git a/.changeset/agui-effect.md b/.changeset/agui-effect.md index b1113719..06553376 100644 --- a/.changeset/agui-effect.md +++ b/.changeset/agui-effect.md @@ -11,4 +11,4 @@ "@systemfsoftware/agent-storage-sqlite": none "@systemfsoftware/agent-testing": none --- -Adds `@systemfsoftware/agent/agui`: `toAgUiEvents` maps a Run's semantic event stream to AG-UI events with Run lifecycle handling, `fromAgUiInput` adapts an AG-UI run input into a Prompt, and `makeAgUiHandler` builds the AG-UI HTTP handler over a durable Run. Suspended and interrupted Runs end with AG-UI `RunFinished` outcomes instead of `RunError`, state snapshots are not emitted, and subagent events are omitted unless `includeSubagents` is set. +Adds `@systemfsoftware/agent/agui`: `toAgUiEvents` maps a Run's semantic event stream to AG-UI events with Run lifecycle handling, `fromAgUiInput` adapts an AG-UI run input into a Prompt, and `makeAgUiHandler` builds the AG-UI HTTP handler over a durable Run. Suspended and interrupted Runs end with AG-UI `RunFinished` outcomes instead of `RunError`, state snapshots are not emitted, and subagent events are omitted unless `includeSubagents` is set. Tool results and failures are JSON-encoded in `TOOL_CALL_RESULT`, and a suspended Run reports one interrupt per pending approval. diff --git a/packages/effect-agent/src/engine/AgUi.ts b/packages/effect-agent/src/engine/AgUi.ts index 09a41091..d701eeee 100644 --- a/packages/effect-agent/src/engine/AgUi.ts +++ b/packages/effect-agent/src/engine/AgUi.ts @@ -48,6 +48,7 @@ interface MapperState { readonly textMessageId: string | undefined readonly reasoningMessageId: string | undefined readonly stepName: string | undefined + readonly pendingApprovals: ReadonlyArray } type Mapped = readonly [MapperState, ReadonlyArray] @@ -56,6 +57,7 @@ const initialState: MapperState = { textMessageId: undefined, reasoningMessageId: undefined, stepName: undefined, + pendingApprovals: [], } const encodeJsonEvent = Schema.encodeEffect(Schema.fromJsonString(Schema.Json)) @@ -66,6 +68,41 @@ const mapped = (value: Mapped): Effect.Effect => Effect.succeed(value) const subagentUsage = (usage: RunTotals | undefined): ReadonlyArray => tokenUsage(usage) ?? [] +const pendingWith = (pending: ReadonlyArray, toolCallId: string): ReadonlyArray => + pending.includes(toolCallId) ? pending : [...pending, toolCallId] + +const pendingWithout = (pending: ReadonlyArray, toolCallId: string): ReadonlyArray => + pending.includes(toolCallId) ? pending.filter((value) => value !== toolCallId) : pending + +const suspensionId = (runId: string, sequence: number, toolCallId: string | undefined): string => + toolCallId === undefined + ? `${runId}:${sequence}:suspended` + : `${runId}:${sequence}:${toolCallId}:suspended` + +const suspendInterrupt = ( + runId: string, + sequence: number, + reason: string, + toolCallId: string | undefined, +): AgUiSchema.Interrupt => ({ + id: suspensionId(runId, sequence, toolCallId), + reason, + ...(toolCallId === undefined ? {} : { toolCallId }), +}) + +const suspensionInterrupts = ( + runId: string, + sequence: number, + reason: string, + pending: ReadonlyArray, +): readonly [AgUiSchema.Interrupt, ...Array] => { + const [head, ...rest] = pending + return [ + suspendInterrupt(runId, sequence, reason, head), + ...rest.map((toolCallId) => suspendInterrupt(runId, sequence, reason, toolCallId)), + ] +} + const tokenUsage = (usage: RunTotals | undefined): ReadonlyArray | undefined => usage === undefined ? undefined @@ -96,28 +133,39 @@ const closeReasoning = (state: MapperState): Mapped => ], ] +const closeContent = (state: MapperState): Mapped => { + const [afterText, textEvents] = closeText(state) + const [afterReasoning, reasoningEvents] = closeReasoning(afterText) + return [afterReasoning, [...textEvents, ...reasoningEvents]] +} + const closeStep = (state: MapperState): Mapped => state.stepName === undefined ? [state, []] : [{ ...state, stepName: undefined }, [{ type: 'STEP_FINISHED', stepName: state.stepName }]] const closeOpen = (state: MapperState): Mapped => { - const [afterText, textEvents] = closeText(state) - const [afterReasoning, reasoningEvents] = closeReasoning(afterText) - const [afterStep, stepEvents] = closeStep(afterReasoning) - return [afterStep, [...textEvents, ...reasoningEvents, ...stepEvents]] + const [afterContent, contentEvents] = closeContent(state) + const [afterStep, stepEvents] = closeStep(afterContent) + return [afterStep, [...contentEvents, ...stepEvents]] } const appendText = (state: MapperState, event: TextDelta): Mapped => { - if (state.textMessageId !== undefined) { - return [state, [{ type: 'TEXT_MESSAGE_CONTENT', messageId: state.textMessageId, delta: event.text }]] + const [closed, closing] = closeReasoning(state) + + if (closed.textMessageId !== undefined) { + return [ + closed, + [...closing, { type: 'TEXT_MESSAGE_CONTENT', messageId: closed.textMessageId, delta: event.text }], + ] } const messageId = `${event.runId}:${event.sequence}:text` return [ - { ...state, textMessageId: messageId }, + { ...closed, textMessageId: messageId }, [ + ...closing, { type: 'TEXT_MESSAGE_START', messageId, role: 'assistant' }, { type: 'TEXT_MESSAGE_CONTENT', messageId, delta: event.text }, ], @@ -125,18 +173,21 @@ const appendText = (state: MapperState, event: TextDelta): Mapped => { } const appendReasoning = (state: MapperState, event: ReasoningDelta): Mapped => { - if (state.reasoningMessageId !== undefined) { + const [closed, closing] = closeText(state) + + if (closed.reasoningMessageId !== undefined) { return [ - state, - [{ type: 'REASONING_MESSAGE_CONTENT', messageId: state.reasoningMessageId, delta: event.text }], + closed, + [...closing, { type: 'REASONING_MESSAGE_CONTENT', messageId: closed.reasoningMessageId, delta: event.text }], ] } const messageId = `${event.runId}:${event.sequence}:reasoning` return [ - { ...state, reasoningMessageId: messageId }, + { ...closed, reasoningMessageId: messageId }, [ + ...closing, { type: 'REASONING_START', messageId }, { type: 'REASONING_MESSAGE_START', messageId, role: 'reasoning' }, { type: 'REASONING_MESSAGE_CONTENT', messageId, delta: event.text }, @@ -193,25 +244,30 @@ const mapEvent = ( ]), TextDelta: (event: TextDelta) => mapped(appendText(state, event)), ReasoningDelta: (event: ReasoningDelta) => mapped(appendReasoning(state, event)), - ToolCallDeclared: (event: ToolCallDeclared) => - Effect.map(encodeJson(event.parameters), (delta): Mapped => [ - state, + ToolCallDeclared: (event: ToolCallDeclared) => { + const parentMessageId = state.textMessageId + const [closed, closing] = closeContent(state) + return Effect.map(encodeJson(event.parameters), (delta): Mapped => [ + closed, [ + ...closing, { type: 'TOOL_CALL_START', toolCallId: event.toolCallId, toolCallName: event.toolName, - ...(state.textMessageId === undefined ? {} : { parentMessageId: state.textMessageId }), + ...(parentMessageId === undefined ? {} : { parentMessageId }), }, { type: 'TOOL_CALL_ARGS', toolCallId: event.toolCallId, delta }, { type: 'TOOL_CALL_END', toolCallId: event.toolCallId }, ], - ]), - ToolCallStarted: (_event: ToolCallStarted) => mapped([state, []]), + ]) + }, + ToolCallStarted: (event: ToolCallStarted) => + mapped([{ ...state, pendingApprovals: pendingWithout(state.pendingApprovals, event.toolCallId) }, []]), ToolProgress: (_event: ToolProgress) => mapped([state, []]), ToolCallSucceeded: (event: ToolCallSucceeded) => Effect.map(encodeJson(event.result), (content): Mapped => [ - state, + { ...state, pendingApprovals: pendingWithout(state.pendingApprovals, event.toolCallId) }, [ { type: 'TOOL_CALL_RESULT', @@ -223,21 +279,24 @@ const mapEvent = ( ], ]), ToolCallFailed: (event: ToolCallFailed) => - mapped([ - state, - [ - { - type: 'TOOL_CALL_RESULT', - messageId: `${event.runId}:${event.toolCallId}:error`, - toolCallId: event.toolCallId, - content: event.message, - role: 'tool', - }, + Effect.map( + encodeJson({ error: event.message, code: event.errorTag }), + (content): Mapped => [ + { ...state, pendingApprovals: pendingWithout(state.pendingApprovals, event.toolCallId) }, + [ + { + type: 'TOOL_CALL_RESULT', + messageId: `${event.runId}:${event.toolCallId}:error`, + toolCallId: event.toolCallId, + content, + role: 'tool', + }, + ], ], - ]), + ), ApprovalRequested: (event: ApprovalRequested) => mapped([ - state, + { ...state, pendingApprovals: pendingWith(state.pendingApprovals, event.toolCallId) }, [ { type: 'CUSTOM', @@ -339,7 +398,12 @@ const mapEvent = ( runId: event.runId, outcome: { type: 'interrupt', - interrupts: [{ id: `${event.runId}:suspended`, reason: event.reason }], + interrupts: suspensionInterrupts( + event.runId, + event.sequence, + event.reason, + state.pendingApprovals, + ), }, ...(usage === undefined ? {} : { usage }), }, From 46e49fd1ac986982825bb60b1fdc1b406b97f13e Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot <318394648+systemfsoftware-bot@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:50:56 -0500 Subject: [PATCH 5/5] fix(agui): close in-flight subagents and clear pending approvals --- .changeset/agui-effect.md | 2 +- packages/effect-agent/src/engine/AgUi.ts | 52 ++++++++++++++++++------ 2 files changed, 40 insertions(+), 14 deletions(-) diff --git a/.changeset/agui-effect.md b/.changeset/agui-effect.md index 06553376..d9b9da31 100644 --- a/.changeset/agui-effect.md +++ b/.changeset/agui-effect.md @@ -11,4 +11,4 @@ "@systemfsoftware/agent-storage-sqlite": none "@systemfsoftware/agent-testing": none --- -Adds `@systemfsoftware/agent/agui`: `toAgUiEvents` maps a Run's semantic event stream to AG-UI events with Run lifecycle handling, `fromAgUiInput` adapts an AG-UI run input into a Prompt, and `makeAgUiHandler` builds the AG-UI HTTP handler over a durable Run. Suspended and interrupted Runs end with AG-UI `RunFinished` outcomes instead of `RunError`, state snapshots are not emitted, and subagent events are omitted unless `includeSubagents` is set. Tool results and failures are JSON-encoded in `TOOL_CALL_RESULT`, and a suspended Run reports one interrupt per pending approval. +Adds `@systemfsoftware/agent/agui`: `toAgUiEvents` maps a Run's semantic event stream to AG-UI events, `makeAgUiHandler` serves them through `AgUiServer.handler`, which applies the AG-UI run lifecycle, and `fromAgUiInput` adapts an AG-UI run input into a Prompt. Suspended and interrupted Runs end with AG-UI `RunFinished` outcomes instead of `RunError`, state snapshots are not emitted, and subagent events are omitted unless `includeSubagents` is set. Tool results and failures are JSON-encoded in `TOOL_CALL_RESULT`, and a suspended Run reports one interrupt per pending approval. diff --git a/packages/effect-agent/src/engine/AgUi.ts b/packages/effect-agent/src/engine/AgUi.ts index d701eeee..8395f2f5 100644 --- a/packages/effect-agent/src/engine/AgUi.ts +++ b/packages/effect-agent/src/engine/AgUi.ts @@ -49,6 +49,7 @@ interface MapperState { readonly reasoningMessageId: string | undefined readonly stepName: string | undefined readonly pendingApprovals: ReadonlyArray + readonly openSubagents: ReadonlyArray } type Mapped = readonly [MapperState, ReadonlyArray] @@ -58,6 +59,7 @@ const initialState: MapperState = { reasoningMessageId: undefined, stepName: undefined, pendingApprovals: [], + openSubagents: [], } const encodeJsonEvent = Schema.encodeEffect(Schema.fromJsonString(Schema.Json)) @@ -150,6 +152,30 @@ const closeOpen = (state: MapperState): Mapped => { return [afterStep, [...contentEvents, ...stepEvents]] } +const subagentWith = (open: ReadonlyArray, childRunId: string): ReadonlyArray => + open.includes(childRunId) ? open : [...open, childRunId] + +const subagentWithout = (open: ReadonlyArray, childRunId: string): ReadonlyArray => + open.includes(childRunId) ? open.filter((value) => value !== childRunId) : open + +const closeSubagents = (state: MapperState): Mapped => { + if (state.openSubagents.length === 0) return [state, []] + return [ + { ...state, openSubagents: [] }, + state.openSubagents.map((subagentRunId): AgUiSchema.Event => ({ + type: 'SUBAGENT_ERROR', + subagentRunId, + message: 'The subagent did not finish.', + })), + ] +} + +const closeAll = (state: MapperState): Mapped => { + const [afterOpen, openEvents] = closeOpen(state) + const [afterSubagents, subagentEvents] = closeSubagents(afterOpen) + return [afterSubagents, [...openEvents, ...subagentEvents]] +} + const appendText = (state: MapperState, event: TextDelta): Mapped => { const [closed, closing] = closeReasoning(state) @@ -335,10 +361,10 @@ const mapEvent = ( ]), AgentUpdateEmitted: (_event: AgentUpdateEmitted) => mapped([state, []]), RunCompleted: (event: RunCompleted) => { - const [closed, closing] = closeOpen(state) + const [closed, closing] = closeAll(state) const usage = tokenUsage(event.usage) return mapped([ - closed, + { ...closed, pendingApprovals: [] }, [ ...closing, { @@ -353,10 +379,10 @@ const mapEvent = ( ]) }, RunFailed: (event: RunFailed) => { - const [closed, closing] = closeOpen(state) + const [closed, closing] = closeAll(state) const usage = tokenUsage(event.usage) return mapped([ - closed, + { ...closed, pendingApprovals: [] }, [ ...closing, { @@ -369,9 +395,9 @@ const mapEvent = ( ]) }, RunInterrupted: (event: RunInterrupted) => { - const [closed, closing] = closeOpen(state) + const [closed, closing] = closeAll(state) return mapped([ - closed, + { ...closed, pendingApprovals: [] }, [ ...closing, { type: 'CUSTOM', name: 'effect_agent.run_interrupted', value: { message: event.message } }, @@ -385,10 +411,10 @@ const mapEvent = ( ]) }, RunSuspended: (event: RunSuspended) => { - const [closed, closing] = closeOpen(state) + const [closed, closing] = closeAll(state) const usage = tokenUsage(event.usage) return mapped([ - closed, + { ...closed, pendingApprovals: [] }, [ ...closing, { type: 'CUSTOM', name: 'effect_agent.run_suspended', value: { reason: event.reason } }, @@ -415,7 +441,7 @@ const mapEvent = ( mapped( includeSubagents ? [ - state, + { ...state, openSubagents: subagentWith(state.openSubagents, event.childRunId) }, [ { type: 'SUBAGENT_STARTED', @@ -447,7 +473,7 @@ const mapEvent = ( mapped( includeSubagents ? [ - state, + { ...state, openSubagents: subagentWithout(state.openSubagents, event.childRunId) }, [ { type: 'SUBAGENT_FINISHED', @@ -462,7 +488,7 @@ const mapEvent = ( mapped( includeSubagents ? [ - state, + { ...state, openSubagents: subagentWithout(state.openSubagents, event.childRunId) }, [ { type: 'SUBAGENT_ERROR', @@ -478,7 +504,7 @@ const mapEvent = ( mapped( includeSubagents ? [ - state, + { ...state, openSubagents: subagentWithout(state.openSubagents, event.childRunId) }, [ { type: 'CUSTOM', @@ -499,7 +525,7 @@ const mapEvent = ( mapped( includeSubagents ? [ - state, + { ...state, openSubagents: subagentWithout(state.openSubagents, event.childRunId) }, [ { type: 'CUSTOM',