The Open Framework for Building Agents
feat(eve): publish durable runtime action events (#1861)
Chad Hietala4138e64b783a
diff --git a/.changeset/runtime-action-events.md b/.changeset/runtime-action-events.mdnew file mode 100644index 000000000..44f4111a2--- /dev/null+++ b/.changeset/runtime-action-events.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Publish durable lifecycle events for runtime actions and user input requests, including approval decisions that resume in another worker. Action terminals expose caller-accepted settlement time, exact outcome, stable error code, and subagent usage even when settlement crosses workers. Framework skill loads are also preserved in eval tool-call facts.diff --git a/packages/eve/src/evals/runner/derive-run-facts.test.ts b/packages/eve/src/evals/runner/derive-run-facts.test.tsindex 6bb14533f..b45803288 100644--- a/packages/eve/src/evals/runner/derive-run-facts.test.ts+++ b/packages/eve/src/evals/runner/derive-run-facts.test.ts@@ -162,6 +162,39 @@ describe("deriveRunFacts", () => {expect(facts.toolCallCount).toBe(2);});+ it("preserves framework skill input in the eval tool-call view", () => {+ const facts = derive([+ turnStarted("t1", 0),+ {+ type: "actions.requested",+ data: {+ actions: [+ {+ callId: "skill-1",+ input: { skill: "research" },+ kind: "load-skill",+ },+ ],+ sequence: 1,+ stepIndex: 0,+ turnId: "t1",+ },+ },+ actionResult({ callId: "skill-1", toolName: "load_skill", output: "Skill body" }),+ ]);++ expect(facts.toolCalls).toEqual([+ {+ input: { skill: "research" },+ name: "load_skill",+ output: "Skill body",+ sessionId: undefined,+ status: "completed",+ turnIndex: 0,+ },+ ]);+ });+it("uses the normalized failed lifecycle status for error results", () => {const events: UnstampedMessageStreamEvent[] = [actionsRequested([{ callId: "c1", toolName: "bash" }]),diff --git a/packages/eve/src/evals/runner/derive-run-facts.ts b/packages/eve/src/evals/runner/derive-run-facts.tsindex 5d6378a33..20578a54d 100644--- a/packages/eve/src/evals/runner/derive-run-facts.ts+++ b/packages/eve/src/evals/runner/derive-run-facts.ts@@ -1,4 +1,5 @@import type { MessageStreamEvent } from "#protocol/message.js";+import { LOAD_SKILL_TOOL_NAME } from "#runtime/skills/fragment-context.js";import type { InputRequest } from "#runtime/input/types.js";import type { JsonObject, JsonValue } from "#shared/json.js";import type { EveEvalDerivedFacts, EveEvalSubagentCall, EveEvalToolCall } from "#evals/types.js";@@ -107,8 +108,11 @@ export function deriveRunFacts(case "actions.requested": {for (const action of event.data.actions) {- if (action.kind !== "tool-call") continue;- ensureToolCall(action.callId, action.toolName, action.input);+ if (action.kind === "tool-call") {+ ensureToolCall(action.callId, action.toolName, action.input);+ } else if (action.kind === "load-skill") {+ ensureToolCall(action.callId, LOAD_SKILL_TOOL_NAME, action.input);+ }}break;}diff --git a/packages/eve/src/execution/durable-session-migrations/turn-workflow.ts b/packages/eve/src/execution/durable-session-migrations/turn-workflow.tsindex 08c06615c..31aa9cf27 100644--- a/packages/eve/src/execution/durable-session-migrations/turn-workflow.ts+++ b/packages/eve/src/execution/durable-session-migrations/turn-workflow.ts@@ -26,6 +26,7 @@ export const TURN_WORKFLOW_INPUT_VERSION = 1;/** Trusted runtime-action results collected by the parent turn driver. */interface RuntimeActionResultStepInput {+ readonly acceptedAtMsByCallId?: Readonly<Record<string, number>>;readonly kind: "runtime-action-result";readonly results: readonly RuntimeActionResult[];}diff --git a/packages/eve/src/execution/node-step.ts b/packages/eve/src/execution/node-step.tsindex 78346a351..25b8ec841 100644--- a/packages/eve/src/execution/node-step.ts+++ b/packages/eve/src/execution/node-step.ts@@ -4,6 +4,7 @@ import type { Runtime, SessionCapabilities } from "#channel/types.js";import { dispatchDynamicModelEvent } from "#context/dynamic-model-lifecycle.js";import { createHarnessDelegationToolDefinition } from "#execution/delegation-tool.js";import type { HarnessToolDefinition } from "#harness/execute-tool.js";+import { LOAD_SKILL_TOOL_NAME } from "#runtime/skills/fragment-context.js";import { createToolLoopHarness } from "#harness/tool-loop.js";import type { HandleEventFn, HarnessToolMap, StepFn } from "#harness/types.js";import { resolveInstalledPackageInfo } from "#internal/application/package.js";@@ -255,6 +256,8 @@ function resolveHarnessToolDefinition(input: {rawExecute,scope: def.name,}),+ frameworkAction:+ isFrameworkTool && def.name === LOAD_SKILL_TOOL_NAME ? "load-skill" : undefined,inputSchema: def.inputSchema ?? UNSPECIFIED_INPUT_SCHEMA,name: def.name,approval: def.approval,diff --git a/packages/eve/src/execution/turn-workflow.test.ts b/packages/eve/src/execution/turn-workflow.test.tsindex 5d69858d5..e4256bcb6 100644--- a/packages/eve/src/execution/turn-workflow.test.ts+++ b/packages/eve/src/execution/turn-workflow.test.ts@@ -551,6 +551,7 @@ describe("turnWorkflow", () => {});it("keeps a local subagent result inside one turn workflow", async () => {+ const now = vi.spyOn(Date, "now").mockReturnValue(1_234);const initialState = createSessionState({ continuationToken: "slack:C1:" });const pendingState = createSessionState({ continuationToken: "slack:C1:T1" });const completedState = createSessionState({ continuationToken: "slack:C1:T1" });@@ -613,8 +614,14 @@ describe("turnWorkflow", () => {});expect(vi.mocked(turnStep).mock.calls[1]?.[0]).toMatchObject({input: {+ acceptedAtMsByCallId: { "call-1": 1_234 },kind: "runtime-action-result",- results: [expect.objectContaining({ callId: "call-1", output: "child output" })],+ results: [+ expect.objectContaining({+ callId: "call-1",+ output: "child output",+ }),+ ],},});expect(resumeHookMock.mock.calls.filter((call) => call[1]?.kind === "turn-result")).toEqual([@@ -631,6 +638,7 @@ describe("turnWorkflow", () => {action: expect.objectContaining({ kind: "dispatch-runtime-actions" }),}),);+ now.mockRestore();});it("waits for dispatch adoption before cascading a cancellation", async () => {@@ -686,6 +694,7 @@ describe("turnWorkflow", () => {});it("keeps dynamic-workflow child dispatch and immediate remote failures in the same turn", async () => {+ const now = vi.spyOn(Date, "now").mockReturnValue(2_345);const pendingState = createSessionState();const completedState = createSessionState();installInbox([]);@@ -731,12 +740,14 @@ describe("turnWorkflow", () => {sessionState: pendingState,});expect(vi.mocked(turnStep).mock.calls[1]?.[0].input).toEqual({+ acceptedAtMsByCallId: { "call-1": 2_345 },kind: "runtime-action-result",results: [expect.objectContaining({ callId: "call-1", isError: true })],});expect(resumeHookMock.mock.calls.filter((call) => call[1]?.kind === "turn-result"),).toHaveLength(1);+ now.mockRestore();});it("proxies child HITL and pulls the response through the active turn", async () => {diff --git a/packages/eve/src/execution/turn-workflow.ts b/packages/eve/src/execution/turn-workflow.tsindex 005330869..313902acf 100644--- a/packages/eve/src/execution/turn-workflow.ts+++ b/packages/eve/src/execution/turn-workflow.ts@@ -28,6 +28,7 @@ import { resolveWorkflowCallbackBaseUrl } from "#execution/workflow-callback-urlimport { normalizeSerializableError } from "#execution/workflow-errors.js";import { turnStep } from "#execution/workflow-steps.js";import { activeTurnId } from "#harness/active-turn-id.js";+import { getRuntimeActionResultKey } from "#runtime/actions/keys.js";import { resolveRuntimeActionResultsForKeys } from "#runtime/actions/results.js";import type { RuntimeActionResult } from "#runtime/actions/types.js";@@ -159,6 +160,7 @@ async function runTurnOwnedWorkflow(input: TurnWorkflowInput): Promise<void> {serializedContext: cursor.serializedContext,sessionState: cursor.sessionState,});+ const initialAcceptedAtMs = dispatchResult.results.length === 0 ? undefined : Date.now();await cursor.adopt(dispatchResult);const results = await waitForRuntimeActionResults({@@ -166,6 +168,7 @@ async function runTurnOwnedWorkflow(input: TurnWorkflowInput): Promise<void> {cancellation,cursor,inboxToken: inbox.token,+ initialAcceptedAtMs,initialResults: dispatchResult.results,iterator,nextDeliveryRequestId,@@ -181,7 +184,7 @@ async function runTurnOwnedWorkflow(input: TurnWorkflowInput): Promise<void> {await finishCancelledTurn({ bufferedDeliveries, cancellation, cursor });return;}- nextStepInput = { kind: "runtime-action-result", results };+ nextStepInput = { kind: "runtime-action-result", ...results };continue;}@@ -258,13 +261,20 @@ async function waitForRuntimeActionResults(input: {readonly cancellation: TurnCancellationControl | undefined;readonly cursor: TurnExecutionCursor;readonly inboxToken: string;+ readonly initialAcceptedAtMs: number | undefined;readonly initialResults: readonly RuntimeActionResult[];readonly iterator: AsyncIterator<TurnInboxPayload>;readonly nextDeliveryRequestId: () => string;readonly pendingActionKeys: readonly string[];-}): Promise<readonly RuntimeActionResult[] | "cancelled" | "cancel-turn"> {+}): Promise<AcceptedRuntimeActionBatch | "cancelled" | "cancel-turn"> {let pendingDeliveryRequest: string | undefined;const results: RuntimeActionResult[] = [...input.initialResults];+ const acceptedAtMsByKey = new Map<string, number>();+ if (input.initialAcceptedAtMs !== undefined) {+ for (const result of input.initialResults) {+ acceptedAtMsByKey.set(getRuntimeActionResultKey(result), input.initialAcceptedAtMs);+ }+ }while (true) {const ready = resolveRuntimeActionResultsForKeys({@@ -280,7 +290,15 @@ async function waitForRuntimeActionResults(input: {requestId: pendingDeliveryRequest,});}- return ready;+ return {+ acceptedAtMsByCallId: Object.fromEntries(+ ready.map((result) => [+ result.callId,+ acceptedAtMsByKey.get(getRuntimeActionResultKey(result))!,+ ]),+ ),+ results: ready,+ };}if (input.cursor.sessionState.hasProxyInputRequests && pendingDeliveryRequest === undefined) {@@ -325,11 +343,16 @@ async function waitForRuntimeActionResults(input: {// dispatch failed — is dropped; the genuine child's result (or the// dispatch error already in `results`) still resolves the wait.const sessionSnapshotState = input.cursor.sessionState.snapshot?.session.state;- results.push(- ...value.results.filter((result) =>- isInboxSubagentResultFromRunningHandle(sessionSnapshotState, result),- ),+ const accepted = value.results.filter((result) =>+ isInboxSubagentResultFromRunningHandle(sessionSnapshotState, result),);+ if (accepted.length > 0) {+ const acceptedAtMs = Date.now();+ results.push(...accepted);+ for (const result of accepted) {+ acceptedAtMsByKey.set(getRuntimeActionResultKey(result), acceptedAtMs);+ }+ }continue;}@@ -369,6 +392,11 @@ async function waitForRuntimeActionResults(input: {}}+interface AcceptedRuntimeActionBatch {+ readonly acceptedAtMsByCallId: Readonly<Record<string, number>>;+ readonly results: readonly RuntimeActionResult[];+}+async function runLegacyTurnWorkflow(input: TurnWorkflowInput): Promise<void> {let currentStepInput: TurnStepInput = input.stepInput;diff --git a/packages/eve/src/execution/workflow-steps.ts b/packages/eve/src/execution/workflow-steps.tsindex a553d0483..077068b9a 100644--- a/packages/eve/src/execution/workflow-steps.ts+++ b/packages/eve/src/execution/workflow-steps.ts@@ -30,6 +30,7 @@ import {setHarnessEmissionState,} from "#harness/emission.js";import { preserveSerializedInstrumentationState } from "#harness/instrumentation-state.js";+import { RuntimeActionSettlementTimesKey } from "#harness/runtime-action-settlement-state.js";import { preserveSerializedAgentTraceState } from "#tracing/agent-trace-context-store.js";import { matchAuthorizationCallbacks } from "#execution/authorization-callback-match.js";import { readTurnSleepDurationMs } from "#harness/turn-sleep.js";@@ -245,6 +246,9 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResuresolved = results.length === 0 ? undefined : results.reduce(coalesceTurnInputs);} else if (input.input?.kind === "runtime-action-result") {recordSubagentUsageSpans(input.input.results);+ if (input.input.acceptedAtMsByCallId !== undefined) {+ ctx.set(RuntimeActionSettlementTimesKey, input.input.acceptedAtMsByCallId);+ }resolved = { runtimeActionResults: input.input.results };}diff --git a/packages/eve/src/harness/execute-tool.ts b/packages/eve/src/harness/execute-tool.tsindex ad92b038e..cca9701f7 100644--- a/packages/eve/src/harness/execute-tool.ts+++ b/packages/eve/src/harness/execute-tool.ts@@ -23,6 +23,7 @@ export interface HarnessToolDefinition {readonly approvalKey?: (toolInput: Readonly<Record<string, unknown>>) => string;readonly description: string;readonly execute?: (input: any, options: ToolExecuteOptions) => any;+ readonly frameworkAction?: "load-skill";readonly inputSchema: FlexibleSchema;readonly name: string;readonly approval?: Approval;diff --git a/packages/eve/src/harness/hitl/approval-input-requests.ts b/packages/eve/src/harness/hitl/approval-input-requests.tsindex 22ddc24ad..3449a0a02 100644--- a/packages/eve/src/harness/hitl/approval-input-requests.ts+++ b/packages/eve/src/harness/hitl/approval-input-requests.ts@@ -2,6 +2,11 @@ import type { ModelMessage } from "ai";import type { RuntimeToolResultActionResult } from "#runtime/actions/types.js";import type { InputRequest, InputResponse } from "#runtime/input/types.js";+import {+ buildResolvedInputBatch,+ resolveApprovalOutcome,+ TOOL_EXECUTION_DENIED_MESSAGE,+} from "#harness/input-request-resolution.js";import { isApprovalRequest } from "#harness/input-request-class.js";import type { PendingInputBatch } from "#harness/pending-input-batches.js";import {@@ -29,12 +34,7 @@ import type { QuestionInputRequest } from "#harness/hitl/question-input-requestsimport type { HarnessSession } from "#harness/types.js";const APPROVED_TOOLS_KEY = "eve.runtime.hitl.approvedTools";-const IGNORED_INPUT_REASON = "Ignored because the user continued without responding.";const TOOL_EXECUTION_DENIED_CODE = "TOOL_EXECUTION_DENIED";-const TOOL_EXECUTION_DENIED_MESSAGE = "Tool execution was denied.";-const TOOL_EXECUTION_INVALID_APPROVAL_MESSAGE = "Invalid approval response.";--type ApprovalTerminalStatus = "approved" | "denied" | "ignored" | "invalid";type ToolApprovalInputRequest = InputRequest & { readonly kind: "tool-approval" };export type RejectedActionBatch = ResolvedInputActionBatch;@@ -130,6 +130,10 @@ export function resolveApprovalInputBatches(leftoverResponses,messages: approval.messages,rejectedActions: approval.rejectedActions,+ resolvedInputs: resolvedBatches.flatMap((batch) => {+ const resolved = buildResolvedInputBatch(batch, input.responses);+ return resolved === undefined ? [] : [resolved];+ }),resolvedStepInput: input.resolvedStepInput,session: removePendingInputBatches(approval.session, resolvedBatches),});@@ -191,27 +195,6 @@ function recordApprovedTools(input: {return { ...input.session, state };}-function resolveApprovalOutcome(response: InputResponse | undefined): {- readonly approved: boolean;- readonly reason: string | undefined;- readonly status: ApprovalTerminalStatus;-} {- if (response === undefined) {- return { approved: false, reason: IGNORED_INPUT_REASON, status: "ignored" };- }- if (response.optionId === "approve") {- return { approved: true, reason: undefined, status: "approved" };- }- if (response.optionId === "cancel") {- return { approved: false, reason: TOOL_EXECUTION_DENIED_MESSAGE, status: "denied" };- }- return {- approved: false,- reason: TOOL_EXECUTION_INVALID_APPROVAL_MESSAGE,- status: "invalid",- };-}-function buildRejectedActionBatch(batch: PendingInputBatch,responses: readonly InputResponse[],diff --git a/packages/eve/src/harness/hitl/pending-input-resolution.ts b/packages/eve/src/harness/hitl/pending-input-resolution.tsindex a2726a2d3..d9d048d4f 100644--- a/packages/eve/src/harness/hitl/pending-input-resolution.ts+++ b/packages/eve/src/harness/hitl/pending-input-resolution.ts@@ -2,6 +2,7 @@ import type { ModelMessage } from "ai";import type { RuntimeToolResultActionResult } from "#runtime/actions/types.js";import type { InputResponse } from "#runtime/input/types.js";+import type { ResolvedInputBatch } from "#harness/input-request-resolution.js";import type { PendingInputBatch, PendingInputBatchEvent } from "#harness/pending-input-batches.js";import { queueDeferredStepInput } from "#harness/pending-input-batches.js";import type { HarnessSession, StepInput } from "#harness/types.js";@@ -34,6 +35,7 @@ export type ResolvePendingInputResult = {readonly outcome: "resolved" | "continue" | "unresolved";readonly messages: ModelMessage[];readonly rejectedActions?: readonly ResolvedInputActionBatch[];+ readonly resolvedInputs?: readonly ResolvedInputBatch[];readonly session: HarnessSession;};@@ -65,6 +67,7 @@ export function finishResolvedInput(input: {readonly limitContinuation?: { readonly granted: boolean };readonly messages: ModelMessage[];readonly rejectedActions?: readonly ResolvedInputActionBatch[];+ readonly resolvedInputs?: readonly ResolvedInputBatch[];readonly resolvedStepInput: ResolvedStepInput | undefined;readonly session: HarnessSession;}): ResolvePendingInputResult {@@ -96,6 +99,7 @@ export function finishResolvedInput(input: {outcome: "resolved",messages: input.messages,rejectedActions: input.rejectedActions,+ resolvedInputs: input.resolvedInputs,session: queueDeferredStepInput(input.session, deferredInput),};}@@ -106,6 +110,7 @@ export function finishResolvedInput(input: {outcome: "resolved",messages: input.messages,rejectedActions: input.rejectedActions,+ resolvedInputs: input.resolvedInputs,session: input.session,};}diff --git a/packages/eve/src/harness/hitl/question-input-requests.ts b/packages/eve/src/harness/hitl/question-input-requests.tsindex 321badd42..1672aec45 100644--- a/packages/eve/src/harness/hitl/question-input-requests.ts+++ b/packages/eve/src/harness/hitl/question-input-requests.ts@@ -1,6 +1,7 @@import type { ModelMessage } from "ai";import type { InputRequest, InputResponse } from "#runtime/input/types.js";+import { buildResolvedInputBatch } from "#harness/input-request-resolution.js";import type { PendingInputBatch } from "#harness/pending-input-batches.js";import {queueDeferredStepInput,@@ -60,6 +61,9 @@ export function resolveQuestionOnlyInputBatches(consumedMessage: input.resolvedStepInput.messageConsumed,outcome: "resolved",messages,+ resolvedInputs: [buildResolvedInputBatch(sole, [])].filter(+ (batch): batch is NonNullable<typeof batch> => batch !== undefined,+ ),session: removePendingInputBatches(input.session, [sole]),};}@@ -74,6 +78,10 @@ export function resolveQuestionOnlyInputBatches(deferTurnInput: input.deferTurnInput,leftoverResponses,messages,+ resolvedInputs: resolvedBatches.flatMap((batch) => {+ const resolved = buildResolvedInputBatch(batch, input.responses);+ return resolved === undefined ? [] : [resolved];+ }),resolvedStepInput: input.resolvedStepInput,session: removePendingInputBatches(input.session, resolvedBatches),});diff --git a/packages/eve/src/harness/hitl/session-limit-input-requests.ts b/packages/eve/src/harness/hitl/session-limit-input-requests.tsindex eccc6e9e1..100605497 100644--- a/packages/eve/src/harness/hitl/session-limit-input-requests.ts+++ b/packages/eve/src/harness/hitl/session-limit-input-requests.ts@@ -1,4 +1,5 @@import type { PendingInputBatch } from "#harness/pending-input-batches.js";+import { buildResolvedInputBatch } from "#harness/input-request-resolution.js";import {getPendingInputBatches,queueDeferredStepInput,@@ -66,6 +67,9 @@ export function resolveSessionLimitInput(leftoverResponses,limitContinuation,messages,+ resolvedInputs: [buildResolvedInputBatch(input.pendingBatch, input.responses)].filter(+ (batch): batch is NonNullable<typeof batch> => batch !== undefined,+ ),resolvedStepInput: input.resolvedStepInput,session,});diff --git a/packages/eve/src/harness/input-request-resolution.ts b/packages/eve/src/harness/input-request-resolution.tsnew file mode 100644index 000000000..474caeb7e--- /dev/null+++ b/packages/eve/src/harness/input-request-resolution.ts@@ -0,0 +1,81 @@+import { isApprovalRequest } from "#harness/input-request-class.js";+import type { PendingInputBatchEvent } from "#harness/pending-input-batches.js";+import type { InputRequest, InputResponse } from "#runtime/input/types.js";++const IGNORED_INPUT_REASON = "Ignored because the user continued without responding.";+export const TOOL_EXECUTION_DENIED_MESSAGE = "Tool execution was denied.";+const TOOL_EXECUTION_INVALID_APPROVAL_MESSAGE = "Invalid approval response.";++type ApprovalTerminalStatus = "approved" | "denied" | "ignored" | "invalid";++export interface ResolvedInputBatch {+ readonly event: PendingInputBatchEvent;+ readonly inputs: readonly {+ readonly outcome: "answered" | ApprovalTerminalStatus;+ readonly request: InputRequest;+ readonly response?: InputResponse;+ }[];+}++export function buildResolvedInputBatch(+ batch: {+ readonly event?: PendingInputBatchEvent;+ readonly requests: readonly InputRequest[];+ },+ responses: readonly InputResponse[],+): ResolvedInputBatch | undefined {+ if (batch.event === undefined) return undefined;+ const responseMap = new Map(responses.map((response) => [response.requestId, response]));+ return {+ event: batch.event,+ inputs: batch.requests.map((request) => {+ const response = responseMap.get(request.requestId);+ return {+ outcome: isApprovalRequest(request)+ ? resolveApprovalOutcome(response).status+ : response === undefined+ ? "ignored"+ : "answered",+ request,+ response,+ };+ }),+ };+}++export function resolveApprovalOutcome(response: InputResponse | undefined): {+ readonly approved: boolean;+ readonly reason: string | undefined;+ readonly status: ApprovalTerminalStatus;+} {+ if (response === undefined) {+ return {+ approved: false,+ reason: IGNORED_INPUT_REASON,+ status: "ignored",+ };+ }++ if (response.optionId === "approve") {+ return {+ approved: true,+ reason: undefined,+ status: "approved",+ };+ }++ // ACP uses "deny" while harness-owned approval prompts use "cancel".+ if (response.optionId === "cancel" || response.optionId === "deny") {+ return {+ approved: false,+ reason: TOOL_EXECUTION_DENIED_MESSAGE,+ status: "denied",+ };+ }++ return {+ approved: false,+ reason: TOOL_EXECUTION_INVALID_APPROVAL_MESSAGE,+ status: "invalid",+ };+}diff --git a/packages/eve/src/harness/input-requests.test.ts b/packages/eve/src/harness/input-requests.test.tsindex af06722b8..073eea5da 100644--- a/packages/eve/src/harness/input-requests.test.ts+++ b/packages/eve/src/harness/input-requests.test.ts@@ -587,7 +587,7 @@ describe("resolvePendingInput", () => {});});- it("returns a rejected action for an explicitly denied approval", () => {+ it("returns a rejected action for an ACP denial", () => {const session = appendPendingInputBatch({event: { sequence: 5, stepIndex: 1, turnId: "turn_0" },requests: [@@ -615,7 +615,7 @@ describe("resolvePendingInput", () => {const result = resolvePendingInput({stepInput: {- inputResponses: [{ requestId: "approval-1", optionId: "cancel" }],+ inputResponses: [{ requestId: "approval-1", optionId: "deny" }],},session,});@@ -645,6 +645,18 @@ describe("resolvePendingInput", () => {],},]);+ expect(result.resolvedInputs).toMatchObject([+ {+ event: { sequence: 5, stepIndex: 1, turnId: "turn_0" },+ inputs: [+ {+ outcome: "denied",+ request: { requestId: "approval-1" },+ response: { optionId: "deny", requestId: "approval-1" },+ },+ ],+ },+ ]);});it("does not return a rejected action when an approval is granted", () => {@@ -682,6 +694,18 @@ describe("resolvePendingInput", () => {expect(result.outcome).toBe("resolved");expect(result.rejectedActions).toBeUndefined();+ expect(result.resolvedInputs).toMatchObject([+ {+ event: { sequence: 5, stepIndex: 1, turnId: "turn_0" },+ inputs: [+ {+ outcome: "approved",+ request: { requestId: "approval-1" },+ response: { optionId: "approve", requestId: "approval-1" },+ },+ ],+ },+ ]);});it("does not retain approval when a deferred response is superseded", () => {diff --git a/packages/eve/src/harness/input-requests.ts b/packages/eve/src/harness/input-requests.tsindex d63b5760a..0c0309a3c 100644--- a/packages/eve/src/harness/input-requests.ts+++ b/packages/eve/src/harness/input-requests.ts@@ -28,6 +28,7 @@ import type { HarnessSession, StepInput } from "#harness/types.js";export { getApprovedTools, clearPendingSessionLimitPrompt };export type { RejectedActionBatch };+export type { ResolvedInputBatch } from "#harness/input-request-resolution.js";export {appendPendingInputBatch,consumeDeferredStepInput,diff --git a/packages/eve/src/harness/instrumentation-dispatch.ts b/packages/eve/src/harness/instrumentation-dispatch.tsindex 67d43f4aa..5125fd738 100644--- a/packages/eve/src/harness/instrumentation-dispatch.ts+++ b/packages/eve/src/harness/instrumentation-dispatch.ts@@ -4,17 +4,25 @@ import {isInstrumentationStateAbandoned,releaseAllInstrumentationAttemptState,releaseAllInstrumentationState,+ releaseAllInstrumentationTurnState,+ takeInstrumentationActionScopes,+ type InstrumentationStateOwner,} from "#harness/instrumentation-state.js";import { createLogger, formatError } from "#internal/logging.js";import type {CreateInstrumentationHooksOptions,+ InstrumentationActionFailedEvent,InstrumentationDispatchGroups,InstrumentationEvent,InstrumentationEventHandler,InstrumentationHooks,InstrumentationHooksInput,InstrumentationProviderDefinition,+ InstrumentationSessionFailedEvent,+ InstrumentationSessionSettledEvent,+ InstrumentationTurnFailedEvent,+ InstrumentationTurnSettledEvent,} from "#harness/instrumentation-lifecycle.js";const log = createLogger("harness.instrumentation-dispatch");@@ -30,6 +38,25 @@ export function createInstrumentationDispatcher(const publish = async (event: InstrumentationEvent): Promise<void> => {const snapshot = snapshotInstrumentationEvent(event, snapshots);+ const cleanupSession =+ snapshot.type === "session.completed" || snapshot.type === "session.failed";+ const cleanupTurn = snapshot.type === "turn.cancelled" || snapshot.type === "turn.failed";+ if (cleanupSession || cleanupTurn) {+ const pendingActions = takeInstrumentationActionScopes(+ snapshot.sessionId,+ cleanupTurn ? snapshot.turnId : undefined,+ );+ const failure = terminalActionFailure(snapshot);+ for (const action of pendingActions) {+ await publish({+ ...failure,+ idempotencyKey: action.idempotencyKey,+ scope: action.scope,+ type: "action.failed",+ });+ }+ }+try {try {for (const provider of groups.serialBefore) {@@ -126,20 +153,19 @@ async function dispatchToProvider(handlerTimeoutMs: number,): Promise<void> {const startedBoundary = event.type.endsWith(".started") || event.type === "input.requested";- const attemptId = stateAttemptId(event);+ const owner = stateOwner(event);const providerName = provider.name;if (isInstrumentationStateAbandoned(providerName, event.idempotencyKey)) return;const handler = provider.events?.[event.type];if (handler === undefined) return;- const state = instrumentationStateSlot(providerName, event.idempotencyKey, attemptId);+ const state = instrumentationStateSlot(providerName, event.idempotencyKey, owner);try {const settled = await withTimeout(() => (handler as InstrumentationEventHandler<InstrumentationEvent>)(event, { state }),handlerTimeoutMs,() => {state.revoke();- if (startedBoundary)- abandonInstrumentationState(providerName, event.idempotencyKey, attemptId);+ if (startedBoundary) abandonInstrumentationState(providerName, event.idempotencyKey, owner);},);if (!settled) {@@ -181,13 +207,17 @@ async function withTimeout(}}-function stateAttemptId(event: InstrumentationEvent): string | undefined {- if (!("scope" in event)) return undefined;+/** Model and SDK tool children are scoped to an attempt; durable pairs are not. */+function stateOwner(event: InstrumentationEvent): InstrumentationStateOwner {+ if (!("scope" in event)) return {};+ if (event.type.startsWith("action.") || event.type.startsWith("input.")) {+ return { sessionId: event.scope.sessionId, turnId: event.scope.turnId };+ }return event.type.startsWith("model.call.") ||event.type.startsWith("tool.call.") ||event.type.startsWith("step.attempt.")- ? event.scope.attemptId- : undefined;+ ? { attemptId: event.scope.attemptId }+ : {};}function releaseTerminalState(event: InstrumentationEvent): void {@@ -195,6 +225,36 @@ function releaseTerminalState(event: InstrumentationEvent): void {if (event.type === "step.attempt.completed" || event.type === "step.attempt.failed") {releaseAllInstrumentationAttemptState(event.scope.attemptId);}+ if (event.type === "session.completed" || event.type === "session.failed") {+ releaseAllInstrumentationTurnState(event.sessionId);+ }+ if (event.type === "turn.cancelled" || event.type === "turn.failed") {+ releaseAllInstrumentationTurnState(event.sessionId, event.turnId);+ }+}++function terminalActionFailure(+ event:+ | InstrumentationSessionFailedEvent+ | InstrumentationSessionSettledEvent+ | InstrumentationTurnFailedEvent+ | InstrumentationTurnSettledEvent,+): Pick<InstrumentationActionFailedEvent, "error" | "errorCode" | "outcome"> {+ if (event.type === "session.failed" || event.type === "turn.failed") {+ return { error: event.error, outcome: "failed" };+ }+ if (event.type === "turn.cancelled") {+ return {+ error: new Error("The action was cancelled with its turn."),+ errorCode: "ACTION_CANCELLED",+ outcome: "cancelled",+ };+ }+ return {+ error: new Error("The session completed before the action settled."),+ errorCode: "ACTION_ABANDONED",+ outcome: "abandoned",+ };}function isTerminal(type: InstrumentationEvent["type"]): boolean {diff --git a/packages/eve/src/harness/instrumentation-lifecycle.test.ts b/packages/eve/src/harness/instrumentation-lifecycle.test.tsindex 5e0917e88..237873627 100644--- a/packages/eve/src/harness/instrumentation-lifecycle.test.ts+++ b/packages/eve/src/harness/instrumentation-lifecycle.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest";import { ContextContainer, contextStorage } from "#context/container.js";import { deserializeContext, serializeContext } from "#context/serialize.js";import {+ actionIdempotencyKey,attemptIdempotencyKey,createInstrumentationHooks,inputIdempotencyKey,@@ -14,7 +15,11 @@ import {type InstrumentationModelCallStartedEvent,type InstrumentationProviderDefinition,} from "#harness/instrumentation-lifecycle.js";-import { instrumentationStateSlot } from "#harness/instrumentation-state.js";+import {+ findInstrumentationActionScopeForCall,+ instrumentationStateSlot,+ rememberInstrumentationActionScope,+} from "#harness/instrumentation-state.js";const { logWarn } = vi.hoisted(() => ({ logWarn: vi.fn() }));vi.mock("#internal/logging.js", () => ({@@ -229,6 +234,73 @@ describe("provider state lifecycle", () => {expect(instrumentationStateSlot("removed", modelKey).get()).toBeUndefined();});});++ it("keeps action state past the originating attempt", async () => {+ const actionKey = actionIdempotencyKey(scope.sessionId, scope.turnId, "call-1");+ const hooks = createInstrumentationHooks([+ {+ events: { "action.started": (_event, ctx) => ctx.state.set("open") },+ name: "sink",+ },+ ]);+ await contextStorage.run(new ContextContainer(), async () => {+ await hooks.publish({+ callId: "call-1",+ idempotencyKey: actionKey,+ input: {},+ kind: "tool-call",+ name: "tool",+ scope,+ type: "action.started",+ });+ await hooks.publish({+ idempotencyKey: attemptIdempotencyKey(scope),+ scope,+ type: "step.attempt.completed",+ });+ expect(instrumentationStateSlot("sink", actionKey).get()).toBe("open");+ });+ });++ it("terminalizes and releases pending actions when a turn is cancelled", async () => {+ const actionKey = actionIdempotencyKey(scope.sessionId, scope.turnId, "call-1");+ const failed = vi.fn();+ const hooks = createInstrumentationHooks([+ {+ events: {+ "action.failed": failed,+ "action.started": (_event, ctx) => ctx.state.set("open"),+ },+ name: "sink",+ },+ ]);+ await contextStorage.run(new ContextContainer(), async () => {+ rememberInstrumentationActionScope(actionKey, scope);+ await hooks.publish({+ callId: "call-1",+ idempotencyKey: actionKey,+ input: {},+ kind: "tool-call",+ name: "tool",+ scope,+ type: "action.started",+ });+ await hooks.publish({+ idempotencyKey: turnIdempotencyKey(scope.sessionId, scope.turnId),+ sessionId: scope.sessionId,+ turnId: scope.turnId,+ type: "turn.cancelled",+ });+ expect(instrumentationStateSlot("sink", actionKey).get()).toBeUndefined();+ expect(findInstrumentationActionScopeForCall(scope.sessionId, "call-1")).toBeUndefined();+ });+ expect(failed).toHaveBeenCalledOnce();+ expect(failed.mock.calls[0]?.[0]).toMatchObject({+ errorCode: "ACTION_CANCELLED",+ outcome: "cancelled",+ type: "action.failed",+ });+ });});describe("provider handler deadlines", () => {diff --git a/packages/eve/src/harness/instrumentation-lifecycle.ts b/packages/eve/src/harness/instrumentation-lifecycle.tsindex bb7df010a..c8a7bd022 100644--- a/packages/eve/src/harness/instrumentation-lifecycle.ts+++ b/packages/eve/src/harness/instrumentation-lifecycle.ts@@ -77,12 +77,31 @@ export type InstrumentationContentPart =readonly toolName: string;};-/** How one tool execution ended. */-export type InstrumentationToolOutput =+/**+ * What eve dispatched an action as. The model sees every action as a tool, so+ * this is the only thing that separates a subagent or remote-agent call from an+ * ordinary tool in a trace.+ */+export type InstrumentationActionKind =+ | "load-skill"+ | "remote-agent-call"+ | "subagent-call"+ | "tool-call";++/** How one action ended. */+export type InstrumentationActionOutput =| { readonly type: "result"; readonly output: unknown }| { readonly type: "error"; readonly error: unknown };-/** Replay-stable row identity for every lifecycle operation. */+/**+ * Every event carries an `idempotencyKey` naming the operation it is about: a+ * start and its terminal share one, and two operations never collide.+ *+ * Every part is identity eve reconstructs on replay — session and turn ids,+ * `scope.attemptId` (itself `session:turn:step:attempt`), AI SDK step number,+ * and durable runtime-action call ids. A provider writing rows can use the key+ * as its row id and be idempotent by construction.+ */export function sessionIdempotencyKey(sessionId: string): string {return `session:${sessionId}`;}@@ -172,6 +191,11 @@ export interface InstrumentationInputResolvedEvent {readonly scope: InstrumentationAttemptScope;}+/** Runtime action call IDs are durable and unique within one session. */+export function actionIdempotencyKey(sessionId: string, turnId: string, callId: string): string {+ return `action:${sessionId}:${turnId}:${callId}`;+}+export interface InstrumentationStepAttemptStartedEvent {readonly type: "step.attempt.started";readonly idempotencyKey: string;@@ -243,6 +267,13 @@ export interface InstrumentationTurnStartedEvent {readonly turnId: string;}+/**+ * A turn that ended without a failure.+ *+ * `turn.cancelled` sits here rather than with the failed shape because+ * cancellation is not an error: the harness settles a cancelled turn as+ * `turn.cancelled` → `session.waiting`, with no failure surfaced anywhere.+ */export interface InstrumentationTurnSettledEvent {readonly type: "turn.cancelled" | "turn.completed";readonly idempotencyKey: string;@@ -319,6 +350,8 @@ export type InstrumentationModelCallTerminalEvent =| InstrumentationModelCallCompletedEvent| InstrumentationModelCallFailedEvent;+export type InstrumentationToolOutput = InstrumentationActionOutput;+export interface InstrumentationToolCallStartedEvent {readonly type: "tool.call.started";readonly callId: string;@@ -346,14 +379,63 @@ export type InstrumentationToolCallTerminalEvent =| InstrumentationToolCallCompletedEvent| InstrumentationToolCallFailedEvent;+/**+ * One thing the agent did on the model's behalf. `kind` is what separates a+ * subagent or remote-agent call from an ordinary tool; `name` is the name the+ * model called, which is the tool name for every kind.+ */+export interface InstrumentationActionStartedEvent {+ readonly type: "action.started";+ readonly callId: string;+ readonly idempotencyKey: string;+ readonly input: unknown;+ readonly kind: InstrumentationActionKind;+ readonly name: string;+ readonly scope: InstrumentationAttemptScope;+}++export type InstrumentationActionOutcome =+ | "abandoned"+ | "cancelled"+ | "completed"+ | "failed"+ | "rejected";++export interface InstrumentationActionCompletedEvent {+ readonly type: "action.completed";+ readonly acceptedAtMs?: number;+ readonly idempotencyKey: string;+ readonly outcome: "completed";+ readonly output: InstrumentationActionOutput;+ readonly scope: InstrumentationAttemptScope;+ readonly usage?: InstrumentationUsage;+}++export interface InstrumentationActionFailedEvent {+ readonly type: "action.failed";+ readonly acceptedAtMs?: number;+ readonly error: unknown;+ readonly errorCode?: string;+ readonly idempotencyKey: string;+ readonly outcome: Exclude<InstrumentationActionOutcome, "completed">;+ readonly scope: InstrumentationAttemptScope;+}++export type InstrumentationActionTerminalEvent =+ | InstrumentationActionCompletedEvent+ | InstrumentationActionFailedEvent;++/** The second argument to every handler. */export interface InstrumentationHandlerContext {+ /** Durable state scoped to this provider and this operation. */readonly state: InstrumentationStateSlot;}/*** The AI SDK can omit a model terminal when an incomplete stream closes. A- * provider that correlates starts with terminals must scope that state to the- * attempt and release anything still open when the step attempt terminates.+ * handler can use `ctx.state` for durable correlation when a terminal arrives,+ * but providers must scope live resources to the attempt and release anything+ * still open when the step attempt terminates.*/export type InstrumentationEventHandler<TEvent> = (event: TEvent,@@ -377,6 +459,9 @@ export interface InstrumentationProviderDefinition {readonly "session.failed"?: InstrumentationEventHandler<InstrumentationSessionFailedEvent>;readonly "session.started"?: InstrumentationEventHandler<InstrumentationSessionStartedEvent>;readonly "session.waiting"?: InstrumentationEventHandler<InstrumentationSessionSettledEvent>;+ readonly "action.started"?: InstrumentationEventHandler<InstrumentationActionStartedEvent>;+ readonly "action.completed"?: InstrumentationEventHandler<InstrumentationActionCompletedEvent>;+ readonly "action.failed"?: InstrumentationEventHandler<InstrumentationActionFailedEvent>;readonly "tool.call.started"?: InstrumentationEventHandler<InstrumentationToolCallStartedEvent>;readonly "tool.call.completed"?: InstrumentationEventHandler<InstrumentationToolCallCompletedEvent>;readonly "tool.call.failed"?: InstrumentationEventHandler<InstrumentationToolCallFailedEvent>;@@ -385,7 +470,9 @@ export interface InstrumentationProviderDefinition {readonly "turn.failed"?: InstrumentationEventHandler<InstrumentationTurnFailedEvent>;readonly "turn.started"?: InstrumentationEventHandler<InstrumentationTurnStartedEvent>;};+ /** Drains anything buffered. Driven by the runtime, not by the bus. */readonly flush?: () => void | PromiseLike<void>;+ /** Releases resources when the process is going away. */readonly shutdown?: () => void | PromiseLike<void>;}@@ -407,6 +494,8 @@ export type InstrumentationHooksInput =export type InstrumentationCorrelatedEvent =| InstrumentationInputRequestedEvent| InstrumentationInputResolvedEvent+ | InstrumentationActionStartedEvent+ | InstrumentationActionTerminalEvent| InstrumentationModelCallStartedEvent| InstrumentationModelCallTerminalEvent| InstrumentationToolCallStartedEvent@@ -434,12 +523,12 @@ export type InstrumentationExecutionOperation =| {readonly idempotencyKey: string;readonly scope: InstrumentationAttemptScope;- readonly type: "model.call";+ readonly type: "tool.call";}| {readonly idempotencyKey: string;readonly scope: InstrumentationAttemptScope;- readonly type: "tool.call";+ readonly type: "model.call";};/** Provider-neutral hook operations consumed by the AI SDK bridge. */diff --git a/packages/eve/src/harness/instrumentation-native-events.test.ts b/packages/eve/src/harness/instrumentation-native-events.test.tsindex 6c883a5e7..afa99f2fd 100644--- a/packages/eve/src/harness/instrumentation-native-events.test.ts+++ b/packages/eve/src/harness/instrumentation-native-events.test.ts@@ -1,6 +1,11 @@import { describe, expect, it } from "vitest";+import { ContextContainer, contextStorage } from "#context/container.js";+import { deserializeContext, serializeContext } from "#context/serialize.js";import {+ createActionResultEvent,+ createActionsRequestedEvent,+ createInputRequestedEvent,createSessionStartedEvent,createSessionWaitingEvent,createStepCompletedEvent,@@ -8,8 +13,18 @@ import {createTurnCompletedEvent,createTurnStartedEvent,} from "#protocol/message.js";-import { createInstrumentationHandleEvent } from "#harness/instrumentation-native-events.js";+import {+ createInstrumentationHandleEvent,+ publishInputResolutions,+} from "#harness/instrumentation-native-events.js";import type { InstrumentationHooks } from "#harness/instrumentation-lifecycle.js";+import {+ actionIdempotencyKey,+ inputIdempotencyKey,+ sessionIdempotencyKey,+ turnIdempotencyKey,+} from "#harness/instrumentation-lifecycle.js";+import { RuntimeActionSettlementTimesKey } from "#harness/runtime-action-settlement-state.js";describe("createInstrumentationHandleEvent", () => {it("publishes native lifecycle transitions after durable handling", async () => {@@ -91,7 +106,7 @@ describe("createInstrumentationHandleEvent", () => {expect(events).toEqual([{- idempotencyKey: "session:session-1",+ idempotencyKey: sessionIdempotencyKey("session-1"),sessionId: "session-1",turnId: "turn-1",type: "session.waiting",@@ -124,7 +139,7 @@ describe("createInstrumentationHandleEvent", () => {expect(events.filter((event) => event.type === "turn.started")).toEqual([{- idempotencyKey: "turn:child-1:child-turn-1",+ idempotencyKey: turnIdempotencyKey("child-1", "child-turn-1"),parentLineage,parentTraceContext: undefined,rootSessionId: "session-1",@@ -134,7 +149,7 @@ describe("createInstrumentationHandleEvent", () => {type: "turn.started",},{- idempotencyKey: "turn:child-1:child-turn-2",+ idempotencyKey: turnIdempotencyKey("child-1", "child-turn-2"),parentLineage,parentTraceContext: undefined,rootSessionId: "session-1",@@ -145,4 +160,281 @@ describe("createInstrumentationHandleEvent", () => {},]);});+ it("publishes every runtime action and settles it in a replacement worker", async () => {+ const events: unknown[] = [];+ const scope = {+ attemptId: "session-1:turn-1:0:0",+ attemptIndex: 0,+ sessionId: "session-1",+ stepIndex: 0,+ turnId: "turn-1",+ };+ const context = new ContextContainer();+ const requested = createActionsRequestedEvent({+ actions: [+ {+ callId: "delegate-1",+ description: "Delegate work.",+ input: { task: "research" },+ kind: "subagent-call",+ name: "delegate",+ nodeId: "workers",+ subagentName: "worker",+ },+ { callId: "skill-1", input: { name: "research" }, kind: "load-skill" },+ {+ callId: "remote-1",+ description: "Call a remote agent.",+ input: { task: "analyze" },+ kind: "remote-agent-call",+ name: "remote",+ nodeId: "remote-agents",+ remoteAgentName: "analyst",+ },+ { callId: "add-1", input: { a: 1, b: 2 }, kind: "tool-call", toolName: "add" },+ ],+ sequence: 0,+ stepIndex: 0,+ turnId: "turn-1",+ });++ await contextStorage.run(context, async () => {+ const handleEvent = createInstrumentationHandleEvent({+ getAttemptScope: () => scope,+ handleEvent: async () => {},+ hooks: { publish: async (event) => void events.push(event) },+ sessionId: "session-1",+ })!;+ await handleEvent(requested);+ await handleEvent(requested);+ });++ const restored = await deserializeContext(await serializeContext(context));+ await contextStorage.run(restored, async () => {+ restored.set(RuntimeActionSettlementTimesKey, { "remote-1": 1_234 });+ const handleEvent = createInstrumentationHandleEvent({+ handleEvent: async () => {},+ hooks: { publish: async (event) => void events.push(event) },+ sessionId: "session-1",+ })!;+ await handleEvent(+ createActionResultEvent({+ result: {+ callId: "delegate-1",+ kind: "subagent-result",+ origin: "dispatch",+ output: "unavailable",+ isError: true,+ subagentName: "worker",+ },+ sequence: 0,+ stepIndex: 0,+ turnId: "turn-2",+ }),+ );+ await handleEvent(+ createActionResultEvent({+ result: {+ callId: "remote-1",+ kind: "subagent-result",+ origin: "child",+ outcome: {+ kind: "terminal",+ result: { kind: "succeeded", output: "done" },+ usageDelta: {+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ inputTokens: 0,+ outputTokens: 0,+ },+ },+ output: "done",+ subagentName: "analyst",+ usage: {+ cacheReadTokens: 3,+ cacheWriteTokens: 4,+ inputTokens: 10,+ outputTokens: 5,+ },+ },+ sequence: 0,+ stepIndex: 0,+ turnId: "turn-2",+ }),+ );+ await handleEvent(+ createActionResultEvent({+ result: {+ callId: "add-1",+ kind: "tool-result",+ output: 3,+ toolName: "add",+ },+ sequence: 0,+ stepIndex: 0,+ turnId: "turn-2",+ }),+ );+ });++ expect(events.slice(0, 4)).toEqual([+ {+ callId: "delegate-1",+ idempotencyKey: actionIdempotencyKey("session-1", "turn-1", "delegate-1"),+ input: { task: "research" },+ kind: "subagent-call",+ name: "delegate",+ scope,+ type: "action.started",+ },+ {+ callId: "skill-1",+ idempotencyKey: actionIdempotencyKey("session-1", "turn-1", "skill-1"),+ input: { name: "research" },+ kind: "load-skill",+ name: "load_skill",+ scope,+ type: "action.started",+ },+ {+ callId: "remote-1",+ idempotencyKey: actionIdempotencyKey("session-1", "turn-1", "remote-1"),+ input: { task: "analyze" },+ kind: "remote-agent-call",+ name: "remote",+ scope,+ type: "action.started",+ },+ {+ callId: "add-1",+ idempotencyKey: actionIdempotencyKey("session-1", "turn-1", "add-1"),+ input: { a: 1, b: 2 },+ kind: "tool-call",+ name: "add",+ scope,+ type: "action.started",+ },+ ]);+ expect(events[4]).toMatchObject({+ errorCode: "ACTION_RESULT_FAILED",+ idempotencyKey: actionIdempotencyKey("session-1", "turn-1", "delegate-1"),+ outcome: "failed",+ scope,+ type: "action.failed",+ });+ expect(events[5]).toEqual({+ acceptedAtMs: 1_234,+ idempotencyKey: actionIdempotencyKey("session-1", "turn-1", "remote-1"),+ outcome: "completed",+ output: { output: "done", type: "result" },+ scope,+ type: "action.completed",+ usage: {+ inputTokenDetails: { cacheReadTokens: 3, cacheWriteTokens: 4 },+ inputTokens: 10,+ outputTokens: 5,+ },+ });+ expect(events[6]).toEqual({+ acceptedAtMs: undefined,+ idempotencyKey: actionIdempotencyKey("session-1", "turn-1", "add-1"),+ outcome: "completed",+ output: { output: 3, type: "result" },+ scope,+ type: "action.completed",+ usage: undefined,+ });+ expect(events).toHaveLength(7);+ expect(events.every(Object.isFrozen)).toBe(true);+ });++ it("publishes each input request and resolves it in a replacement worker", async () => {+ const events: unknown[] = [];+ const scope = {+ attemptId: "session-1:turn-1:0:0",+ attemptIndex: 0,+ sessionId: "session-1",+ stepIndex: 0,+ turnId: "turn-1",+ };+ const request = {+ action: {+ callId: "call-1",+ input: { city: "SF" },+ kind: "tool-call" as const,+ toolName: "weather",+ },+ display: "confirmation" as const,+ kind: "tool-approval" as const,+ options: [+ { id: "approve", label: "Approve" },+ { id: "deny", label: "Deny", style: "danger" as const },+ ],+ prompt: "Approve weather?",+ requestId: "request-1",+ };+ const requested = createInputRequestedEvent({+ requests: [request],+ sequence: 0,+ stepIndex: 0,+ turnId: "turn-1",+ });+ const context = new ContextContainer();+ await contextStorage.run(context, async () => {+ const handleEvent = createInstrumentationHandleEvent({+ getAttemptScope: () => scope,+ handleEvent: async () => {},+ hooks: { publish: async (event) => void events.push(event) },+ sessionId: "session-1",+ })!;+ await handleEvent(requested);+ await handleEvent(requested);+ });++ const restored = await deserializeContext(await serializeContext(context));+ await contextStorage.run(restored, () =>+ publishInputResolutions({+ batch: {+ event: { sequence: 0, stepIndex: 0, turnId: "turn-1" },+ inputs: [+ {+ outcome: "approved",+ request,+ response: { optionId: "approve", requestId: "request-1" },+ },+ ],+ },+ hooks: { publish: async (event) => void events.push(event) },+ sessionId: "session-1",+ }),+ );++ const idempotencyKey = inputIdempotencyKey("session-1", "turn-1", "request-1");+ expect(events).toEqual([+ {+ action: { callId: "call-1", name: "weather" },+ idempotencyKey,+ kind: "tool-approval",+ request: {+ allowFreeform: undefined,+ display: "confirmation",+ options: request.options,+ prompt: "Approve weather?",+ },+ requestId: "request-1",+ scope,+ type: "input.requested",+ },+ {+ idempotencyKey,+ kind: "tool-approval",+ outcome: "approved",+ requestId: "request-1",+ response: { optionId: "approve", text: undefined },+ scope,+ type: "input.resolved",+ },+ ]);+ expect(events.every(Object.isFrozen)).toBe(true);+ });});diff --git a/packages/eve/src/harness/instrumentation-native-events.ts b/packages/eve/src/harness/instrumentation-native-events.tsindex 9d0de169c..bfe369b6e 100644--- a/packages/eve/src/harness/instrumentation-native-events.ts+++ b/packages/eve/src/harness/instrumentation-native-events.ts@@ -1,15 +1,37 @@import type { UnstampedMessageStreamEvent } from "#protocol/message.js";+import { contextStorage } from "#context/container.js";import type {+ InstrumentationActionFailedEvent,+ InstrumentationActionStartedEvent,+ InstrumentationAttemptScope,InstrumentationHooks,+ InstrumentationInputRequestedEvent,+ InstrumentationInputResolvedEvent,InstrumentationParentLineage,InstrumentationPointEvent,InstrumentationTraceContext,+ InstrumentationUsage,} from "#harness/instrumentation-lifecycle.js";-import { sessionIdempotencyKey, turnIdempotencyKey } from "#harness/instrumentation-lifecycle.js";+import {+ actionIdempotencyKey,+ inputIdempotencyKey,+ sessionIdempotencyKey,+ turnIdempotencyKey,+} from "#harness/instrumentation-lifecycle.js";+import {+ rememberInstrumentationActionScope,+ rememberInstrumentationInputScope,+ takeInstrumentationActionScopeForCall,+ takeInstrumentationInputScope,+} from "#harness/instrumentation-state.js";+import type { ResolvedInputBatch } from "#harness/input-requests.js";+import { RuntimeActionSettlementTimesKey } from "#harness/runtime-action-settlement-state.js";import type { HandleEventFn } from "#harness/types.js";+import type { RuntimeActionRequest, RuntimeActionResult } from "#runtime/actions/types.js";export interface CreateInstrumentationHandleEventInput {readonly agentName?: string;+ readonly getAttemptScope?: () => InstrumentationAttemptScope | undefined;readonly handleEvent?: HandleEventFn;readonly hooks?: InstrumentationHooks;readonly parentLineage?: InstrumentationParentLineage;@@ -29,14 +51,197 @@ export function createInstrumentationHandleEvent(const handleEvent = input.handleEvent;const hooks = input.hooks;let activeTurnId = input.turnId;+ const publishedActions = new Set<string>();+ const publishedInputs = new Set<string>();return async (event, messages) => {await handleEvent(event, messages);const lifecycleEvent = toLifecycleEvent(event, input, activeTurnId);if (event.type === "turn.started") activeTurnId = event.data.turnId;if (lifecycleEvent !== undefined) await hooks.publish(lifecycleEvent);+ if (event.type === "actions.requested") {+ await publishActionStarts(event, input, hooks, publishedActions);+ } else if (event.type === "action.result") {+ await publishActionTerminal(event, input, hooks);+ } else if (event.type === "input.requested") {+ await publishInputStarts(event, input, hooks, publishedInputs);+ }};}+async function publishInputStarts(+ event: Extract<UnstampedMessageStreamEvent, { type: "input.requested" }>,+ input: CreateInstrumentationHandleEventInput,+ hooks: InstrumentationHooks,+ published: Set<string>,+): Promise<void> {+ const scope = input.getAttemptScope?.();+ if (scope === undefined) return;++ for (const request of event.data.requests) {+ const idempotencyKey = inputIdempotencyKey(+ input.sessionId,+ event.data.turnId,+ request.requestId,+ );+ if (published.has(idempotencyKey)) continue;+ published.add(idempotencyKey);+ rememberInstrumentationInputScope(idempotencyKey, scope);+ await hooks.publish(+ Object.freeze({+ action: Object.freeze({+ callId: request.action.callId,+ name: request.action.toolName,+ }),+ idempotencyKey,+ kind: request.kind,+ request: Object.freeze({+ allowFreeform: request.allowFreeform,+ display: request.display,+ options: request.options,+ prompt: request.prompt,+ }),+ requestId: request.requestId,+ scope,+ type: "input.requested",+ } satisfies InstrumentationInputRequestedEvent),+ );+ }+}++/** Publishes accepted input resolutions against their original request scope. */+export async function publishInputResolutions(input: {+ readonly batch: ResolvedInputBatch;+ readonly hooks: InstrumentationHooks;+ readonly sessionId: string;+}): Promise<void> {+ for (const resolved of input.batch.inputs) {+ const idempotencyKey = inputIdempotencyKey(+ input.sessionId,+ input.batch.event.turnId,+ resolved.request.requestId,+ );+ const scope = takeInstrumentationInputScope(idempotencyKey);+ if (scope === undefined) continue;+ await input.hooks.publish(+ Object.freeze({+ idempotencyKey,+ kind: resolved.request.kind,+ outcome: resolved.outcome,+ requestId: resolved.request.requestId,+ response:+ resolved.response === undefined+ ? undefined+ : Object.freeze({+ optionId: resolved.response.optionId,+ text: resolved.response.text,+ }),+ scope,+ type: "input.resolved",+ } satisfies InstrumentationInputResolvedEvent),+ );+ }+}++async function publishActionStarts(+ event: Extract<UnstampedMessageStreamEvent, { type: "actions.requested" }>,+ input: CreateInstrumentationHandleEventInput,+ hooks: InstrumentationHooks,+ published: Set<string>,+): Promise<void> {+ const scope = input.getAttemptScope?.();+ if (scope === undefined) return;++ for (const action of event.data.actions) {+ const idempotencyKey = actionIdempotencyKey(input.sessionId, event.data.turnId, action.callId);+ if (published.has(idempotencyKey)) continue;+ published.add(idempotencyKey);+ rememberInstrumentationActionScope(idempotencyKey, scope);+ await hooks.publish(+ Object.freeze({+ callId: action.callId,+ idempotencyKey,+ input: action.input,+ kind: action.kind,+ name: actionName(action),+ scope,+ type: "action.started",+ } satisfies InstrumentationActionStartedEvent),+ );+ }+}++async function publishActionTerminal(+ event: Extract<UnstampedMessageStreamEvent, { type: "action.result" }>,+ input: CreateInstrumentationHandleEventInput,+ hooks: InstrumentationHooks,+): Promise<void> {+ const correlation = takeInstrumentationActionScopeForCall(+ input.sessionId,+ event.data.result.callId,+ );+ if (correlation === undefined) return;+ const { idempotencyKey, scope } = correlation;++ if (event.data.status === "completed") {+ await hooks.publish(+ Object.freeze({+ acceptedAtMs: contextStorage.getStore()?.get(RuntimeActionSettlementTimesKey)?.[+ event.data.result.callId+ ],+ idempotencyKey,+ outcome: "completed",+ output: Object.freeze({ output: event.data.result.output, type: "result" }),+ scope,+ type: "action.completed",+ usage: actionUsage(event.data.result),+ }),+ );+ return;+ }++ const error =+ event.data.error === undefined+ ? event.data.result.output+ : Object.assign(new Error(event.data.error.message), { code: event.data.error.code });+ await hooks.publish(+ Object.freeze({+ acceptedAtMs: contextStorage.getStore()?.get(RuntimeActionSettlementTimesKey)?.[+ event.data.result.callId+ ],+ error,+ errorCode: event.data.error?.code,+ idempotencyKey,+ outcome: event.data.status,+ scope,+ type: "action.failed",+ } satisfies InstrumentationActionFailedEvent),+ );+}++function actionUsage(result: RuntimeActionResult): InstrumentationUsage | undefined {+ if (+ result.kind !== "subagent-result" ||+ result.origin !== "child" ||+ result.usage === undefined+ ) {+ return undefined;+ }+ return {+ inputTokenDetails: {+ cacheReadTokens: result.usage.cacheReadTokens,+ cacheWriteTokens: result.usage.cacheWriteTokens,+ },+ inputTokens: result.usage.inputTokens,+ outputTokens: result.usage.outputTokens,+ };+}++function actionName(action: RuntimeActionRequest): string {+ if (action.kind === "tool-call") return action.toolName;+ if (action.kind === "load-skill") return "load_skill";+ return action.name;+}+function toLifecycleEvent(event: UnstampedMessageStreamEvent,input: CreateInstrumentationHandleEventInput,diff --git a/packages/eve/src/harness/instrumentation-state.test.ts b/packages/eve/src/harness/instrumentation-state.test.tsindex 5659fbd5b..3b13dc245 100644--- a/packages/eve/src/harness/instrumentation-state.test.ts+++ b/packages/eve/src/harness/instrumentation-state.test.ts@@ -2,20 +2,28 @@ import { describe, expect, it } from "vitest";import { ContextContainer, contextStorage } from "#context/container.js";import { deserializeContext, serializeContext } from "#context/serialize.js";+import {+ actionIdempotencyKey,+ type InstrumentationAttemptScope,+} from "#harness/instrumentation-lifecycle.js";import {abandonInstrumentationState,instrumentationStateSlot,isInstrumentationStateAbandoned,preserveSerializedInstrumentationState,+ rememberInstrumentationActionScope,releaseAllInstrumentationAttemptState,releaseAllInstrumentationState,+ takeInstrumentationActionScopeForCall,} from "#harness/instrumentation-state.js";describe("instrumentation state", () => {it("survives a serialized step boundary", async () => {const context = new ContextContainer();contextStorage.run(context, () => {- instrumentationStateSlot("sink", "model:1", "attempt-1").set({ rowId: "row-1" });+ instrumentationStateSlot("sink", "model:1", { attemptId: "attempt-1" }).set({+ rowId: "row-1",+ });});const restored = await deserializeContext(await serializeContext(context));contextStorage.run(restored, () => {@@ -34,6 +42,37 @@ describe("instrumentation state", () => {});});+ it("correlates same-turn actions with their stored attempt scopes", () => {+ const first: InstrumentationAttemptScope = {+ attemptId: "session-1:turn-1:0:0",+ attemptIndex: 0,+ sessionId: "session-1",+ stepIndex: 0,+ turnId: "turn-1",+ };+ const second: InstrumentationAttemptScope = {+ ...first,+ attemptId: "session-1:turn-1:1:0",+ stepIndex: 1,+ };+ const firstKey = actionIdempotencyKey(first.sessionId, first.turnId, "call-1");+ const secondKey = actionIdempotencyKey(second.sessionId, second.turnId, "call-2");++ contextStorage.run(new ContextContainer(), () => {+ rememberInstrumentationActionScope(firstKey, first);+ rememberInstrumentationActionScope(secondKey, second);++ expect(takeInstrumentationActionScopeForCall(second.sessionId, "call-2")).toEqual({+ idempotencyKey: secondKey,+ scope: second,+ });+ expect(takeInstrumentationActionScopeForCall(first.sessionId, "call-1")).toEqual({+ idempotencyKey: firstKey,+ scope: first,+ });+ });+ });+it("rejects values that cannot survive serialization", () => {contextStorage.run(new ContextContainer(), () => {expect(() => instrumentationStateSlot("sink", "turn:1").set(new Date() as never)).toThrow(@@ -72,8 +111,8 @@ describe("instrumentation state", () => {it("releases exact and attempt-owned state", () => {contextStorage.run(new ContextContainer(), () => {- instrumentationStateSlot("sink", "model:1", "attempt-1").set("one");- instrumentationStateSlot("sink", "model:2", "attempt-2").set("two");+ instrumentationStateSlot("sink", "model:1", { attemptId: "attempt-1" }).set("one");+ instrumentationStateSlot("sink", "model:2", { attemptId: "attempt-2" }).set("two");releaseAllInstrumentationState("model:2");releaseAllInstrumentationAttemptState("attempt-1");expect(instrumentationStateSlot("sink", "model:1").get()).toBeUndefined();@@ -96,7 +135,7 @@ describe("instrumentation state", () => {it("persists abandonment across serialization", async () => {const context = new ContextContainer();contextStorage.run(context, () => {- abandonInstrumentationState("sink", "model:1", "attempt-1");+ abandonInstrumentationState("sink", "model:1", { attemptId: "attempt-1" });});const restored = await deserializeContext(await serializeContext(context));contextStorage.run(restored, () => {diff --git a/packages/eve/src/harness/instrumentation-state.ts b/packages/eve/src/harness/instrumentation-state.tsindex 18ee462f3..3ea17a7be 100644--- a/packages/eve/src/harness/instrumentation-state.ts+++ b/packages/eve/src/harness/instrumentation-state.ts@@ -1,15 +1,37 @@import { contextStorage, loadContext } from "#context/container.js";import { ContextKey } from "#context/key.js";import { type JsonValue, parseJsonValue } from "#shared/json.js";+import type { InstrumentationAttemptScope } from "#harness/instrumentation-lifecycle.js";+/**+ * What every provider has staged, flattened into one durable slot.+ *+ * Flat rather than nested by provider, because every read and write is already+ * scoped to a single `(provider, operation)` pair — nesting would buy a grouping+ * nothing asks for and make releasing one operation a two-level rewrite.+ */interface InstrumentationStateRecord {abandoned?: true;attemptId?: string;+ sessionId?: string;+ turnId?: string;value?: JsonValue;}+export interface InstrumentationStateOwner {+ readonly attemptId?: string;+ readonly sessionId?: string;+ readonly turnId?: string;+}+type InstrumentationStateMap = Readonly<Record<string, InstrumentationStateRecord>>;+type InstrumentationScopeMap = Readonly<Record<string, InstrumentationAttemptScope>>;+/**+ * Provider state lives in serialized Workflow context, not in the harness, so a+ * value staged by `action.started` in one process is still there when+ * `action.completed` runs in another.+ */const InstrumentationStateKey = new ContextKey<InstrumentationStateMap>("eve.harness.instrumentationState",{@@ -20,29 +42,75 @@ const InstrumentationStateKey = new ContextKey<InstrumentationStateMap>(},);-/** Keeps provider state from an interrupted step's discarded context changes. */+const InstrumentationActionScopeKey = new ContextKey<InstrumentationScopeMap>(+ "eve.harness.instrumentationActionScopes",+ {+ codec: {+ deserialize: deserializeScopes,+ serialize: (state) => state,+ },+ },+);++const InstrumentationInputScopeKey = new ContextKey<InstrumentationScopeMap>(+ "eve.harness.instrumentationInputScopes",+ {+ codec: {+ deserialize: deserializeScopes,+ serialize: (state) => state,+ },+ },+);++/**+ * Keeps provider state from an interrupted step's context changes.+ *+ * A cancelled step's context writes are discarded wholesale. Provider state has+ * to be an exception for the same reason eve's own trace state is: the+ * cancellation epilogue still publishes `turn.cancelled`, and a provider that+ * staged something at the start of the operation being cancelled needs it there+ * to close cleanly. Without this, the terminal arrives with an empty slot and+ * whatever the provider opened is never closed.+ */export function preserveSerializedInstrumentationState(original: Record<string, unknown>,interrupted: Record<string, unknown>,): Record<string, unknown> {- const state = interrupted[InstrumentationStateKey.name];- return state === undefined ? original : { ...original, [InstrumentationStateKey.name]: state };+ let preserved = original;+ for (const key of [+ InstrumentationStateKey,+ InstrumentationActionScopeKey,+ InstrumentationInputScopeKey,+ ]) {+ const state = interrupted[key.name];+ if (state !== undefined) preserved = { ...preserved, [key.name]: state };+ }+ return preserved;}+/** One provider's view of its own state for one operation. */export interface InstrumentationStateSlot {get(): JsonValue | undefined;+ /** Stages a value; `undefined` releases the slot. */set(value: JsonValue | undefined): void;}export interface InstrumentationStateLease extends InstrumentationStateSlot {+ /** Makes later reads empty and writes no-ops. */revoke(): void;}-/** One provider's durable state for one operation. */+/**+ * Scopes state to one provider and one operation.+ *+ * Two providers handling the same event get separate slots, and the same+ * provider gets a separate slot per operation, so neither can read or clobber+ * the other's.+ */export function instrumentationStateSlot(provider: string,idempotencyKey: string,- attemptId?: string,+ owner: InstrumentationStateOwner = {},): InstrumentationStateLease {const key = stateKey(provider, idempotencyKey);let active = true;@@ -56,34 +124,39 @@ export function instrumentationStateSlot(active = false;},set: (value) => {- if (!active || contextStorage.getStore() === undefined) return;- if (value === undefined) {- writeState((state) => writeSlot(state, key, undefined));- return;- }- const record: InstrumentationStateRecord = {- value: cloneAndFreezeJson(parseJsonValue(value)),- };- const current = contextStorage.getStore()?.get(InstrumentationStateKey)?.[key];- if (current?.abandoned === true) record.abandoned = true;- if (attemptId !== undefined) record.attemptId = attemptId;- writeState((state) => writeSlot(state, key, record));+ if (!active) return;+ // Reject a lossy value here rather than at the step boundary, where the+ // throw would be attributed to serialization instead of to the handler+ // that wrote it.+ const staged = value === undefined ? undefined : cloneAndFreezeJson(parseJsonValue(value));+ writeInstrumentationState((state) => {+ if (staged === undefined) return writeSlot(state, key, undefined);+ const current = state[key];+ const record: InstrumentationStateRecord = { value: staged };+ if (current?.abandoned === true) record.abandoned = true;+ assignOwner(record, owner);+ return writeSlot(state, key, record);+ });},};}+/** Persists that a provider's start handler timed out for this operation. */export function abandonInstrumentationState(provider: string,idempotencyKey: string,- attemptId?: string,+ owner: InstrumentationStateOwner = {},): void {- if (contextStorage.getStore() === undefined) return;const key = stateKey(provider, idempotencyKey);- writeState((state) => {+ writeInstrumentationState((state) => {const current = state[key];+ const resolvedOwner = {+ attemptId: owner.attemptId ?? current?.attemptId,+ sessionId: owner.sessionId ?? current?.sessionId,+ turnId: owner.turnId ?? current?.turnId,+ };const record: InstrumentationStateRecord = { abandoned: true };- const owner = attemptId ?? current?.attemptId;- if (owner !== undefined) record.attemptId = owner;+ assignOwner(record, resolvedOwner);if (current?.value !== undefined) record.value = current.value;return writeSlot(state, key, record);});@@ -107,6 +180,13 @@ export function releaseAllInstrumentationAttemptState(attemptId: string): void {releaseMatchingInstrumentationState((_key, record) => record.attemptId === attemptId);}+export function releaseAllInstrumentationTurnState(sessionId: string, turnId?: string): void {+ releaseMatchingInstrumentationState(+ (_key, record) =>+ record.sessionId === sessionId && (turnId === undefined || record.turnId === turnId),+ );+}+function releaseMatchingInstrumentationState(matches: (key: string, record: InstrumentationStateRecord) => boolean,): void {@@ -117,7 +197,7 @@ function releaseMatchingInstrumentationState() {return;}- writeState((state) => {+ writeInstrumentationState((state) => {const next = { ...state };for (const [key, record] of Object.entries(state)) {if (matches(key, record)) delete next[key];@@ -126,8 +206,97 @@ function releaseMatchingInstrumentationState(});}-function writeState(update: (state: InstrumentationStateMap) => InstrumentationStateMap): void {- loadContext().set(InstrumentationStateKey, (state) => update(state ?? {}));+/** Remembers where a durable runtime action originated. */+export function rememberInstrumentationActionScope(+ idempotencyKey: string,+ scope: InstrumentationAttemptScope,+): void {+ writeContextKey(InstrumentationActionScopeKey, (state) => ({+ ...state,+ [idempotencyKey]: scope,+ }));+}++/** Remembers where a durable input request originated. */+export function rememberInstrumentationInputScope(+ idempotencyKey: string,+ scope: InstrumentationAttemptScope,+): void {+ writeContextKey(InstrumentationInputScopeKey, (state) => ({+ ...state,+ [idempotencyKey]: scope,+ }));+}++/** Reads and releases one durable input request's originating scope. */+export function takeInstrumentationInputScope(+ idempotencyKey: string,+): InstrumentationAttemptScope | undefined {+ const scope = contextStorage.getStore()?.get(InstrumentationInputScopeKey)?.[idempotencyKey];+ if (scope === undefined) return undefined;+ writeContextKey(InstrumentationInputScopeKey, (state) => {+ const next = { ...state };+ delete next[idempotencyKey];+ return next;+ });+ return scope;+}++export interface InstrumentationActionCorrelation {+ readonly idempotencyKey: string;+ readonly scope: InstrumentationAttemptScope;+}++export function findInstrumentationActionScopeForCall(+ sessionId: string,+ callId: string,+): InstrumentationActionCorrelation | undefined {+ const scopes = contextStorage.getStore()?.get(InstrumentationActionScopeKey);+ if (scopes === undefined) return undefined;+ for (const candidate of Object.values(scopes)) {+ const idempotencyKey = `action:${sessionId}:${candidate.turnId}:${callId}`;+ const scope = scopes[idempotencyKey];+ if (scope !== undefined) return { idempotencyKey, scope };+ }+ return undefined;+}++/** Reads and releases one durable runtime action's originating scope. */+export function takeInstrumentationActionScopeForCall(+ sessionId: string,+ callId: string,+): InstrumentationActionCorrelation | undefined {+ const correlation = findInstrumentationActionScopeForCall(sessionId, callId);+ if (correlation === undefined) return undefined;+ writeContextKey(InstrumentationActionScopeKey, (state) => {+ const next = { ...state };+ delete next[correlation.idempotencyKey];+ return next;+ });+ return correlation;+}++/** Takes every still-open action owned by one session or turn. */+export function takeInstrumentationActionScopes(+ sessionId: string,+ turnId?: string,+): readonly InstrumentationActionCorrelation[] {+ const current = contextStorage.getStore()?.get(InstrumentationActionScopeKey);+ if (current === undefined) return [];+ const correlations = Object.entries(current)+ .filter(+ ([, scope]) =>+ scope.sessionId === sessionId && (turnId === undefined || scope.turnId === turnId),+ )+ .map(([idempotencyKey, scope]) => ({ idempotencyKey, scope }));+ if (correlations.length === 0) return [];+ const keys = new Set(correlations.map((correlation) => correlation.idempotencyKey));+ writeContextKey(InstrumentationActionScopeKey, (state) => {+ const next = { ...state };+ for (const key of keys) delete next[key];+ return next;+ });+ return correlations;}function writeSlot(@@ -135,12 +304,35 @@ function writeSlot(key: string,value: InstrumentationStateRecord | undefined,): InstrumentationStateMap {- const next = { ...state };- if (value === undefined) delete next[key];- else next[key] = value;- return next;+ if (value === undefined) {+ const next = { ...state };+ delete next[key];+ return next;+ }+ return { ...state, [key]: value };+}++function writeInstrumentationState(+ update: (state: InstrumentationStateMap) => InstrumentationStateMap,+): void {+ writeContextKey(InstrumentationStateKey, update);+}++function assignOwner(record: InstrumentationStateRecord, owner: InstrumentationStateOwner): void {+ if (owner.attemptId !== undefined) record.attemptId = owner.attemptId;+ if (owner.sessionId !== undefined) record.sessionId = owner.sessionId;+ if (owner.turnId !== undefined) record.turnId = owner.turnId;}+function writeContextKey<T extends Readonly<Record<string, unknown>>>(+ key: ContextKey<T>,+ update: (state: T) => T,+): void {+ if (contextStorage.getStore() === undefined) return;+ loadContext().set(key, (state) => update(state ?? ({} as T)));+}++/** A provider name cannot contain NUL, so the pair cannot be ambiguous. */function stateKey(provider: string, idempotencyKey: string): string {return `${provider}\0${idempotencyKey}`;}@@ -151,13 +343,18 @@ function deserializeState(data: unknown): InstrumentationStateMap {for (const [key, value] of Object.entries(data)) {if (typeof value !== "object" || value === null || Array.isArray(value)) continue;const record = value as Record<string, unknown>;+ const attemptId = typeof record["attemptId"] === "string" ? record["attemptId"] : undefined;+ const sessionId = typeof record["sessionId"] === "string" ? record["sessionId"] : undefined;+ const turnId = typeof record["turnId"] === "string" ? record["turnId"] : undefined;const parsed: InstrumentationStateRecord = {};if (record["abandoned"] === true) parsed.abandoned = true;- if (typeof record["attemptId"] === "string") parsed.attemptId = record["attemptId"];+ if (attemptId !== undefined) parsed.attemptId = attemptId;+ if (sessionId !== undefined) parsed.sessionId = sessionId;+ if (turnId !== undefined) parsed.turnId = turnId;if (record["value"] !== undefined) {parsed.value = cloneAndFreezeJson(record["value"] as JsonValue);}- if (parsed.abandoned === true || parsed.value !== undefined) state[key] = parsed;+ state[key] = parsed;}return state;}@@ -174,3 +371,8 @@ function cloneAndFreezeJson(value: JsonValue): JsonValue {}return Object.freeze(copy);}++function deserializeScopes(data: unknown): InstrumentationScopeMap {+ if (typeof data !== "object" || data === null || Array.isArray(data)) return {};+ return data as InstrumentationScopeMap;+}diff --git a/packages/eve/src/harness/runtime-action-settlement-state.ts b/packages/eve/src/harness/runtime-action-settlement-state.tsnew file mode 100644index 000000000..691c4356f--- /dev/null+++ b/packages/eve/src/harness/runtime-action-settlement-state.ts@@ -0,0 +1,6 @@+import { ContextKey } from "#context/key.js";++/** Per-call acceptance times ferried through one internal turn step. */+export const RuntimeActionSettlementTimesKey = new ContextKey<Readonly<Record<string, number>>>(+ "eve.harness.runtimeActionSettlementTimes",+);diff --git a/packages/eve/src/harness/runtime-actions.test.ts b/packages/eve/src/harness/runtime-actions.test.tsindex 89241038f..07afc1be0 100644--- a/packages/eve/src/harness/runtime-actions.test.ts+++ b/packages/eve/src/harness/runtime-actions.test.ts@@ -5,6 +5,7 @@ import {import { describe, expect, it } from "vitest";import {+ createRuntimeActionRequestFromToolCall,getPendingRuntimeActionBatch,resolvePendingRuntimeActions,resolveToolCallInputObject,@@ -35,6 +36,52 @@ const OPERATION_ID = deriveAgentOperationId({parentTurnId: "turn_0",});+describe("createRuntimeActionRequestFromToolCall", () => {+ const loadSkillCall = {+ input: { skill: "research" },+ toolCallId: "call-skill",+ toolName: "load_skill",+ type: "tool-call" as const,+ };++ it("classifies the framework load_skill tool as a skill action", () => {+ expect(+ createRuntimeActionRequestFromToolCall({+ toolCall: loadSkillCall,+ tools: new Map([+ [+ "load_skill",+ {+ description: "Load a skill.",+ frameworkAction: "load-skill" as const,+ inputSchema: jsonSchema({ type: "object" }),+ name: "load_skill",+ },+ ],+ ]),+ }),+ ).toEqual({+ callId: "call-skill",+ input: { skill: "research" },+ kind: "load-skill",+ });+ });++ it("keeps an authored load_skill override as an ordinary tool action", () => {+ expect(+ createRuntimeActionRequestFromToolCall({+ toolCall: loadSkillCall,+ tools: new Map(),+ }),+ ).toEqual({+ callId: "call-skill",+ input: { skill: "research" },+ kind: "tool-call",+ toolName: "load_skill",+ });+ });+});+function createParkedSession(): HarnessSession {const base: HarnessSession = {agent: { modelReference: { id: "test-model" }, system: "", tools: [] },@@ -611,3 +658,4 @@ describe("resolveToolCallInputObject", () => {);});});+import { jsonSchema } from "ai";diff --git a/packages/eve/src/harness/runtime-actions.ts b/packages/eve/src/harness/runtime-actions.tsindex 05cdc445d..f69f9c90a 100644--- a/packages/eve/src/harness/runtime-actions.ts+++ b/packages/eve/src/harness/runtime-actions.ts@@ -340,6 +340,17 @@ export function createRuntimeActionRequestFromToolCall(input: {}): RuntimeActionRequest {const definition = input.tools.get(input.toolCall.toolName);+ if (definition?.frameworkAction === "load-skill") {+ return {+ callId: input.toolCall.toolCallId,+ input: resolveToolCallInputObject(input.toolCall.input, {+ callId: input.toolCall.toolCallId,+ toolName: input.toolCall.toolName,+ }),+ kind: "load-skill",+ };+ }+if (definition?.runtimeAction?.kind === "subagent-call") {return {callId: input.toolCall.toolCallId,diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.tsindex a780b2cd1..d3d84af5a 100644--- a/packages/eve/src/harness/tool-loop.test.ts+++ b/packages/eve/src/harness/tool-loop.test.ts@@ -3296,6 +3296,7 @@ describe("createToolLoopHarness", () => {// which mis-routed the resume through the fresh-turn lifecycle path.const emission = getHarnessEmissionState(result.session.state);expect(emission.turnId).toBe("turn_0");+ expect(emission.stepIndex).toBe(1);expect(emission.sessionStarted).toBe(true);expect(isHarnessBetweenTurns(result.session)).toBe(false);});@@ -10246,6 +10247,60 @@ describe("createToolLoopHarness", () => {);});+ it("publishes a delegation action when the AI SDK skips execution callbacks", async () => {+ setupMockAgent({+ finishReason: "tool-calls",+ response: {+ messages: [+ {+ content: [+ {+ input: { message: "research this" },+ toolCallId: "call-delegate",+ toolName: "delegate",+ type: "tool-call",+ },+ ],+ role: "assistant",+ },+ ],+ },+ text: "",+ toolCalls: [+ {+ input: { message: "research this" },+ toolCallId: "call-delegate",+ toolName: "delegate",+ type: "tool-call",+ },+ ],+ toolResults: [],+ });+ const started = vi.fn();+ const hooks = createInstrumentationHooks([+ { events: { "action.started": started }, name: "test" },+ ]);+ const { emit } = createEventCollector();+ const runStep = createToolLoopHarness(+ createTestConfig("conversation", emit, {+ instrumentation: { hooks, runInContext: (_operation, execute) => execute() },+ tools: createDelegationToolMap(),+ }),+ );++ await runStep(createTestSession(), { message: "delegate" });++ expect(started).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({+ callId: "call-delegate",+ kind: "subagent-call",+ name: "delegate",+ type: "action.started",+ }),+ expect.anything(),+ );+ });+it("composes lifecycle hooks with existing authored OTel", async () => {setupMockAgent({finishReason: "stop",diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.tsindex d91ce21ff..0409fedc2 100644--- a/packages/eve/src/harness/tool-loop.ts+++ b/packages/eve/src/harness/tool-loop.ts@@ -132,7 +132,10 @@ import {} from "#harness/approval-delivery-coordinator.js";import { buildTelemetryRuntimeContext } from "#harness/instrumentation-runtime-context.js";import { createAiSdkHookBridge } from "#harness/ai-sdk-hook-bridge.js";-import { createInstrumentationHandleEvent } from "#harness/instrumentation-native-events.js";+import {+ createInstrumentationHandleEvent,+ publishInputResolutions,+} from "#harness/instrumentation-native-events.js";import type { InstrumentationAttemptScope } from "#harness/instrumentation-lifecycle.js";import { attemptIdempotencyKey } from "#harness/instrumentation-lifecycle.js";import { resolveParentLineage } from "#harness/parent-lineage.js";@@ -607,8 +610,10 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {const store = contextStorage.getStore();const parent = store?.get(ParentSessionKey);const hasDelegatedCaller = parent !== undefined || store?.get(SessionCallbackKey) !== undefined;+ let activeAttemptScope: InstrumentationAttemptScope | undefined;const emit = createInstrumentationHandleEvent({agentName: config.runtimeIdentity?.agentName,+ getAttemptScope: () => activeAttemptScope,handleEvent: baseEmit,hooks: config.instrumentation?.hooks,parentLineage: resolveParentLineage(parent, store?.get(ChannelKey)),@@ -944,6 +949,16 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {return { next: null, session: pending.session };}+ if (config.instrumentation?.hooks !== undefined && pending.resolvedInputs !== undefined) {+ for (const batch of pending.resolvedInputs) {+ await publishInputResolutions({+ batch,+ hooks: config.instrumentation.hooks,+ sessionId: session.sessionId,+ });+ }+ }+// Surface denied tool-call approvals as rejected `action.result` events.// The denial otherwise lives only in model history, so consumers (e.g.// observability) never see the tool call resolve. Attributed to the turn@@ -1298,6 +1313,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {stepIndex: emissionState.stepIndex,turnId: instrumentationTurnId,};+ activeAttemptScope = attemptScope;const bridgeIntegration =attemptScope === undefined || instrumentationHooks === undefined? undefined@@ -2394,7 +2410,7 @@ async function handleStepResult(input: {responseMessages,session: { ...baseSession, history: [...promptMessages] },}),- emissionState,+ advanceStep(emissionState),),};}diff --git a/packages/eve/src/protocol/message.ts b/packages/eve/src/protocol/message.tsindex 424c9f044..9bf14430a 100644--- a/packages/eve/src/protocol/message.ts+++ b/packages/eve/src/protocol/message.ts@@ -1136,8 +1136,8 @@ export function createActionResultEvent(input: {error: outcome.error,result: input.result,sequence: input.sequence,- stepIndex: input.stepIndex,status: outcome.status,+ stepIndex: input.stepIndex,turnId: input.turnId,},type: "action.result",diff --git a/packages/eve/src/runtime/actions/results.ts b/packages/eve/src/runtime/actions/results.tsindex 79001fdeb..bd507c685 100644--- a/packages/eve/src/runtime/actions/results.ts+++ b/packages/eve/src/runtime/actions/results.ts@@ -2,12 +2,12 @@ import { getRuntimeActionResultKey } from "#runtime/actions/keys.js";import type { RuntimeActionResult } from "#runtime/actions/types.js";/** Returns results in pending-key order once every requested action has completed. */-export function resolveRuntimeActionResultsForKeys(input: {+export function resolveRuntimeActionResultsForKeys<TResult extends RuntimeActionResult>(input: {readonly pendingKeys: readonly string[];- readonly results: readonly RuntimeActionResult[];-}): RuntimeActionResult[] | undefined {+ readonly results: readonly TResult[];+}): TResult[] | undefined {const pendingKeySet = new Set(input.pendingKeys);- const resultsByKey = new Map<string, RuntimeActionResult>();+ const resultsByKey = new Map<string, TResult>();for (const result of input.results) {const key = getRuntimeActionResultKey(result);@@ -19,7 +19,7 @@ export function resolveRuntimeActionResultsForKeys(input: {resultsByKey.set(key, result);}- const orderedResults: RuntimeActionResult[] = [];+ const orderedResults: TResult[] = [];for (const key of input.pendingKeys) {const result = resultsByKey.get(key);