The Open Framework for Building Agents
refactor(eve): centralize human-in-the-loop session state under one requests key (#4566)
Rui1a8db93b3b5d
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 515ff5ae3..4019b1518 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -95,8 +95,8 @@ jobs:- name: Run unit testsrun: pnpm test:unit- - name: Test workflow helpers- run: node --test .github/scripts/*.test.mjs+ - name: Test workflow and guard helpers+ run: node --test .github/scripts/*.test.mjs scripts/hitl-state-readers.test.mjstest-integration:name: test-integration (${{ matrix.os }})diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/README.md b/e2e/fixtures/agent-tools-hitl/evals/hitl/README.mdindex 57582455f..c81e56579 100644--- a/e2e/fixtures/agent-tools-hitl/evals/hitl/README.md+++ b/e2e/fixtures/agent-tools-hitl/evals/hitl/README.md@@ -78,7 +78,7 @@ the evals above by `expectNoModelCallWhileOpen` and- **A fresh relayed batch replacing an older one.** This needs a child orremote agent to ask again from the same source while its earlier batch isopen. Each workflow `ctx.ask()` is its own source. Covered by- `harness/proxy-input-requests.test.ts` ("replaces prior entries for the same+ `harness/hitl/relays.test.ts` ("replaces prior entries for the samechild continuation token").- **Handoff blocked while a request is open.** This needs a deploymenthandoff, which only the Vercel redeploy suite performs.diff --git a/packages/eve/src/execution/authorization-callback-match.test.ts b/packages/eve/src/execution/authorization-callback-match.test.tsindex 20766cb3e..824fa38b1 100644--- a/packages/eve/src/execution/authorization-callback-match.test.ts+++ b/packages/eve/src/execution/authorization-callback-match.test.ts@@ -1,21 +1,19 @@import { describe, expect, it } from "vitest";import { matchAuthorizationCallbacks } from "#execution/authorization-callback-match.js";-import type { PendingAuthorizationState } from "#harness/authorization.js";+import type { AuthorizationChallenge } from "#harness/authorization.js";describe("matchAuthorizationCallbacks", () => {it.each([undefined, "another-attempt"])("ignores an unmatched attempt %s", (attemptId) => {const result = matchAuthorizationCallbacks(- {- challenges: [- {- attemptId: "attempt-1",- name: "crm",- hookUrl: "https://app.example/callback",- challenge: {},- principal: { type: "app" },- },- ],- },+ [+ {+ attemptId: "attempt-1",+ name: "crm",+ hookUrl: "https://app.example/callback",+ challenge: {},+ principal: { type: "app" },+ },+ ],[{authorizationCallback: {@@ -39,17 +37,15 @@ describe("matchAuthorizationCallbacks", () => {};const message = { message: "Continue after signing in" };const result = matchAuthorizationCallbacks(- {- challenges: [- {- attemptId: "attempt-1",- name: "crm",- hookUrl: "https://app.example/callback",- challenge: {},- principal: { type: "app" },- },- ],- },+ [+ {+ attemptId: "attempt-1",+ name: "crm",+ hookUrl: "https://app.example/callback",+ challenge: {},+ principal: { type: "app" },+ },+ ],[callback, message, callback],);expect(result.matches).toHaveLength(1);@@ -57,20 +53,18 @@ describe("matchAuthorizationCallbacks", () => {});it("carries the resolved connection instance into the callback result", () => {- const pending: PendingAuthorizationState = {- challenges: [- {- attemptId: "attempt-1",- challenge: { url: "https://auth.example.com" },- hookUrl: "https://app.example.com/callback",- instanceId: "connection:instance-a",- name: "crm",- principal: { type: "app" },- },- ],- };+ const signIns: AuthorizationChallenge[] = [+ {+ attemptId: "attempt-1",+ challenge: { url: "https://auth.example.com" },+ hookUrl: "https://app.example.com/callback",+ instanceId: "connection:instance-a",+ name: "crm",+ principal: { type: "app" },+ },+ ];- const result = matchAuthorizationCallbacks(pending, [+ const result = matchAuthorizationCallbacks(signIns, [{authorizationCallback: {attemptId: "attempt-1",diff --git a/packages/eve/src/execution/authorization-callback-match.ts b/packages/eve/src/execution/authorization-callback-match.tsindex ffc466856..a1749bc76 100644--- a/packages/eve/src/execution/authorization-callback-match.ts+++ b/packages/eve/src/execution/authorization-callback-match.ts@@ -1,9 +1,5 @@import type { DeliverPayload } from "#channel/types.js";-import type {- AuthorizationChallenge,- AuthorizationResult,- PendingAuthorizationState,-} from "#harness/authorization.js";+import type { AuthorizationChallenge, AuthorizationResult } from "#harness/authorization.js";import type { AuthorizationCallback } from "#shared/connection-types.js";export interface MatchedAuthorizationCallback {@@ -13,7 +9,7 @@ export interface MatchedAuthorizationCallback {/** Matches each callback to exactly one pending authorization attempt. */export function matchAuthorizationCallbacks(- pending: PendingAuthorizationState,+ signIns: readonly AuthorizationChallenge[],payloads: readonly DeliverPayload[],): {readonly matches: readonly MatchedAuthorizationCallback[];@@ -36,7 +32,7 @@ export function matchAuthorizationCallbacks(continue;}- const challenge = pending.challenges.find((candidate) => {+ const challenge = signIns.find((candidate) => {if (candidate.name !== callback.connectionName) return false;return typeof callback.attemptId === "string" && candidate.attemptId === callback.attemptId;});diff --git a/packages/eve/src/execution/catalog/step-catalog.integration.test.ts b/packages/eve/src/execution/catalog/step-catalog.integration.test.tsindex 31a605779..0b7d9cc1d 100644--- a/packages/eve/src/execution/catalog/step-catalog.integration.test.ts+++ b/packages/eve/src/execution/catalog/step-catalog.integration.test.ts@@ -16,12 +16,8 @@ import { dispatchDynamicToolEvent } from "#context/dynamic-tool-lifecycle.js";import { SessionIdKey, StaticModelReferenceKey } from "#context/keys.js";import { ConnectionRegistryKey } from "#context/providers/connection-key.js";import { mockModel } from "#evals/mock-model.js";-import {- CallbackBaseUrlKey,- clearPendingAuthorization,- getPendingAuthorization,- PendingAuthorizationResultKey,-} from "#harness/authorization.js";+import { CallbackBaseUrlKey, PendingAuthorizationResultKey } from "#harness/authorization.js";+import { readHitlState, writeHitlState } from "#harness/hitl/requests.js";import { createToolLoopHarness } from "#harness/tool-loop.js";import type { HarnessSession, HarnessToolMap, StepInput, StepResult } from "#harness/types.js";import {@@ -347,7 +343,7 @@ describe("step catalog in the harness (real AI SDK)", () => {// A connection tool parks the turn for sign-in, then runs once the user signs in.reply(calls(call("items", CALL_TOOL_NAME, { name: "private__list_items" })));const signingIn = await drive({ message: "Alice wants the items in the private catalog." });- const [challenge] = getPendingAuthorization(signingIn.session.state)?.challenges ?? [];+ const [challenge] = readHitlState(signingIn.session.state).signIns;expect(challenge?.name).toBe("private");expect(privateCatalog.signIns).toHaveLength(1);// Delivers the callback the way the turn step does when the user signs in.@@ -360,10 +356,11 @@ describe("step catalog in the harness (real AI SDK)", () => {name: "private",},]);- driver.session = {- ...driver.session,- state: clearPendingAuthorization(driver.session.state, [challenge!.attemptId!]),- };+ driver.session = writeHitlState(driver.session, {+ signIns: readHitlState(driver.session.state).signIns.filter(+ (pending) => pending.attemptId !== challenge!.attemptId,+ ),+ });reply(calls(call("items-after-sign-in", CALL_TOOL_NAME, { name: "private__list_items" })),text("The private catalog has Alice's lamp."),diff --git a/packages/eve/src/execution/durable-session-store.ts b/packages/eve/src/execution/durable-session-store.tsindex 3f4b65951..706ee8cf3 100644--- a/packages/eve/src/execution/durable-session-store.ts+++ b/packages/eve/src/execution/durable-session-store.ts@@ -1,5 +1,5 @@import type { HarnessModelMessage } from "#harness/messages.js";-import { hasProxyInputRequests } from "#harness/proxy-input-requests.js";+import { readHitlState } from "#harness/hitl/index.js";import type { HarnessSession, HarnessSessionBase, SessionStateMap } from "#harness/types.js";import { projectToDurableSession } from "#execution/session.js";import type { SandboxState } from "#sandbox/state.js";@@ -100,7 +100,7 @@ export function replaceDurableSessionSnapshot(input: {function projectDurableSessionState(session: DurableSession): DurableSessionState {return {continuationToken: session.continuationToken,- hasProxyInputRequests: hasProxyInputRequests(session.state),+ hasProxyInputRequests: readHitlState(session.state).relays.size > 0,sessionId: session.sessionId,version: DURABLE_SESSION_VERSION,snapshot: { session },diff --git a/packages/eve/src/execution/forward-session-input.ts b/packages/eve/src/execution/forward-session-input.tsindex 78a27e436..d1d2df6a7 100644--- a/packages/eve/src/execution/forward-session-input.ts+++ b/packages/eve/src/execution/forward-session-input.ts@@ -7,7 +7,7 @@ import {SessionInboxKey,} from "#context/keys.js";import { forwardLegacySessionInput } from "#execution/legacy-remote-agent/protocol.js";-import { resolvedForParent } from "#harness/proxy-input-requests.js";+import { resolvedForParent } from "#harness/hitl/relays.js";import { postSessionCallbackRequest } from "#execution/session-callback-request.js";import { sessionCommandHookToken } from "#execution/session-inbox/address.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";diff --git a/packages/eve/src/execution/proxied-deliver-step.ts b/packages/eve/src/execution/proxied-deliver-step.tsindex 6a246d599..0a51a9ae3 100644--- a/packages/eve/src/execution/proxied-deliver-step.ts+++ b/packages/eve/src/execution/proxied-deliver-step.ts@@ -1,6 +1,4 @@-import { sessionView } from "#harness/session-machine/commit.js";-import { routeAnswer, hold, receiveRelayedAnswer } from "#harness/session-machine/transitions.js";-import { storedProjection } from "#harness/session-machine/view.js";+import { receiveRelayedAnswer, routeAnswer } from "#harness/session-machine/transitions.js";import type { SessionInboxAddress } from "#execution/session-inbox/address.js";import { hasDelegatedSessionContext } from "#execution/delegated-session-context.js";import { buildAdapterContext } from "#channel/adapter-context.js";@@ -8,14 +6,9 @@ import type { DeliverHookPayload, DeliverPayload } from "#channel/types.js";import { AuthKey, TurnDeliveryIdsKey } from "#context/keys.js";import { setChannelContext } from "#execution/channel-context.js";import { coalesceDeliverPayloads } from "#execution/deliver-payloads.js";-import {- type DurableSessionState,- readDurableSession,- replaceDurableSessionSnapshot,-} from "#execution/durable-session-store.js";+import { type DurableSessionState, readDurableSession } from "#execution/durable-session-store.js";import {publishSessionEvents,- relaySessionEvents,type PublishedSessionEvents,type SessionStepState,} from "#execution/publish-session-events.js";@@ -36,9 +29,10 @@ import {toToolInputResponseResponder,} from "#execution/tools/workflow/answer.js";import type { StepCoordinates as PendingInputBatchEvent } from "#harness/session-machine/view.js";-import type { WorkflowAskRoute } from "#harness/proxy-input-requests.js";+import type { WorkflowAskRoute } from "#harness/hitl/relays.js";import { type InputResolution, type UnstampedMessageStreamEvent } from "#protocol/message.js";-import { getProxyInputRequests, retireProxyInputRequests } from "#harness/proxy-input-requests.js";+import { readHitlState } from "#harness/hitl/index.js";+import { commitSessionStep } from "#execution/publish-session-events.js";import type { InputResponse } from "#shared/input.js";export type RoutedDeliverResult =@@ -56,9 +50,7 @@ export type RoutedDeliverResult =interface ChildBucket {readonly workflowAsk?: WorkflowAskRoute;- readonly remote?: NonNullable<- import("#harness/proxy-input-requests.js").ProxyInputRequest["remote"]- >;+ readonly remote?: NonNullable<import("#harness/hitl/relays.js").ProxyInputRequest["remote"]>;readonly childContinuationToken: string;readonly childSessionInbox?: SessionInboxAddress;readonly event: PendingInputBatchEvent;@@ -83,12 +75,12 @@ export async function routeProxiedDeliverStep(async function routeProxiedDeliver(input: SessionStepState & { readonly delivery: DeliverHookPayload },): Promise<RoutedDeliverResult> {- const requests = getProxyInputRequests(readDurableSession(input.sessionState).state);+ const requests = readHitlState(readDurableSession(input.sessionState).state).relays;const { delivery: sourceDelivery, serializedContext } = await deliverChannelInputResponses({...input,routable: (response) => requests.has(response.requestId),});- let durableSession = readDurableSession(input.sessionState);+ const durableSession = readDurableSession(input.sessionState);const parentPayloads = new Map<number, DeliverPayload>();const children = new Map<string, ChildBucket>();let parentAction: { readonly kind: "cancel-turn" } | undefined;@@ -165,7 +157,6 @@ async function routeProxiedDeliver(}}- let retired = false;const answered: { event: PendingInputBatchEvent; resolutions: InputResolution[] }[] = [];for (const child of children.values()) {if (child.workflowAsk !== undefined) {@@ -203,37 +194,24 @@ async function routeProxiedDeliver();}}+ // Only answers that went down to their child retire its routes.answered.push({ event: child.event, resolutions: [...child.resolutions.values()] });- // Successfully forwarded request IDs are retired so later deliveries- // cannot route through stale entries.- durableSession = retireProxyInputRequests(durableSession, [...child.resolutions.keys()]);- retired = true;}- const view = sessionView(storedProjection(durableSession.state), durableSession.state);- const resolvedEvents = [...routeAnswer(view, { children: answered }).events];- // Answers that leave other requests pending, and nothing for the turn itself, keep the- // open turn held, so it parks again as after a partial approval answer. A forwarded approval- // stays open until its child settles it, but it no longer waits on the person.+ // A forwarded approval stays open until its child settles it, but it no longer waits on the+ // person.const forwarded = new Set([...children.values()].flatMap((child) =>child.payloads.flatMap((payload) => (payload.inputResponses ?? []).map((r) => r.requestId)),),);- if (+ const retired = new Set(answered.flatMap((child) => child.resolutions.map((r) => r.requestId)));+ const holds =children.size > 0 &&parentPayloads.size === 0 &&parentAction === undefined &&- [...getProxyInputRequests(durableSession.state).keys()].some((id) => !forwarded.has(id))- ) {- resolvedEvents.push(...hold(view, { on: "input" }).events);- }+ [...requests.keys()].some((id) => !retired.has(id) && !forwarded.has(id));- let published: PublishedSessionEvents = {- serializedContext,- sessionState: retired- ? replaceDurableSessionSnapshot({ session: durableSession, state: input.sessionState })- : input.sessionState,- };+ let published: PublishedSessionEvents = { serializedContext, sessionState: input.sessionState };if (answerMessages.length > 0) {// Like a steering message, the answer joins the open turn, so the turn's// later events carry its delivery ids too.@@ -246,9 +224,10 @@ async function routeProxiedDeliver(answerMessages,);}- const context = await relaySessionEvents(+ const context = await commitSessionStep({ ...published, sessionWritable: input.sessionWritable },- resolvedEvents,+ (view) => [routeAnswer(view, { children: answered, holds })],+ { origin: "relayed" },);if (parentAction !== undefined) return { ...context, ...parentAction };const orderedParentPayloads = [...parentPayloads].sort(([a], [b]) => a - b);diff --git a/packages/eve/src/execution/publish-session-events.integration.test.ts b/packages/eve/src/execution/publish-session-events.integration.test.tsindex 25e7d4f2a..53cd553da 100644--- a/packages/eve/src/execution/publish-session-events.integration.test.ts+++ b/packages/eve/src/execution/publish-session-events.integration.test.ts@@ -1,14 +1,21 @@-import { expect, it } from "vitest";+import { expect, it, vi } from "vitest";-import { replaceDurableSessionSnapshot } from "#execution/durable-session-store.js";+import { readTurnState } from "#harness/session-machine/state.js";++import { sandboxProvider } from "#context/providers/sandbox.js";+import {+ readDurableSession,+ replaceDurableSessionSnapshot,+} from "#execution/durable-session-store.js";+import { commitSessionStep } from "#execution/publish-session-events.js";import { applyRunMessagesStep } from "#execution/tools/workflow/apply-run-messages-step.js";import { withdrawWorkflowToolRunQuestionStep } from "#execution/tools/workflow/withdraw-step.js";-import { upsertProxyInputRequests } from "#harness/proxy-input-requests.js";+import type { HarnessSession } from "#harness/types.js";import { createTestRuntime } from "#internal/testing/app-harness.js";import { createTestSessionState } from "#internal/testing/session-state.js";import { createInputRequestedEvent, type MessageStreamEvent } from "#protocol/message.js";-import { withPublished } from "#internal/testing/session-machine.js";+import { withPublished, withRelays } from "#internal/testing/session-machine.js";import { defineHook } from "#public/definitions/hook.js";import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";@@ -89,22 +96,8 @@ it("publishes a session step's action.partial to the stream and its hooks", asynit("relays a withdrawn workflow question's input.resolved to the stream and its hooks", async () => {const { hooked, runtime, sessionWritable, streamed } = await createPublishingRuntime();const base = createTestSessionState();- const asked = upsertProxyInputRequests({- entries: [- [- "ask-1",- {- workflowAsk: { control: "control" },- reply: {},- runId: "run-1",- childContinuationToken: "ask-1",- event: { sequence: 1, stepIndex: 0, turnId: "turn-1" },- kind: "question",- },- ],- ],- forChildContinuationToken: "ask-1",- session: withPublished(base.snapshot.session as HarnessSession, [+ const asked = withRelays(+ withPublished(base.snapshot.session as HarnessSession, [createInputRequestedEvent({callId: "call-1",requests: [@@ -120,7 +113,23 @@ it("relays a withdrawn workflow question's input.resolved to the stream and itsturnId: "turn-1",}),]),- });+ {+ entries: [+ [+ "ask-1",+ {+ workflowAsk: { control: "control" },+ reply: {},+ runId: "run-1",+ childContinuationToken: "ask-1",+ event: { sequence: 1, stepIndex: 0, turnId: "turn-1" },+ kind: "question",+ },+ ],+ ],+ forChildContinuationToken: "ask-1",+ },+ );await runtime.run(async () => {await withdrawWorkflowToolRunQuestionStep({@@ -144,3 +153,27 @@ it("relays a withdrawn workflow question's input.resolved to the stream and its]);expect(hooked).toEqual([{ event: streamed[0], sessionId: "test-session" }]);});++it("keeps what the sandbox provider commits when a session step saves a transition", async () => {+ const { runtime, sessionWritable } = await createPublishingRuntime();+ const captured = { session: null, snapshot: "captured-in-scope" };+ const commit = vi+ .spyOn(sandboxProvider, "commit")+ .mockImplementation(async (_access, session) => ({ ...session, sandboxState: captured }));+ try {+ const published = await runtime.run(() =>+ commitSessionStep(+ { serializedContext, sessionState: createTestSessionState(), sessionWritable },+ (view) => [{ events: [], turn: { ...view.turn, grants: ["deploy"] } }],+ { origin: "relayed" },+ ),+ );+ expect(commit).toHaveBeenCalled();+ expect(published.sessionState.snapshot.session.sandboxState).toEqual(captured);+ expect(readTurnState(readDurableSession(published.sessionState).state).grants).toEqual([+ "deploy",+ ]);+ } finally {+ commit.mockRestore();+ }+});diff --git a/packages/eve/src/execution/publish-session-events.test.ts b/packages/eve/src/execution/publish-session-events.test.tsnew file mode 100644index 000000000..bc0d6c119--- /dev/null+++ b/packages/eve/src/execution/publish-session-events.test.ts@@ -0,0 +1,62 @@+import { expect, it } from "vitest";+import { commitSessionStep } from "#execution/publish-session-events.js";+import { createTestSessionState } from "#internal/testing/session-state.js";++const target = () => ({+ serializedContext: {},+ sessionState: createTestSessionState(),+ sessionWritable: new WritableStream<Uint8Array>(),+});+it("rejects overlapping turn snapshots before restoring or publishing", async () => {+ await expect(+ commitSessionStep(+ target(),+ (view) => [+ { turn: { ...view.turn }, events: [] },+ { turn: { ...view.turn }, events: [] },+ ],+ { origin: "relayed" },+ ),+ ).rejects.toThrow("must not overlap");+});+it("rejects overlapping sign-in snapshots before restoring or publishing", async () => {+ await expect(+ commitSessionStep(+ target(),+ (view) => [+ { turn: view.turn, events: [], signIns: [] },+ { turn: view.turn, events: [], signIns: [] },+ ],+ { origin: "relayed" },+ ),+ ).rejects.toThrow("must not overlap");+});+it("allows a batch of unchanged transitions", async () => {+ const state = target();+ await expect(+ commitSessionStep(+ state,+ (view) => [+ { turn: view.turn, events: [] },+ { turn: view.turn, events: [] },+ ],+ { origin: "relayed" },+ ),+ ).resolves.toEqual({+ serializedContext: state.serializedContext,+ sessionState: state.sessionState,+ });+});++it("rejects a changed turn followed by the original turn snapshot", async () => {+ await expect(+ commitSessionStep(+ target(),+ (view) => [+ { turn: { ...view.turn }, events: [] },+ { turn: view.turn, events: [] },+ ],+ { origin: "relayed" },+ ),+ ).rejects.toThrow("must not overlap");+});diff --git a/packages/eve/src/execution/publish-session-events.ts b/packages/eve/src/execution/publish-session-events.tsindex b5cf1e343..33f964e70 100644--- a/packages/eve/src/execution/publish-session-events.ts+++ b/packages/eve/src/execution/publish-session-events.ts@@ -22,14 +22,25 @@ import {import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";import { reconcileSessionContinuationToken } from "#execution/reconcile-session-continuation-token.js";import { hydrateDurableSession } from "#execution/session.js";-import { dropClosedRecords } from "#harness/session-machine/commit.js";+import {+ publishTransition,+ saveTransition,+ sessionView,+ type Transition,+ dropClosedRecords,+} from "#harness/session-machine/commit.js";import {currentProjection,enterSessionProjection,recordPublishedEvent,saveSessionProjection,} from "#harness/session-machine/current.js";-import { activeTurnId, turnPosition } from "#harness/session-machine/view.js";+import {+ storedProjection,+ type SessionView,+ activeTurnId,+ turnPosition,+} from "#harness/session-machine/view.js";import { validateHarnessModelMessages, type HarnessModelMessage } from "#harness/messages.js";import type { HandleEventFn, HarnessSession, HarnessSessionBase } from "#harness/types.js";import { bindSessionInstrumentation } from "#instrumentation/runtime.js";@@ -89,14 +100,6 @@ export async function publishSessionEvents(return await publishEventsFromStep(target, "own", events);}-/** Publishes events of an exchange this session relays; see {@link SessionEventOrigin}. */-export async function relaySessionEvents(- target: SessionStepState,- events: readonly UnstampedMessageStreamEvent[],-): Promise<PublishedSessionEvents> {- return await publishEventsFromStep(target, "relayed", events);-}-async function publishEventsFromStep(target: SessionStepState,origin: SessionEventOrigin,@@ -509,3 +512,66 @@ async function writeUnroutedSessionEvent(writer.release();}}++/**+ * The commit of a step that owns the session outside a turn: restore it, decide its transitions+ * against what it restored, publish their events in order, and save what they change.+ * Used by relay-changing steps outside a turn; other steps still publish or apply transitions+ * directly. Batches keep the turn unchanged and contain at most one sign-in snapshot.+ */+export async function commitSessionStep(+ target: SessionStepState | RestoredSessionStep,+ decide: (view: SessionView) => readonly Transition[],+ options: {+ readonly origin: SessionEventOrigin;+ /** Where a relayed input batch came from; see `SessionStepPublication.inputSource`. */+ readonly inputSource?: string;+ },+): Promise<PublishedSessionEvents> {+ const { state } =+ "ctx" in target ? target.durableSession : readDurableSession(target.sessionState);+ const view = sessionView(storedProjection(state), state);+ const transitions = decide(view);+ if (+ (transitions.length > 1 && transitions.some((transition) => transition.turn !== view.turn)) ||+ transitions.filter((transition) => transition.signIns !== undefined).length > 1+ ) {+ throw new Error("A transition batch must not overlap turn or sign-in snapshots.");+ }+ if ("ctx" in target) return await commit(target, transitions, options);+ if (transitions.every((transition) => changesNothing(view, transition))) {+ return { serializedContext: target.serializedContext, sessionState: target.sessionState };+ }+ return await commit(await restoreSessionStep(target), transitions, options);+}++async function commit(+ restored: RestoredSessionStep,+ transitions: readonly Transition[],+ options: { readonly origin: SessionEventOrigin; readonly inputSource?: string },+): Promise<PublishedSessionEvents> {+ const { published } = await publishFromSessionStep(restored, {+ inputSource: options.inputSource,+ origin: options.origin,+ async publish(emit) {+ for (const transition of transitions) await publishTransition(transition, emit);+ },+ // Save onto the session the scope committed, which carries what its providers captured.+ updateSession: (session) => ({+ session: transitions.reduce((next, transition) => saveTransition(next, transition), session),+ }),+ });+ return published;+}++/** A transition that reports nothing and changes no record, as the machine decides with no work. */+function changesNothing(view: SessionView, transition: Transition): boolean {+ return (+ transition.turn === view.turn &&+ transition.events.length === 0 &&+ transition.signIns === undefined &&+ transition.relays === undefined &&+ transition.commit === undefined &&+ transition.clearsHistory === undefined+ );+}diff --git a/packages/eve/src/execution/session-workflow-tool-run.integration.test.ts b/packages/eve/src/execution/session-workflow-tool-run.integration.test.tsindex ac77e84a6..e13ca6f4f 100644--- a/packages/eve/src/execution/session-workflow-tool-run.integration.test.ts+++ b/packages/eve/src/execution/session-workflow-tool-run.integration.test.ts@@ -1,5 +1,7 @@import { describe, expect, it } from "vitest";+import { readHitlState } from "#harness/hitl/requests.js";+import { handleWorkflowToolRunMessage } from "#execution/session-workflow-tool-run.js";import { applyRunMessagesStep } from "#execution/tools/workflow/apply-run-messages-step.js";import { SessionStateCursor } from "#execution/session/state-cursor.js";@@ -11,7 +13,7 @@ import {writeTaskTable,} from "#execution/tasks/table.js";import type { WorkflowToolRunRef } from "#execution/tools/workflow/messages.js";-import { getProxyInputRequests } from "#harness/proxy-input-requests.js";+import { createTestRuntime } from "#internal/testing/app-harness.js";import { containsEventSequence, filterEventsByType } from "#internal/testing/events.js";import { createTestSessionState } from "#internal/testing/session-state.js";@@ -126,6 +128,6 @@ describe("handleWorkflowToolRunMessage", () => {expect(containsEventSequence(events, ["input.requested", "input.resolved", "task.settled"]),).toBe(true);- expect(getProxyInputRequests(cursor.sessionState.snapshot.session.state).size).toBe(0);+ expect(readHitlState(cursor.sessionState.snapshot.session.state).relays.size).toBe(0);});});diff --git a/packages/eve/src/execution/session-workflow-tool-run.ts b/packages/eve/src/execution/session-workflow-tool-run.tsindex ed9b5fb93..ddf8b07e4 100644--- a/packages/eve/src/execution/session-workflow-tool-run.ts+++ b/packages/eve/src/execution/session-workflow-tool-run.ts@@ -24,7 +24,7 @@ import {isInboxToolResultFromRecordedWorkflowToolRun,} from "#harness/workflow-tool-runs.js";import { runProxySubagentEventStep } from "#subagents/event-proxy-step.js";-import type { WorkflowAskRoute } from "#harness/proxy-input-requests.js";+import type { WorkflowAskRoute } from "#harness/hitl/relays.js";import type { RuntimeActionResult } from "#shared/action-types.js";interface HandlerInput<T> {diff --git a/packages/eve/src/execution/session/checkpoint-migrations.test.ts b/packages/eve/src/execution/session/checkpoint-migrations.test.tsindex 7cd2ea11e..90600c4c7 100644--- a/packages/eve/src/execution/session/checkpoint-migrations.test.ts+++ b/packages/eve/src/execution/session/checkpoint-migrations.test.ts@@ -1,7 +1,11 @@import { describe, expect, it } from "vitest";+import { readDurableSession } from "#execution/durable-session-store.js";import { migrateSessionCheckpoint } from "#execution/session/checkpoint-migrations.js";import { SESSION_CHECKPOINT_VERSION } from "#execution/session/handoff.js";+import { createApprovalCandidate, getApprovalAuditState } from "#harness/hitl/candidates.js";+import { readHitlState } from "#harness/hitl/requests.js";+import { readTurnState } from "#harness/session-machine/state.js";describe("migrateSessionCheckpoint", () => {it("upgrades a checkpoint written by an eve 0.66 owner to the current shape", () => {@@ -159,8 +163,134 @@ describe("migrateSessionCheckpoint", () => {kind: "incompatible",});});++ it.each([12, 13, 14])(+ "loads a saved version %s session's approvals, sign-ins and relays from the requests key",+ (version) => {+ const alice = { authenticator: "slack", principalId: "alice", principalType: "user" };+ const bob = { ...alice, principalId: "bob" };+ const settlement = {+ actor: alice,+ approver: { ...alice, attributes: {} },+ candidateId: "alice",+ outcome: "allowed",+ requestId: "deploy",+ settledAt: 300,+ };+ const candidateSignIn = {+ attemptId: "attempt-bob",+ candidateId: "bob",+ challenge: { instructions: "Sign in to GitHub." },+ hookUrl: "https://app.example/cb/bob",+ name: "github",+ };+ const bobCandidate = {+ authorizationChallenges: [candidateSignIn],+ candidateId: "bob",+ createdAt: 400,+ decision: "cancel",+ expiresAt: 900,+ requestId: "release",+ responder: { ...bob, attributes: { team: "infra" } },+ status: "authorization-required",+ };+ const signIn = {+ attemptId: "attempt-1",+ challenge: { instructions: "Sign in to Linear." },+ hookUrl: "https://app.example/cb/1",+ name: "linear",+ principal: { id: "alice", type: "user" },+ };+ const event = { sequence: 4, stepIndex: 0, turnId: "turn_1" };+ const relayed = {+ batch: { approvalRequestIds: ["child-approval"], requestIds: ["child-approval"] },+ childContinuationToken: "child-token",+ childSessionInbox: { sessionId: "child-session" },+ event,+ inputSource: "subagent:research",+ kind: "tool-approval",+ reply: { options: [{ id: "approve", label: "Approve" }] },+ };+ const asked = {+ childContinuationToken: "run-token",+ event,+ kind: "question",+ reply: { allowFreeform: true },+ runId: "run-1",+ workflowAsk: { control: "control-hook" },+ };+ const relays = {+ "child-approval": relayed,+ "run-question": asked,+ // A child request id shaped like a sign-in attempt stays a relay.+ "signin:attempt-1": { ...asked, runId: "run-2" },+ };+ const saved = JSON.stringify(+ savedCheckpoint(version, {+ "eve.harness.turnState": { grants: ["deploy:api"], suspended: [] },+ "eve.runtime.hitl.approvalState": {+ activeCandidates: { bob: bobCandidate },+ candidateHistory: [+ {+ candidateId: "alice",+ completedAt: 300,+ createdAt: 200,+ decision: "approve",+ requestId: "deploy",+ responder: alice,+ status: "allowed",+ },+ ],+ nextCandidateSequence: 2,+ settlements: { deploy: settlement },+ },+ "eve.runtime.pendingAuthorization": { challenges: [signIn] },+ "eve.runtime.proxyInputRequests": relays,+ "eve.unrelated": true,+ }),+ );++ const result = migrateSessionCheckpoint(JSON.parse(saved));+ if (result.kind !== "current") throw new Error(result.detail);+ const reloaded = JSON.parse(JSON.stringify(result.checkpoint));+ const { state } = readDurableSession(reloaded.sessionState);+ expect(Object.keys(state ?? {}).sort()).toEqual([+ "eve.harness.turnState",+ "eve.runtime.hitl.requests",+ "eve.unrelated",+ ]);+ const hitl = readHitlState(state);+ expect(readTurnState(state).grants).toEqual(["deploy:api"]);+ expect(hitl.signIns).toEqual([signIn]);+ expect(Object.fromEntries(hitl.relays)).toEqual(relays);+ const audit = getApprovalAuditState(state);+ expect(audit.activeCandidates).toEqual([bobCandidate]);+ expect(audit.candidateHistory.map((entry) => entry.candidateId)).toEqual(["alice"]);+ expect(audit.settlements).toEqual([settlement]);+ // Ids already issued stay taken: a responder reusing one gets a fresh one.+ const next = createApprovalCandidate({+ candidateIdPrefix: "alice",+ createdAt: 500,+ decision: "approve",+ expiresAt: 900,+ requestId: "release",+ responder: { ...alice, attributes: {} },+ state,+ });+ expect(getApprovalAuditState(next.state).activeCandidates.map((c) => c.candidateId)).toEqual([+ "bob",+ "alice.2",+ ]);+ // A current checkpoint loads unchanged.+ expect(migrateSessionCheckpoint(reloaded)).toEqual({ ...result, checkpoint: reloaded });+ },+ );});+function savedCheckpoint(version: number, state: Record<string, unknown>) {+ return { ...v11Checkpoint(state), version };+}+function v11Checkpoint(state: Record<string, unknown>) {return {version: 11,diff --git a/packages/eve/src/execution/session/checkpoint-migrations.ts b/packages/eve/src/execution/session/checkpoint-migrations.tsindex c627b0980..7537c88d9 100644--- a/packages/eve/src/execution/session/checkpoint-migrations.ts+++ b/packages/eve/src/execution/session/checkpoint-migrations.ts@@ -2,6 +2,7 @@ import { SESSION_CHECKPOINT_VERSION, type SessionCheckpoint } from "#execution/simport { isObject } from "#shared/guards.js";import { initialSessionProjection } from "#protocol/session-projection.js";import { getBlockingWorkflowToolRuns } from "#harness/workflow-tool-runs.js";+import { LEGACY_HITL_STATE_KEYS, upgradeLegacyHitlState } from "#harness/hitl/requests.js";/*** Oldest checkpoint a successor upgrades (eve 0.66.0). Earlier checkpoints@@ -97,6 +98,18 @@ const CHECKPOINT_UPGRADES: Readonly<// Version 14 prevents older deployments from dropping the batched messages// workflow tool runs relay. Existing checkpoints need no data changes.13: (checkpoint) => checkpoint,+ // Approval candidates, sign-ins and relayed requests moved under one requests key.+ 14: (checkpoint) => {+ const sessionState = readRecord(checkpoint, "sessionState");+ const snapshot = readRecord(sessionState, "snapshot");+ const session = readRecord(snapshot, "session");+ if (session.state === undefined) return checkpoint;+ const state = upgradeLegacyHitlState(readRecord(session, "state"));+ return {+ ...checkpoint,+ sessionState: { ...sessionState, snapshot: { ...snapshot, session: { ...session, state } } },+ };+ },};/**@@ -156,7 +169,7 @@ function upgradeIdleLifecycle(checkpoint: CheckpointRecord): CheckpointRecord {refuse("lifecycle position is malformed or a turn is still open");const retiredPendingKeys = [- "eve.runtime.pendingAuthorization",+ LEGACY_HITL_STATE_KEYS.signIns,"eve.runtime.pendingInputBatch","eve.runtime.pendingCoordinationBatch","eve.runtime.deferredStepInput",@@ -167,7 +180,7 @@ function upgradeIdleLifecycle(checkpoint: CheckpointRecord): CheckpointRecord {const batches = state["eve.runtime.pendingInputBatches"];if (batches !== undefined && (!Array.isArray(batches) || batches.length > 0))refuse("session holds pending input");- const routes = state["eve.runtime.proxyInputRequests"];+ const routes = state[LEGACY_HITL_STATE_KEYS.relays];if (sessionState.hasProxyInputRequests !== false ||(routes !== undefined && (!isObject(routes) || Object.keys(routes).length > 0))@@ -179,7 +192,7 @@ function upgradeIdleLifecycle(checkpoint: CheckpointRecord): CheckpointRecord {if (error instanceof CheckpointRefusal) throw error;refuse("workflow tool run registry is incompatible");}- const approvals = state["eve.runtime.hitl.approvalState"];+ const approvals = state[LEGACY_HITL_STATE_KEYS.approvals];if (approvals !== undefined &&(!isObject(approvals) ||@@ -203,7 +216,6 @@ function upgradeIdleLifecycle(checkpoint: CheckpointRecord): CheckpointRecord {"eve.harness.emission","eve.runtime.hitl.approvedTools","eve.runtime.pendingInputBatches",- "eve.runtime.proxyInputRequests",]),"eve.harness.sessionProjection": projection,};diff --git a/packages/eve/src/execution/session/handoff-steps.ts b/packages/eve/src/execution/session/handoff-steps.tsindex 9abf5fc0c..4a1b58d26 100644--- a/packages/eve/src/execution/session/handoff-steps.ts+++ b/packages/eve/src/execution/session/handoff-steps.ts@@ -1,6 +1,7 @@import { queuedInput, storedProjection } from "#harness/session-machine/view.js";import { openInputs, openSignIns } from "#protocol/session-projection.js";import { getBlockingWorkflowToolRuns } from "#harness/workflow-tool-runs.js";+import { holdsHitlRequests } from "#harness/hitl/index.js";import {EntityConflictError,RunExpiredError,@@ -24,7 +25,6 @@ import { getResolvedRuntimeAgentNode } from "#runtime/graph.js";import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";import { getSandboxEnvironmentRuntime } from "#shared/sandbox-environment.js";import { walkCauseChain } from "#shared/errors.js";-import { isObject } from "#shared/guards.js";const log = createLogger("execution.handoff");@@ -38,8 +38,8 @@ export function isSessionStateIdleForHandoff(input: {// These registries are deleted when work settles. Their ordinary readers// tolerate malformed values as absent; that must not authorize a handoff.+ if (holdsHitlRequests(state)) return false;const pendingKeys = [- "eve.runtime.pendingAuthorization","eve.runtime.pendingInputBatch","eve.runtime.pendingCoordinationBatch","eve.runtime.deferredStepInput",@@ -48,12 +48,6 @@ export function isSessionStateIdleForHandoff(input: {if (pendingKeys.some((key) => state?.[key] !== undefined)) return false;const batches = state?.["eve.runtime.pendingInputBatches"];if (batches !== undefined && (!Array.isArray(batches) || batches.length > 0)) return false;- const proxyRequests = state?.["eve.runtime.proxyInputRequests"];- if (- proxyRequests !== undefined &&- (!isObject(proxyRequests) || Object.keys(proxyRequests).length > 0)- )- return false;const projection = storedProjection(state);return (workflowToolRuns.length === 0 &&diff --git a/packages/eve/src/execution/session/handoff.ts b/packages/eve/src/execution/session/handoff.tsindex e7150bd19..25b17d95e 100644--- a/packages/eve/src/execution/session/handoff.ts+++ b/packages/eve/src/execution/session/handoff.ts@@ -26,7 +26,7 @@ import { isObject } from "#shared/guards.js";* A newer successor must always accept older checkpoints: every bump adds the* upgrade from the previous version in `checkpoint-migrations.ts`.*/-export const SESSION_CHECKPOINT_VERSION = 14;+export const SESSION_CHECKPOINT_VERSION = 15;/** Everything a successor needs to continue an idle session. Hooks are derived from the state. */export interface SessionCheckpoint {diff --git a/packages/eve/src/execution/session/pending-turn-state.ts b/packages/eve/src/execution/session/pending-turn-state.tsindex 6f4d61afe..22592d345 100644--- a/packages/eve/src/execution/session/pending-turn-state.ts+++ b/packages/eve/src/execution/session/pending-turn-state.ts@@ -1,4 +1,4 @@-import { getPendingAuthorization } from "#harness/authorization.js";+import { readHitlState } from "#harness/hitl/index.js";import { sessionView } from "#harness/session-machine/commit.js";import { ownOpenRequestIds } from "#harness/session-machine/transitions.js";import { runtimeWait } from "#harness/session-machine/view.js";@@ -23,11 +23,14 @@ export function derivePendingState(readonly pendingCoordinationCallIds?: readonly string[];readonly pendingTaskToolCalls?: readonly TaskToolCall[];} {- const pendingAuth = getPendingAuthorization(session.state);+ const { signIns } = readHitlState(session.state);const base = {- authorizationAttemptIds: pendingAuth?.challenges.flatMap((challenge) =>- challenge.attemptId === undefined ? [] : [challenge.attemptId],- ),+ authorizationAttemptIds:+ signIns.length === 0+ ? undefined+ : signIns.flatMap((challenge) =>+ challenge.attemptId === undefined ? [] : [challenge.attemptId],+ ),hasPendingAuthorization: openSignIns(projection).length > 0,hasPendingInputBatch: ownOpenRequestIds(sessionView(projection, session.state)).size > 0,};diff --git a/packages/eve/src/execution/session/turn-connection-approval.integration.test.ts b/packages/eve/src/execution/session/turn-connection-approval.integration.test.tsindex d56eb40c3..989f78928 100644--- a/packages/eve/src/execution/session/turn-connection-approval.integration.test.ts+++ b/packages/eve/src/execution/session/turn-connection-approval.integration.test.ts@@ -16,7 +16,11 @@ import {getApprovalAuditState,markApprovalCandidateAuthorizationRequired,} from "#harness/hitl/candidates.js";-import { CallbackBaseUrlKey, setPendingAuthorization } from "#harness/authorization.js";+import { CallbackBaseUrlKey } from "#harness/authorization.js";++import { withSignIns } from "#harness/hitl/sign-ins.js";+import { readHitlState, writeHitlState } from "#harness/hitl/requests.js";+import { ConnectionAuthorizationRequiredError } from "#connections/errors.js";import { defineInteractiveAuthorization } from "#shared/connection-types.js";import { suspendedSteps } from "#harness/session-machine/view.js";@@ -629,17 +633,15 @@ describe("turn connection approval restoration", () => {challenge: { url: "https://example.com/sign-in" },},];- fixture.updateSession((session) => ({- ...session,- state: setPendingAuthorization(- markApprovalCandidateAuthorizationRequired({- state: session.state,- candidateId: candidate.candidateId,- authorizationChallenges: challenges,- }),- { challenges },- ),- }));+ fixture.updateSession((session) => {+ const state = markApprovalCandidateAuthorizationRequired({+ state: session.state,+ candidateId: candidate.candidateId,+ authorizationChallenges: challenges,+ });+ const signIns = withSignIns(readHitlState(state).signIns, challenges);+ return { ...session, state: writeHitlState({ state }, { signIns }).state };+ });clearDurableDynamicCallbacks(sessionId);const start = fixture.events.length;await fixture.step({diff --git a/packages/eve/src/execution/session/turn-step.test.ts b/packages/eve/src/execution/session/turn-step.test.tsindex d76c79c2d..5114c7f80 100644--- a/packages/eve/src/execution/session/turn-step.test.ts+++ b/packages/eve/src/execution/session/turn-step.test.ts@@ -49,8 +49,8 @@ import { APPROVED_CALL_INTERRUPTED_MESSAGE } from "#harness/hitl/approved-calls.import { textStreamResult } from "#internal/testing/approval-resume.js";import { openInputs } from "#protocol/session-projection.js";import type { InputRequest } from "#shared/input.js";-import { getPendingAuthorization, setPendingAuthorization } from "#harness/authorization.js";-import { upsertProxyInputRequests } from "#harness/proxy-input-requests.js";+import { withSignIns } from "#harness/hitl/sign-ins.js";+import { readHitlState, writeHitlState } from "#harness/hitl/requests.js";import {parkedSteps,positionOf,@@ -59,6 +59,7 @@ import {withParkedStep,withPublished,withQueuedInput,+ withRelays,} from "#internal/testing/session-machine.js";import type { HarnessSession, StepFn, StepInput, StepResult } from "#harness/types.js";import { createRuntimeHookRegistry } from "#runtime/hooks/registry.js";@@ -389,24 +390,26 @@ afterEach(() => {describe("routeProxiedDeliverStep", () => {it("replies to the saved child inbox after its continuation alias changes", async () => {- const session = upsertProxyInputRequests({- entries: [- [- "request-1",- {- childContinuationToken: "stale-alias",- childSessionInbox: { sessionId: "original-child" },- event: REQUEST_EVENT,- kind: "question",- },- ],- ],- forChildContinuationToken: "stale-alias",- session: createStubSession({+ const session = withRelays(+ createStubSession({continuationToken: "parent-token",sessionId: "parent-session",}),- });+ {+ entries: [+ [+ "request-1",+ {+ childContinuationToken: "stale-alias",+ childSessionInbox: { sessionId: "original-child" },+ event: REQUEST_EVENT,+ kind: "question",+ },+ ],+ ],+ forChildContinuationToken: "stale-alias",+ },+ );installSessionStoreMocks([session]);await routeProxiedDeliverStep({@@ -453,7 +456,7 @@ describe("routeProxiedDeliverStep", () => {});it("answers a root question once when one delivery carries several messages", async () => {- const session = upsertProxyInputRequests({+ const session = withRelays(createStubSession(), {entries: [["ask-1",@@ -468,7 +471,6 @@ describe("routeProxiedDeliverStep", () => {],],forChildContinuationToken: "ask-1",- session: createStubSession(),});installSessionStoreMocks([session]);@@ -501,7 +503,7 @@ describe("routeProxiedDeliverStep", () => {principalId: "alice",principalType: "user",};- const session = upsertProxyInputRequests({+ const session = withRelays(createStubSession(), {entries: [["approval-1",@@ -514,7 +516,6 @@ describe("routeProxiedDeliverStep", () => {],],forChildContinuationToken: "child-token",- session: createStubSession(),});installSessionStoreMocks([session]);@@ -567,11 +568,13 @@ describe("routeProxiedDeliverStep", () => {requestId,})),});- const session = upsertProxyInputRequests({- entries: requestIds.map((requestId) => [requestId, approvalRoute] as const),- forChildContinuationToken: "child-token",- session: withPublished(withOpenTurn(createStubSession(), REQUEST_EVENT), [relayed]),- });+ const session = withRelays(+ withPublished(withOpenTurn(createStubSession(), REQUEST_EVENT), [relayed]),+ {+ entries: requestIds.map((requestId) => [requestId, approvalRoute] as const),+ forChildContinuationToken: "child-token",+ },+ );// Read back what each step persists, so a later step sees the routes it left.vi.mocked(readDurableSession).mockImplementation((state) => state.snapshot!.session);return replaceDurableSessionSnapshot({ session, state: createStubSessionState() });@@ -633,7 +636,7 @@ describe("routeProxiedDeliverStep", () => {},],])("does not answer a delegated %s question from steering text", async (_, serializedContext) => {- const session = upsertProxyInputRequests({+ const session = withRelays(createStubSession(), {entries: [["ask-1",@@ -651,7 +654,6 @@ describe("routeProxiedDeliverStep", () => {],],forChildContinuationToken: "ask-1",- session: createStubSession(),});installSessionStoreMocks([session]);@@ -676,23 +678,33 @@ describe("routeProxiedDeliverStep", () => {principalId: "user-1",principalType: "user",};- const session = upsertProxyInputRequests({- entries: [- [- "request-1",- { childContinuationToken: "child-token", event: REQUEST_EVENT, kind: "tool-approval" },- ],- [- "request-2",- { childContinuationToken: "child-token", event: REQUEST_EVENT, kind: "tool-approval" },- ],- ],- forChildContinuationToken: "child-token",- session: createStubSession({+ const session = withRelays(+ createStubSession({continuationToken: "parent-token",sessionId: "parent-session",}),- });+ {+ entries: [+ [+ "request-1",+ {+ childContinuationToken: "child-token",+ event: REQUEST_EVENT,+ kind: "tool-approval",+ },+ ],+ [+ "request-2",+ {+ childContinuationToken: "child-token",+ event: REQUEST_EVENT,+ kind: "tool-approval",+ },+ ],+ ],+ forChildContinuationToken: "child-token",+ },+ );installSessionStoreMocks([session]);const result = await routeProxiedDeliverStep({@@ -735,19 +747,8 @@ describe("routeProxiedDeliverStep", () => {replyTo: { kind: "hook" as const, token: "parent-turn" },subagentName: "research",};- const session = upsertProxyInputRequests({- entries: [- [- "child-a",- { childContinuationToken: "child-token-a", event: REQUEST_EVENT, kind: "question" },- ],- [- "child-b",- { childContinuationToken: "child-token-b", event: REQUEST_EVENT, kind: "question" },- ],- ],- forChildContinuationToken: "child-token-a",- session: upsertProxyInputRequests({+ const session = withRelays(+ withRelays(createStubSession(), {entries: [["child-b",@@ -755,9 +756,21 @@ describe("routeProxiedDeliverStep", () => {],],forChildContinuationToken: "child-token-b",- session: createStubSession(),}),- });+ {+ entries: [+ [+ "child-a",+ { childContinuationToken: "child-token-a", event: REQUEST_EVENT, kind: "question" },+ ],+ [+ "child-b",+ { childContinuationToken: "child-token-b", event: REQUEST_EVENT, kind: "question" },+ ],+ ],+ forChildContinuationToken: "child-token-a",+ },+ );installSessionStoreMocks([session]);const delivery = {@@ -2713,19 +2726,22 @@ describe("turnStep", () => {const bob: SessionAuthContext = { ...alice, principalId: "slack:bob" };installSessionStoreMocks([createStubSession({- state: setPendingAuthorization(undefined, {- challenges: [- {- attemptId: "attempt-linear",- challenge: { url: "https://idp.example/authorize" },- hookUrl: "https://agent.example/callback",- name: "linear",- principal: { id: "slack:alice", issuer: "slack", type: "user" },- principalId: "slack:alice",- requester: alice,- },- ],- }),+ state: writeHitlState(+ { state: undefined },+ {+ signIns: [+ {+ attemptId: "attempt-linear",+ challenge: { url: "https://idp.example/authorize" },+ hookUrl: "https://agent.example/callback",+ name: "linear",+ principal: { id: "slack:alice", issuer: "slack", type: "user" },+ principalId: "slack:alice",+ requester: alice,+ },+ ],+ },+ ).state,}),]);const ctx = new ContextContainer();@@ -2769,20 +2785,23 @@ describe("turnStep", () => {name: "authorization",withPending: (session: HarnessSession): HarnessSession => ({...session,- state: setPendingAuthorization(session.state, {- challenges: [- {- attemptId: "attempt-statuspage",- challenge: {- instructions: "Sign in to continue",- url: "https://idp.example/authorize",+ state: writeHitlState(+ { state: session.state },+ {+ signIns: withSignIns(readHitlState(session.state).signIns, [+ {+ attemptId: "attempt-statuspage",+ challenge: {+ instructions: "Sign in to continue",+ url: "https://idp.example/authorize",+ },+ hookUrl: "https://app.example/callback",+ name: "statuspage",+ principal: { type: "app" },},- hookUrl: "https://app.example/callback",- name: "statuspage",- principal: { type: "app" },- },- ],- }),+ ]),+ },+ ).state,}),},{@@ -3218,7 +3237,7 @@ describe("turnStep", () => {};const session = createStubSession({history: [{ content: "visible", kind: "user", role: "user" }],- state: setPendingAuthorization({ retained: "yes" }, { challenges: [challenge] }),+ state: writeHitlState({ state: { retained: "yes" } }, { signIns: [challenge] }).state,});const turnInput = {context: ["Current context"],@@ -3252,7 +3271,7 @@ describe("turnStep", () => {let observedStepInput: unknown = "not-called";vi.mocked(createExecutionNodeStep).mockImplementation(() => {return async (session, stepInput): Promise<StepResult> => {- observedPendingAuth = getPendingAuthorization(session.state);+ observedPendingAuth = readHitlState(session.state).signIns;observedStepInput = stepInput;return { next: null, session };};@@ -3278,7 +3297,7 @@ describe("turnStep", () => {sessionState: createStubSessionState(),});- expect(observedPendingAuth).toBeUndefined();+ expect(observedPendingAuth).toEqual([]);expect(observedStepInput).toEqual(inputKind === "current"? { message: `thread=unset; user=${turnInput.message}` }@@ -3291,7 +3310,7 @@ describe("turnStep", () => {]);const persistedSession = vi.mocked(createDurableSessionValues).mock.calls.at(-1)?.[0];expect(persistedSession?.state?.retained).toBe("yes");- expect(getPendingAuthorization(persistedSession?.state)).toBeUndefined();+ expect(readHitlState(persistedSession?.state).signIns).toEqual([]);},);});diff --git a/packages/eve/src/execution/session/turn-step.ts b/packages/eve/src/execution/session/turn-step.tsindex 8d5e32b9d..0be5622cb 100644--- a/packages/eve/src/execution/session/turn-step.ts+++ b/packages/eve/src/execution/session/turn-step.ts@@ -36,13 +36,19 @@ import * as agentTraceState from "#tracing/eve/agent-trace-context-store.js";import { matchAuthorizationCallbacks } from "#execution/authorization-callback-match.js";import { isTurnCancellation, throwIfTurnAborted } from "#harness/turn-cancellation.js";import { setChannelContext } from "#execution/channel-context.js";-import { activeTurnId, isBetweenTurns, turnPosition } from "#harness/session-machine/view.js";+import {+ activeTurnId,+ isBetweenTurns,+ storedProjection,+ turnPosition,+} from "#harness/session-machine/view.js";import {currentProjection,enterSessionProjection,saveSessionProjection,} from "#harness/session-machine/current.js";-import { dropClosedRecords } from "#harness/session-machine/commit.js";+import { saveTransition, dropClosedRecords, sessionView } from "#harness/session-machine/commit.js";+import { matchSignIns } from "#harness/session-machine/transitions.js";import {sessionStartedForResolvers,turnStartedForResolvers,@@ -60,12 +66,8 @@ import { withSessionStateDelta } from "#execution/session/state-delta.js";import { openSessionEventPublisher } from "#execution/publish-session-events.js";import { createTurnEventHandler } from "#execution/session/turn-event-handler.js";import { derivePendingState } from "#execution/session/pending-turn-state.js";-import {- CallbackBaseUrlKey,- clearPendingAuthorization,- getPendingAuthorization,- PendingAuthorizationResultKey,-} from "#harness/authorization.js";+import { CallbackBaseUrlKey, PendingAuthorizationResultKey } from "#harness/authorization.js";+import { readHitlState } from "#harness/hitl/index.js";import { resolveWorkflowCallbackBaseUrl } from "#execution/workflow-callback-url.js";import { countRunUsage } from "#execution/agent-sessions/usage.js";import {@@ -152,22 +154,20 @@ async function runSessionStepBody(// Outside a workflow context (e.g. tests) — getHookUrl will return undefined.}- const pendingAuth = getPendingAuthorization(durableSession.state);+ const { signIns } = readHitlState(durableSession.state);let completedAuths: ReturnType<typeof matchAuthorizationCallbacks>["matches"] | undefined;- if (pendingAuth && delivery !== undefined) {- const { matches, remainingPayloads } = matchAuthorizationCallbacks(- pendingAuth,- delivery.payloads,- );+ if (signIns.length > 0 && delivery !== undefined) {+ const { matches, remainingPayloads } = matchAuthorizationCallbacks(signIns, delivery.payloads);delivery = { ...delivery, payloads: remainingPayloads };if (matches.length > 0) {const matchedAttemptIds = matches.map((match) => match.result.attemptId);const authResults = matches.map((match) => match.result);ctx.set(PendingAuthorizationResultKey, authResults);- durableSession = {- ...durableSession,- state: clearPendingAuthorization(durableSession.state, matchedAttemptIds),- };+ // The session stops waiting on them; the turn they resume reports their completion.+ const view = sessionView(storedProjection(durableSession.state), durableSession.state);+ const transition = matchSignIns(view, { attemptIds: matchedAttemptIds });+ if (transition.events.length !== 0) throw new Error("matchSignIns must not emit events.");+ durableSession = saveTransition(durableSession, transition);completedAuths = matches;if (remainingPayloads.length === 0) delivery = undefined;}diff --git a/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts b/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.tsindex 90cefab73..d605d05f5 100644--- a/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts+++ b/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts@@ -1,17 +1,16 @@import { describe, expect, it } from "vitest";+import { readHitlState } from "#harness/hitl/requests.js";+import type { HarnessSession, SessionStateMap } from "#harness/types.js";import { readDurableSession } from "#execution/durable-session-store.js";import { settleCancelledTurnStep } from "#execution/settle-cancelled-turn-step.js";-import {- getProxyInputRequests,- upsertProxyInputRequestState,- type ProxyInputRequest,-} from "#harness/proxy-input-requests.js";++import type { ProxyInputRequest } from "#harness/hitl/relays.js";import { filterEventsByType } from "#internal/testing/events.js";import { createInputRequestedEvent, type MessageStreamEvent } from "#protocol/message.js";import type { InputRequest } from "#shared/input.js";-import { withPublished } from "#internal/testing/session-machine.js";+import { withPublished, withRelays } from "#internal/testing/session-machine.js";import {accumulateTurnUsage,getTurnUsageState,@@ -138,7 +137,7 @@ describe("settleCancelledTurnStep", () => {[{ kind: "question", outcome: "cancelled", requestId: "deploy-run-ask-1" }],[{ kind: "tool-approval", outcome: "cancelled", requestId: "reviewer-approval-1" }],]);- expect(getProxyInputRequests(readDurableSession(result.sessionState).state).size).toBe(0);+ expect(readHitlState(readDurableSession(result.sessionState).state).relays.size).toBe(0);});});@@ -158,11 +157,13 @@ function relay(const published = withPublished({ ...openSession, state }, [createInputRequestedEvent({ callId: `${requestId}-served`, requests: [request], ...event }),]);- return upsertProxyInputRequestState({- entries: [[requestId, { ...route, childContinuationToken: requestId, event }]],- forChildContinuationToken: requestId,- state: published.state,- });+ return withRelays(+ { state: published.state },+ {+ entries: [[requestId, { ...route, childContinuationToken: requestId, event }]],+ forChildContinuationToken: requestId,+ },+ ).state;}const openSession: HarnessSession = {diff --git a/packages/eve/src/execution/tasks/session.test.ts b/packages/eve/src/execution/tasks/session.test.tsindex 6187a1715..ef7de7aa1 100644--- a/packages/eve/src/execution/tasks/session.test.ts+++ b/packages/eve/src/execution/tasks/session.test.ts@@ -13,9 +13,9 @@ import {writeTaskTable,type TaskTable,} from "#execution/tasks/table.js";-import { upsertProxyInputRequestState } from "#harness/proxy-input-requests.js";+import type { HarnessSession } from "#harness/types.js";-import { withPublished } from "#internal/testing/session-machine.js";+import { withPublished, withRelays } from "#internal/testing/session-machine.js";import { createInputRequestedEvent } from "#protocol/message.js";import { createTestSessionState } from "#internal/testing/session-state.js";@@ -24,20 +24,36 @@ import { createTestSessionState } from "#internal/testing/session-state.js";// reach the session's own instrumentation.vi.mock("#internal/workflow/runtime.js", () => ({ resumeHook: vi.fn(async () => {}) }));const { published } = vi.hoisted(() => ({ published: [] as unknown[] }));-vi.mock("#execution/publish-session-events.js", () => {- const publisher =- (origin: "own" | "relayed") =>- async (+vi.mock("#execution/publish-session-events.js", async () => {+ const { readDurableSession } = await import("#execution/durable-session-store.js");+ const { sessionView } = await import("#harness/session-machine/commit.js");+ const { storedProjection } = await import("#harness/session-machine/view.js");+ return {+ commitSessionStep: async (+ target: {+ readonly serializedContext: Record<string, unknown>;+ readonly sessionState: Parameters<typeof readDurableSession>[0];+ },+ decide: (view: ReturnType<typeof sessionView>) => readonly { readonly events: unknown[] }[],+ options: { readonly origin: "own" | "relayed" },+ ) => {+ const { state } = readDurableSession(target.sessionState);+ for (const transition of decide(sessionView(storedProjection(state), state))) {+ published.push(...transition.events.map((event) => ({ event, origin: options.origin })));+ }+ return { serializedContext: target.serializedContext, sessionState: target.sessionState };+ },+ publishSessionEvents: async (target: {readonly serializedContext: Record<string, unknown>;readonly sessionState: unknown;},events: readonly unknown[],) => {- published.push(...events.map((event) => ({ event, origin })));+ published.push(...events.map((event) => ({ event, origin: "own" })));return { serializedContext: target.serializedContext, sessionState: target.sessionState };- };- return { publishSessionEvents: publisher("own"), relaySessionEvents: publisher("relayed") };+ },+ };});const REQUEST_EVENT = { sequence: 3, stepIndex: 1, turnId: "turn_1" };@@ -259,22 +275,24 @@ function withQuestion(session: DurableSession, runId: string): DurableSession {...REQUEST_EVENT,}),]);- const state = upsertProxyInputRequestState({- entries: [- [- requestId,- {- childContinuationToken: requestId,- event: REQUEST_EVENT,- kind: "question",- runId,- workflowAsk: { control: `${runId}-control` },- reply: {},- },+ const state = withRelays(+ { state: session.state },+ {+ entries: [+ [+ requestId,+ {+ childContinuationToken: requestId,+ event: REQUEST_EVENT,+ kind: "question",+ runId,+ workflowAsk: { control: `${runId}-control` },+ reply: {},+ },+ ],],- ],- forChildContinuationToken: requestId,- state: session.state,- });+ forChildContinuationToken: requestId,+ },+ ).state;return { ...session, state };}diff --git a/packages/eve/src/execution/tasks/steps.ts b/packages/eve/src/execution/tasks/steps.tsindex ab62c1d8d..7d9c8c678 100644--- a/packages/eve/src/execution/tasks/steps.ts+++ b/packages/eve/src/execution/tasks/steps.ts@@ -23,12 +23,11 @@ import {} from "#execution/tasks/table.js";import { ignoreGoneTarget } from "#execution/tasks/workflow-target.js";import { countRunUsage } from "#execution/agent-sessions/usage.js";-import {- publishSessionEvents,- relaySessionEvents,- type PublishedSessionEvents,- type SessionStepState,+import type {+ PublishedSessionEvents,+ SessionStepState,} from "#execution/publish-session-events.js";+import { commitSessionStep } from "#execution/publish-session-events.js";import {withSessionStateDelta,type SessionStateTransition,@@ -39,12 +38,12 @@ import type {WorkflowToolRunOutcomeMessage,} from "#execution/tools/workflow/messages.js";import { workflowToolRunFailureOutput } from "#execution/tools/workflow/owner-inbox.js";-import { getProxyInputRequests } from "#harness/proxy-input-requests.js";-import { sessionView } from "#harness/session-machine/commit.js";+import { readHitlState } from "#harness/hitl/index.js";+import type { Transition } from "#harness/session-machine/commit.js";import { finishRun, settleTask } from "#harness/session-machine/transitions.js";-import { storedProjection } from "#harness/session-machine/view.js";+import type { SessionView } from "#harness/session-machine/view.js";import { resumeHook } from "#internal/workflow/runtime.js";-import type { TaskCancelReason, UnstampedMessageStreamEvent } from "#protocol/message.js";+import type { TaskCancelReason } from "#protocol/message.js";/** The messages a task's run sends that change its record. */export type TaskRunMessage = Extract<@@ -68,8 +67,8 @@ export async function applyTaskRunMessage(return { serializedContext: input.serializedContext, sessionState: input.sessionState };}let table = readTaskTable(session.state);- const events: UnstampedMessageStreamEvent[] = [];- let withdrawn: readonly UnstampedMessageStreamEvent[] = [];+ const settles: Decision[] = [];+ const withdraws: Decision[] = [];switch (message.kind) {case "started": {const started = markTaskRunStarted(table, taskId, message.from.runId);@@ -83,7 +82,7 @@ export async function applyTaskRunMessage(const record = findTask(table, taskId);const settled = settleTaskCalls(table, { callIds: message.callIds, outcome, taskId });table = settled.table;- events.push(...taskSettledEvents(session, record, settled.settled, outcome));+ settles.push(...taskSettled(record, settled.settled, outcome));break;}case "usage":@@ -94,21 +93,18 @@ export async function applyTaskRunMessage(const outcome = toOutcome(message);const record = findTask(table, taskId);const settled = settleRemainingTaskCalls(table, taskId, outcome);- events.push(...taskSettledEvents(session, record, settled.settled, outcome));+ settles.push(...taskSettled(record, settled.settled, outcome));table = finishTaskRun(settled.table, taskId, message.from.runId);// Nobody can answer what a finished run relayed, so channels stop offering it.- withdrawn = finishRun(viewOf(session), {- requestIds: runRequestIds(session, message.from.runId),- taskId,- }).events;+ const requestIds = runRequestIds(session, message.from.runId);+ withdraws.push((view) => finishRun(view, { requestIds, taskId }));break;}}- const relayed = await relaySessionEvents(- { ...input, sessionState: saveTable(input.sessionState, session, table) },- withdrawn,- );- return await publishSessionEvents({ ...input, ...relayed }, events);+ return await commitTaskDecisions(input, saveTable(input.sessionState, session, table), {+ settles,+ withdraws,+ });}/**@@ -135,39 +131,60 @@ async function cancelTasks(): Promise<PublishedSessionEvents> {const session = readDurableSession(input.sessionState);let table = readTaskTable(session.state);- const events: UnstampedMessageStreamEvent[] = [];- const view = viewOf(session);- const withdrawn: UnstampedMessageStreamEvent[] = [];+ const settles: Decision[] = [];+ const withdraws: Decision[] = [];const outcome: TaskOutcome = { reason: input.reason, status: "cancelled" };for (const taskId of input.taskIds) {const record = findTask(table, taskId);const cancelled = cancelTask(table, taskId);table = cancelled.table;- events.push(...taskSettledEvents(session, record, cancelled.settled, outcome));+ settles.push(...taskSettled(record, cancelled.settled, outcome));if (cancelled.send === undefined) continue;// A `task()` run's cancel settles what it relayed; a `serve()` run withdraws its own.if (record?.resumable === false) {const requestIds = runRequestIds(session, cancelled.send.run.runId);- withdrawn.push(...finishRun(view, { requestIds, taskId }).events);+ withdraws.push((view) => finishRun(view, { requestIds, taskId }));}await sendTaskRunCommands(cancelled.send);}- const relayed = await relaySessionEvents(- { ...input, sessionState: saveTable(input.sessionState, session, table) },- withdrawn,+ return await commitTaskDecisions(input, saveTable(input.sessionState, session, table), {+ settles,+ withdraws,+ });+}++/** A transition a task step decides against the session it commits to. */+type Decision = (view: SessionView) => Transition;++/**+ * Commits a task step's decisions to the session with its saved table: the requests it+ * withdraws, which this session relayed, and then its own `task.settled` events.+ */+async function commitTaskDecisions(+ input: SessionStepState,+ sessionState: DurableSessionState,+ decisions: { readonly settles: readonly Decision[]; readonly withdraws: readonly Decision[] },+): Promise<PublishedSessionEvents> {+ const relayed = await commitSessionStep(+ { ...input, sessionState },+ (view) => decisions.withdraws.map((decide) => decide(view)),+ { origin: "relayed" },+ );+ return await commitSessionStep(+ { ...input, ...relayed },+ (view) => decisions.settles.map((decide) => decide(view)),+ { origin: "own" },);- return await publishSessionEvents({ ...input, ...relayed }, events);}-/** The `task.settled` events for a task's settled calls; calls only settle on a known task. */-function taskSettledEvents(- session: DurableSession,+/** Settles a task's settled calls; calls only settle on a known task. */+function taskSettled(record: TaskRecord | undefined,calls: readonly TaskCall[],outcome: TaskOutcome,-): readonly UnstampedMessageStreamEvent[] {+): readonly Decision[] {if (record === undefined) return [];- return settleTask(viewOf(session), { calls, outcome, task: record }).events;+ return [(view) => settleTask(view, { calls, outcome, task: record })];}/**@@ -230,15 +247,11 @@ function countTaskRunUsage(/** The requests a run relayed: its own questions and those of the sessions it opened. */function runRequestIds(session: DurableSession, runId: string): readonly string[] {- return [...getProxyInputRequests(session.state)]+ return [...readHitlState(session.state).relays].filter(([, route]) => route.runId === runId).map(([requestId]) => requestId);}-function viewOf(session: DurableSession) {- return sessionView(storedProjection(session.state), session.state);-}-function saveTable(state: DurableSessionState,session: DurableSession,diff --git a/packages/eve/src/execution/tasks/task-run-usage.test.ts b/packages/eve/src/execution/tasks/task-run-usage.test.tsindex 3bc1f5c2d..d7077085f 100644--- a/packages/eve/src/execution/tasks/task-run-usage.test.ts+++ b/packages/eve/src/execution/tasks/task-run-usage.test.ts@@ -24,14 +24,7 @@ import type { TokenUsage } from "#shared/token-usage.js";// The settled calls' stream events are not under test; the committed session is.vi.mock("#execution/publish-session-events.js", () => ({- publishSessionEvents: async ({- serializedContext,- sessionState,- }: {- readonly serializedContext: Record<string, unknown>;- readonly sessionState: unknown;- }) => ({ serializedContext, sessionState }),- relaySessionEvents: async ({+ commitSessionStep: async ({serializedContext,sessionState,}: {diff --git a/packages/eve/src/execution/tools/workflow/answer.ts b/packages/eve/src/execution/tools/workflow/answer.tsindex 90a0e251b..e677e33f4 100644--- a/packages/eve/src/execution/tools/workflow/answer.ts+++ b/packages/eve/src/execution/tools/workflow/answer.ts@@ -3,7 +3,7 @@ import type {WorkflowToolRunAnswer,WorkflowToolRunControlMessage,} from "#execution/tools/workflow/messages.js";-import type { WorkflowAskRoute } from "#harness/proxy-input-requests.js";+import type { WorkflowAskRoute } from "#harness/hitl/relays.js";import { resumeHook } from "#internal/workflow/runtime.js";import type { InputResponse } from "#shared/input.js";import type { ToolInputResponseResponder } from "#tools/definition.js";diff --git a/packages/eve/src/execution/tools/workflow/withdraw-step.ts b/packages/eve/src/execution/tools/workflow/withdraw-step.tsindex e6b81a138..7af5475e4 100644--- a/packages/eve/src/execution/tools/workflow/withdraw-step.ts+++ b/packages/eve/src/execution/tools/workflow/withdraw-step.ts@@ -1,9 +1,9 @@import { readDurableSession } from "#execution/durable-session-store.js";-import {- relaySessionEvents,- type PublishedSessionEvents,- type SessionStepState,+import type {+ PublishedSessionEvents,+ SessionStepState,} from "#execution/publish-session-events.js";+import { commitSessionStep } from "#execution/publish-session-events.js";import {withSessionStateDelta,type SessionStateTransition,@@ -11,10 +11,9 @@ import {import type { WorkflowToolRunControlMessage } from "#execution/tools/workflow/messages.js";import { ignoreGoneTarget } from "#execution/tasks/workflow-target.js";import { resumeHook } from "#internal/workflow/runtime.js";-import { getProxyInputRequests, type ProxyInputRequest } from "#harness/proxy-input-requests.js";-import { sessionView } from "#harness/session-machine/commit.js";+import { readHitlState } from "#harness/hitl/index.js";+import type { ProxyInputRequest } from "#harness/hitl/relays.js";import { finishRun } from "#harness/session-machine/transitions.js";-import { storedProjection } from "#harness/session-machine/view.js";/*** Decides a run's request to withdraw a question. A question the session@@ -74,10 +73,11 @@ export async function relayWithdrawnRequests(input: SessionStepState,select: (requestId: string, route: ProxyInputRequest) => boolean,): Promise<PublishedSessionEvents> {- const session = readDurableSession(input.sessionState);- const requestIds = [...getProxyInputRequests(session.state)]+ const { state } = readDurableSession(input.sessionState);+ const requestIds = [...readHitlState(state).relays].filter(([requestId, route]) => select(requestId, route)).map(([requestId]) => requestId);- const view = sessionView(storedProjection(session.state), session.state);- return await relaySessionEvents(input, finishRun(view, { requestIds }).events);+ return await commitSessionStep(input, (view) => [finishRun(view, { requestIds })], {+ origin: "relayed",+ });}diff --git a/packages/eve/src/harness/authorization.test.ts b/packages/eve/src/harness/authorization.test.tsindex 2b13e2d57..3653c3933 100644--- a/packages/eve/src/harness/authorization.test.ts+++ b/packages/eve/src/harness/authorization.test.ts@@ -4,15 +4,17 @@ import { ContextContainer, contextStorage } from "#context/container.js";import { SessionIdKey } from "#context/keys.js";import {CallbackBaseUrlKey,- clearPendingAuthorization,consumeAuthorizationResult,- getPendingAuthorization,getHookUrl,PendingAuthorizationResultKey,+} from "#harness/authorization.js";+import {+ withSignIns,+ signInAttemptKey,resolveActiveAuthorizationChallenges,- setPendingAuthorization,supersededChallenges,-} from "#harness/authorization.js";+} from "#harness/hitl/sign-ins.js";+import type { ConnectionPrincipal } from "#shared/connection-types.js";afterEach(() => {@@ -109,43 +111,29 @@ function candidateChallenge(name: string, candidateId: string) {describe("pending authorization state", () => {it("merges concurrent candidate challenges by authorization name", () => {- const first = setPendingAuthorization(undefined, {- challenges: [candidateChallenge("candidate-1:github", "candidate-1")],- });- const second = setPendingAuthorization(first, {- challenges: [candidateChallenge("candidate-2:github", "candidate-2")],- });+ const first = withSignIns([], [candidateChallenge("candidate-1:github", "candidate-1")]);+ const second = withSignIns(first, [candidateChallenge("candidate-2:github", "candidate-2")]);- expect(getPendingAuthorization(second)?.challenges).toEqual([+ expect(second).toEqual([expect.objectContaining({ candidateId: "candidate-1", name: "candidate-1:github" }),expect.objectContaining({ candidateId: "candidate-2", name: "candidate-2:github" }),]);});it("replaces a repeated challenge without duplicating it", () => {- const first = setPendingAuthorization(undefined, {- challenges: [candidateChallenge("candidate-1:github", "candidate-1")],- });- const second = setPendingAuthorization(first, {- challenges: [- {- ...candidateChallenge("candidate-1:github", "candidate-1"),- hookUrl: "https://eve.example/refreshed",- },- ],- });-- expect(getPendingAuthorization(second)?.challenges).toEqual([- expect.objectContaining({ hookUrl: "https://eve.example/refreshed" }),+ const first = withSignIns([], [candidateChallenge("candidate-1:github", "candidate-1")]);+ const second = withSignIns(first, [+ {+ ...candidateChallenge("candidate-1:github", "candidate-1"),+ hookUrl: "https://eve.example/refreshed",+ },]);++ expect(second).toEqual([expect.objectContaining({ hookUrl: "https://eve.example/refreshed" })]);});it("clears by candidate ID", () => {- const state = setPendingAuthorization(undefined, {- challenges: [candidateChallenge("github", "candidate-1")],- });-- expect(clearPendingAuthorization(state, ["candidate-1"])).toBeUndefined();+ expect(signInAttemptKey(candidateChallenge("github", "candidate-1"))).toBe("candidate-1");});});@@ -165,31 +153,23 @@ describe("pending authorization attempts", () => {it("keeps same-name attempts owned by different principals", () => {const userA = { id: "user-a", issuer: "idp", type: "user" } as const;const userB = { id: "user-b", issuer: "idp", type: "user" } as const;- const first = setPendingAuthorization(undefined, {- challenges: [challenge("linear", "linear-a", userA)],- });- const second = setPendingAuthorization(first, {- challenges: [challenge("linear", "linear-b", userB)],- });+ const first = withSignIns([], [challenge("linear", "linear-a", userA)]);+ const second = withSignIns(first, [challenge("linear", "linear-b", userB)]);- expect(getPendingAuthorization(second)?.challenges).toEqual([+ expect(second).toEqual([challenge("linear", "linear-a", userA),challenge("linear", "linear-b", userB),]);});it("merges distinct names and replaces only the same name", () => {- const first = setPendingAuthorization(undefined, {- challenges: [challenge("linear", "linear-1"), challenge("github", "github-1")],- });- const replaced = setPendingAuthorization(first, {- challenges: [challenge("linear", "linear-2")],- });+ const first = withSignIns(+ [],+ [challenge("linear", "linear-1"), challenge("github", "github-1")],+ );+ const replaced = withSignIns(first, [challenge("linear", "linear-2")]);- expect(getPendingAuthorization(replaced)?.challenges).toEqual([- challenge("github", "github-1"),- challenge("linear", "linear-2"),- ]);+ expect(replaced).toEqual([challenge("github", "github-1"), challenge("linear", "linear-2")]);});it("keeps only the latest same-scope challenge from one batch", () => {@@ -201,11 +181,7 @@ describe("pending authorization attempts", () => {const active = resolveActiveAuthorizationChallenges([first, otherPrincipal, latest]);expect(active).toEqual([otherPrincipal, latest]);- expect(- getPendingAuthorization(- setPendingAuthorization(undefined, { challenges: [first, otherPrincipal, latest] }),- )?.challenges,- ).toEqual([otherPrincipal, latest]);+ expect(withSignIns([], [first, otherPrincipal, latest])).toEqual([otherPrincipal, latest]);});it("shows one sign-in per Vercel Connect grant across tools and connections", () => {@@ -215,9 +191,7 @@ describe("pending authorization attempts", () => {...challenge(name, attemptId, principal),grant: "linear/myagent",});- const pending = setPendingAuthorization(undefined, {- challenges: [grant("linear", "connection")],- });+ const pending = withSignIns([], [grant("linear", "connection")]);const listTool = grant("list_issues__linear_myagent", "list-tool");const createTool = grant("create_issue__linear_myagent", "create-tool");const bobTool = grant("create_issue__linear_myagent", "bob-tool", bob);@@ -226,19 +200,18 @@ describe("pending authorization attempts", () => {expect(resolveActiveAuthorizationChallenges([listTool, createTool, bobTool, approval])).toEqual([createTool, bobTool, approval],);- expect(- supersededChallenges(getPendingAuthorization(pending)?.challenges ?? [], [createTool]),- ).toEqual([grant("linear", "connection")]);+ expect(supersededChallenges(pending, [createTool])).toEqual([grant("linear", "connection")]);});it("clears by exact attempt identity", () => {- const state = setPendingAuthorization(undefined, {- challenges: [challenge("linear", "linear-2"), challenge("github", "github-1")],- });+ const state = withSignIns(+ [],+ [challenge("linear", "linear-2"), challenge("github", "github-1")],+ );- expect(clearPendingAuthorization(state, ["linear-1"])).toEqual(state);- expect(- getPendingAuthorization(clearPendingAuthorization(state, ["linear-2"]))?.challenges,- ).toEqual([challenge("github", "github-1")]);+ expect(state.filter((c) => signInAttemptKey(c) !== "linear-1")).toEqual(state);+ expect(state.filter((c) => signInAttemptKey(c) !== "linear-2")).toEqual([+ challenge("github", "github-1"),+ ]);});});diff --git a/packages/eve/src/harness/authorization.ts b/packages/eve/src/harness/authorization.tsindex ceb35b491..552314665 100644--- a/packages/eve/src/harness/authorization.ts+++ b/packages/eve/src/harness/authorization.ts@@ -19,7 +19,7 @@ import {** 1. `startAuthorization` returns `{ challenge, resume? }`. The runtime* stores `resume` on the {@link AuthorizationChallenge} and journals it- * onto `session.state` via {@link setPendingAuthorization} when the turn+ * onto `session.state` when the turn* parks — so it survives the suspend/resume across a `"use step"`* boundary.* 2. The IdP redirect hits the framework callback route, which parses it@@ -296,133 +296,3 @@ export const CallbackBaseUrlKey = new ContextKey<string>("eve.callbackBaseUrl");/** Hook token of a runtime that owns its callback instead of using the session hook. */export const AuthorizationHookKey = new ContextKey<string>("eve.authorizationHook");--// ----------------------------------------------------------------------------// Session state persistence (internal — used by framework only)-// -----------------------------------------------------------------------------const PENDING_AUTHORIZATION_KEY = "eve.runtime.pendingAuthorization";--export interface PendingAuthorizationState {- readonly challenges: readonly AuthorizationChallenge[];-}--export function setPendingAuthorization(- sessionState: Record<string, unknown> | undefined,- value: PendingAuthorizationState,-): Record<string, unknown> {- return {- ...sessionState,- [PENDING_AUTHORIZATION_KEY]: {- challenges: withSignIns(- getPendingAuthorization(sessionState)?.challenges ?? [],- value.challenges,- ),- },- };-}--/** The pending sign-ins once `challenges` are asked for: each replaces the attempt it supersedes. */-export function withSignIns(- previous: readonly AuthorizationChallenge[],- challenges: readonly AuthorizationChallenge[],-): readonly AuthorizationChallenge[] {- const active = resolveActiveAuthorizationChallenges(challenges);- const superseded = supersededChallenges(previous, active);- return [...previous.filter((challenge) => !superseded.includes(challenge)), ...active];-}--/** Keeps the last challenge for each sign-in and principal. */-export function resolveActiveAuthorizationChallenges(- challenges: readonly AuthorizationChallenge[],-): readonly AuthorizationChallenge[] {- return challenges.filter(- (candidate, index) =>- !challenges.slice(index + 1).some((replacement) => sameSignIn(candidate, replacement)),- );-}--/** The attempts in `previous` that `replacements` replace: the same sign-in and principal. */-export function supersededChallenges(- previous: readonly AuthorizationChallenge[],- replacements: readonly AuthorizationChallenge[],-): readonly AuthorizationChallenge[] {- return previous.filter((candidate) =>- replacements.some((replacement) => sameSignIn(candidate, replacement)),- );-}--/**- * Same scope, or the same grant from another scope, such as two tools and a- * connection that all use one Vercel Connect connector. Approval sign-ins- * stay per candidate because each one settles its own approval.- */-function sameSignIn(- left: Pick<AuthorizationChallenge, "candidateId" | "grant" | "name" | "principal">,- right: Pick<AuthorizationChallenge, "candidateId" | "grant" | "name" | "principal">,-): boolean {- const sameGrant =- left.grant !== undefined &&- left.grant === right.grant &&- left.candidateId === right.candidateId;- return (left.name === right.name || sameGrant) && samePrincipal(left.principal, right.principal);-}--function samePrincipal(- left: ConnectionPrincipal | undefined,- right: ConnectionPrincipal | undefined,-): boolean {- if (left === undefined || right === undefined) return left === right;- if (left.type === "app" || right.type === "app") return left.type === right.type;- return left.id === right.id && left.issuer === right.issuer;-}--export function clearPendingAuthorization(- sessionState: Record<string, unknown> | undefined,- attemptIds?: readonly string[],-): Record<string, unknown> | undefined {- if (sessionState === undefined || sessionState[PENDING_AUTHORIZATION_KEY] === undefined) {- return sessionState;- }-- if (attemptIds !== undefined) {- if (attemptIds.length === 0) return sessionState;-- const pending = getPendingAuthorization(sessionState);- if (pending !== undefined) {- const completedAttemptIds = new Set(attemptIds);- const challenges = pending.challenges.filter(- (challenge) => !completedAttemptIds.has(authorizationAttemptKey(challenge)),- );- if (challenges.length > 0) {- return {- ...sessionState,- [PENDING_AUTHORIZATION_KEY]: { challenges },- };- }- }- }-- const state = { ...sessionState };- delete state[PENDING_AUTHORIZATION_KEY];- return Object.keys(state).length > 0 ? state : undefined;-}--function authorizationAttemptKey(challenge: AuthorizationChallenge): string {- return challenge.attemptId ?? challenge.candidateId ?? challenge.name;-}--export function getPendingAuthorization(- sessionState: Record<string, unknown> | undefined,-): PendingAuthorizationState | undefined {- if (!sessionState) return undefined;- const v = sessionState[PENDING_AUTHORIZATION_KEY];- if (typeof v !== "object" || v === null) return undefined;- return v as PendingAuthorizationState;-}--export function hasPendingAuthorization(- sessionState: Record<string, unknown> | undefined,-): boolean {- return getPendingAuthorization(sessionState) !== undefined;-}diff --git a/packages/eve/src/harness/coordination.test.ts b/packages/eve/src/harness/coordination.test.tsindex d77d90e9e..32b41beef 100644--- a/packages/eve/src/harness/coordination.test.ts+++ b/packages/eve/src/harness/coordination.test.ts@@ -13,8 +13,11 @@ import {registerWorkflowToolRun,} from "#harness/workflow-tool-runs.js";+import { readHitlState } from "#harness/hitl/requests.js";+import { withRelays } from "#internal/testing/session-machine.js";+import { toolOutput } from "#tools/model-output.js";-import { getProxyInputRequests, upsertProxyInputRequests } from "#harness/proxy-input-requests.js";+import { setTurnUsageState } from "#harness/turn-tag-state.js";import type { HarnessSession } from "#harness/types.js";import { isRuntimeWorkflowToolAction } from "#shared/action-types.js";@@ -296,19 +299,8 @@ describe("runtime results", () => {address: { runId: "run-1", hookToken: "eve:workflow-tool-run:op-1" },});const answerToken = "eve:workflow-tool-run-answer:run-1:0";- const session = upsertProxyInputRequests({- entries: [- [- "other-request",- {- childContinuationToken: CHILD_CONTINUATION_TOKEN,- event: REQUEST_EVENT,- kind: "question",- },- ],- ],- forChildContinuationToken: CHILD_CONTINUATION_TOKEN,- session: upsertProxyInputRequests({+ const session = withRelays(+ withRelays(withRun, {entries: [[answerToken,@@ -323,9 +315,21 @@ describe("runtime results", () => {],],forChildContinuationToken: answerToken,- session: withRun,}),- });+ {+ entries: [+ [+ "other-request",+ {+ childContinuationToken: CHILD_CONTINUATION_TOKEN,+ event: REQUEST_EVENT,+ kind: "question",+ },+ ],+ ],+ forChildContinuationToken: CHILD_CONTINUATION_TOKEN,+ },+ );const finished = forgetFinishedRuns(session,@@ -335,7 +339,7 @@ describe("runtime results", () => {expect(getBlockingWorkflowToolRuns(finished.session.state)).toEqual([]);expect(finished.requestIds).toEqual([answerToken]);- expect([...getProxyInputRequests(finished.session.state).keys()]).toContain("other-request");+ expect([...readHitlState(finished.session.state).relays.keys()]).toContain("other-request");});it("projects a workflow tool's result through its toModelOutput", async () => {diff --git a/packages/eve/src/harness/coordination.ts b/packages/eve/src/harness/coordination.tsindex b3cba8e4e..31a231444 100644--- a/packages/eve/src/harness/coordination.ts+++ b/packages/eve/src/harness/coordination.ts@@ -11,7 +11,7 @@ import { SKILL_ENTRY_NAME, SKILL_TOOL_NAME } from "#protocol/catalog-tools.js";import { markRuntimeWorkflowToolAction } from "#shared/action-types.js";import { skillTarget } from "#shared/action-request-name.js";import { parseJsonObject, type JsonObject } from "#shared/json.js";-import { getProxyInputRequests } from "#harness/proxy-input-requests.js";+import { readHitlState } from "#harness/hitl/index.js";import {findBlockingWorkflowToolRun,removeBlockingWorkflowToolRuns,@@ -52,7 +52,7 @@ export function forgetFinishedRuns(if (result.kind !== "tool-result") continue;const record = findBlockingWorkflowToolRun(next.state, result.callId, turnId);if (record === undefined) continue;- for (const [requestId, route] of getProxyInputRequests(next.state)) {+ for (const [requestId, route] of readHitlState(next.state).relays) {if (route.runId === record.address.runId) requestIds.push(requestId);}next = removeBlockingWorkflowToolRuns(next, turnId, record.callId);diff --git a/packages/eve/src/harness/hitl/approvals.ts b/packages/eve/src/harness/hitl/approvals.tsindex 8f2e5032c..c41e15658 100644--- a/packages/eve/src/harness/hitl/approvals.ts+++ b/packages/eve/src/harness/hitl/approvals.ts@@ -1,11 +1,8 @@import type { ModelMessage } from "ai";import type { getApprovalAuditState } from "#harness/hitl/candidates.js";-import {- supersededChallenges,- withSignIns,- type AuthorizationChallenge,-} from "#harness/authorization.js";+import type { AuthorizationChallenge } from "#harness/authorization.js";+import { supersededChallenges, withSignIns } from "./sign-ins.js";import { authorizationEventFields } from "#harness/authorization-event-fields.js";import { renderPendingApprovalsSnippet } from "#harness/hitl/approval-prompt.js";import { isApprovalRequest } from "#harness/input-request-class.js";diff --git a/packages/eve/src/harness/hitl/candidates.test.ts b/packages/eve/src/harness/hitl/candidates.test.tsindex c33def30e..1930aca5b 100644--- a/packages/eve/src/harness/hitl/candidates.test.ts+++ b/packages/eve/src/harness/hitl/candidates.test.ts@@ -286,11 +286,13 @@ describe("approval candidate state", () => {create({ candidateId: "candidate-1", principalId: "U1" }).state,).activeCandidates[0]!;const state: SessionStateMap = {- "eve.runtime.hitl.approvalState": {- activeCandidates: { "candidate-1": persisted },- candidateHistory: [],- nextCandidateSequence: 1,- settlements: {},+ "eve.runtime.hitl.requests": {+ approvals: {+ activeCandidates: { "candidate-1": persisted },+ candidateHistory: [],+ nextCandidateSequence: 1,+ settlements: {},+ },},};diff --git a/packages/eve/src/harness/hitl/candidates.ts b/packages/eve/src/harness/hitl/candidates.tsindex 35efe8105..37c275db1 100644--- a/packages/eve/src/harness/hitl/candidates.ts+++ b/packages/eve/src/harness/hitl/candidates.ts@@ -2,7 +2,7 @@ import type { SessionAuthContext } from "#channel/types.js";import type { AuthorizationChallenge } from "#harness/authorization.js";import type { SessionStateMap } from "#harness/types.js";-const APPROVAL_STATE_KEY = "eve.runtime.hitl.approvalState";+import { readApprovalState, writeApprovalState } from "./requests.js";type ApprovalCandidateStatus =| "pending"@@ -55,7 +55,7 @@ export interface ActiveApprovalCandidate {readonly authorizationChallenges?: readonly AuthorizationChallenge[];}-interface DurableApprovalState {+export interface DurableApprovalState {readonly activeCandidates: Readonly<Record<string, ActiveApprovalCandidate>>;readonly nextCandidateSequence: number;readonly candidateHistory: readonly ApprovalCandidateAuditRecord[];@@ -382,66 +382,6 @@ export function sameResponder();}-/**- * A candidate is an Approve unless it records Cancel: candidates persisted- * before Cancel was authorized carry no decision, and their responder pressed- * Approve.- */-function readActiveCandidates(- candidates: Readonly<Record<string, ActiveApprovalCandidate>>,-): Readonly<Record<string, ActiveApprovalCandidate>> {- return Object.fromEntries(- Object.entries(candidates).map(([candidateId, candidate]) => [- candidateId,- { ...candidate, decision: candidate.decision === "cancel" ? "cancel" : "approve" },- ]),- );-}--function readApprovalState(state: SessionStateMap | undefined): DurableApprovalState {- const value = state?.[APPROVAL_STATE_KEY];- if (typeof value !== "object" || value === null) {- return {- activeCandidates: {},- candidateHistory: [],- nextCandidateSequence: 0,- settlements: {},- };- }- const candidate = value as Partial<DurableApprovalState>;- return {- activeCandidates:- typeof candidate.activeCandidates === "object" && candidate.activeCandidates !== null- ? readActiveCandidates(candidate.activeCandidates)- : {},- candidateHistory: Array.isArray(candidate.candidateHistory) ? candidate.candidateHistory : [],- nextCandidateSequence:- typeof candidate.nextCandidateSequence === "number" &&- Number.isSafeInteger(candidate.nextCandidateSequence) &&- candidate.nextCandidateSequence >= 0- ? candidate.nextCandidateSequence- : deriveNextCandidateSequence(candidate),- settlements:- typeof candidate.settlements === "object" && candidate.settlements !== null- ? candidate.settlements- : {},- };-}--function deriveNextCandidateSequence(state: Partial<DurableApprovalState>): number {- return (- Object.keys(state.activeCandidates ?? {}).length +- (Array.isArray(state.candidateHistory) ? state.candidateHistory.length : 0)- );-}--function writeApprovalState(- state: SessionStateMap | undefined,- approvalState: DurableApprovalState,-): SessionStateMap {- return { ...state, [APPROVAL_STATE_KEY]: approvalState };-}-/*** The held turn moved on, steered or cancelled: the responders still checking one of its* approvals stop, their candidates stale.diff --git a/packages/eve/src/harness/hitl/coordinator.test.ts b/packages/eve/src/harness/hitl/coordinator.test.tsindex 5a1464b7d..a4ccec026 100644--- a/packages/eve/src/harness/hitl/coordinator.test.ts+++ b/packages/eve/src/harness/hitl/coordinator.test.ts@@ -1,3 +1,4 @@+import { readHitlState, writeHitlState } from "./requests.js";import { describe, expect, it, vi } from "vitest";import { jsonSchema } from "ai";import type { ApprovalResponsePolicy } from "#approval/definition.js";@@ -216,6 +217,34 @@ describe("coordinateApprovalDelivery", () => {);});+ it("withdraws only the expired candidate's sign-ins through a transition", async () => {+ const ingested = await ingest();+ const candidate = getApprovalAuditState(ingested.session.state).activeCandidates[0]!;+ const expired = {+ name: "expired",+ hookUrl: "https://example.com/expired",+ challenge: { url: "https://example.com/login" },+ };+ const retained = {+ name: "retained",+ hookUrl: "https://example.com/retained",+ challenge: { url: "https://example.com/login" },+ };+ const session = writeHitlState(+ {+ ...ingested.session,+ state: markApprovalCandidateAuthorizationRequired({+ candidateId: candidate.candidateId,+ state: ingested.session.state,+ authorizationChallenges: [expired],+ }),+ },+ { signIns: [expired, retained] },+ );+ const result = await coordinateApprovalDelivery({ now: 600_100, session, tools: new Map() });+ expect(readHitlState(result.session.state).signIns).toEqual([retained]);+ });+it("completes a failed authorizer timeout", async () => {vi.useFakeTimers();try {diff --git a/packages/eve/src/harness/hitl/coordinator.ts b/packages/eve/src/harness/hitl/coordinator.tsindex 84347f083..68dfb7469 100644--- a/packages/eve/src/harness/hitl/coordinator.ts+++ b/packages/eve/src/harness/hitl/coordinator.ts@@ -1,3 +1,4 @@+import { readHitlState } from "./requests.js";import type { SessionAuthContext } from "#channel/types.js";import { buildCallbackContext } from "#context/build-callback-context.js";import { contextStorage } from "#context/container.js";@@ -21,10 +22,12 @@ import {type ApprovalCandidateDecision,type ApprovalSettlementAuditRecord,} from "#harness/hitl/candidates.js";+import { saveTransition, sessionView } from "#harness/session-machine/commit.js";+import { matchSignIns } from "#harness/session-machine/transitions.js";+import { storedProjection } from "#harness/session-machine/view.js";+import { signInAttemptKey } from "./sign-ins.js";import {- clearPendingAuthorization,getAuthorizationResult,- getPendingAuthorization,isAuthorizationSignal,type AuthorizationChallenge,} from "#harness/authorization.js";@@ -87,17 +90,17 @@ export async function coordinateApprovalDelivery(input: {const expiredCandidates = getApprovalAuditState(input.session.state).activeCandidates.filter((candidate) => candidate.expiresAt <= now,);- const expiredChallengeIds = expiredCandidates.flatMap(- (candidate) =>- candidate.authorizationChallenges?.map(- (challenge) => challenge.attemptId ?? challenge.candidateId ?? challenge.name,- ) ?? [],+ const expiredChallengeIds = new Set(+ expiredCandidates.flatMap(+ (candidate) => candidate.authorizationChallenges?.map(signInAttemptKey) ?? [],+ ),);const expiredState = expireApprovalCandidates({ now, state: input.session.state });- let session: HarnessSession = {- ...input.session,- state: clearPendingAuthorization(expiredState, expiredChallengeIds),- };+ let session: HarnessSession = { ...input.session, state: expiredState };+ if (expiredChallengeIds.size > 0) {+ const view = sessionView(storedProjection(session.state), session.state);+ session = saveTransition(session, matchSignIns(view, { attemptIds: [...expiredChallengeIds] }));+ }const audit = getApprovalAuditState(session.state);const batches = suspendedSteps(session.state).filter((step) => step.requests.length > 0);const pendingRequestIds = new Set(@@ -231,7 +234,7 @@ export async function coordinateApprovalDelivery(input: {// Candidates are persisted in an earlier pass. Run pending candidates and// resume only authorization-required candidates whose callback arrived.const parkedChallengeNames = new Set(- getPendingAuthorization(session.state)?.challenges.map((challenge) => challenge.name) ?? [],+ readHitlState(session.state).signIns.map((challenge) => challenge.name),);for (const candidate of candidatesAtStart) {if (candidate.status === "authorization-required") {diff --git a/packages/eve/src/harness/hitl/index.ts b/packages/eve/src/harness/hitl/index.tsindex 9dfa2165e..719b348f8 100644--- a/packages/eve/src/harness/hitl/index.ts+++ b/packages/eve/src/harness/hitl/index.ts@@ -2,7 +2,6 @@ import type { ModelMessage } from "ai";import type { SessionAuthContext } from "#channel/types.js";import { AuthKey, SessionKey } from "#context/keys.js";-import { clearPendingAuthorization } from "#harness/authorization.js";import type { resolveInlineAuthorizationInterrupt } from "#harness/inline-tool-authorization.js";import { validateHarnessModelMessages } from "#harness/messages.js";import { fail, hold } from "#harness/session-machine/transitions.js";@@ -34,7 +33,7 @@ import { holdForInput } from "./intake.js";// meets it: a delivery's answers and sign-in callbacks before its turn runs (`acceptHumanInput`),// the work they approved once its model step starts (`runApprovedLocalCalls`), a model step's gated calls and// sign-ins, the budget gate before each model call, and what the model reads about pending-// approvals. Nothing outside this directory reads its records.+// approvals. Outside readers use only the read-only requests view exported here.export {acceptHumanInput,@@ -47,6 +46,7 @@ export {} from "./intake.js";export { extractToolApprovalInputRequests } from "#harness/input-extraction.js";export { hasRunnableQueue } from "./approvals.js";+export { discardClearedHitlState as discardClearedHumanInput } from "./requests.js";/*** A model step made calls that need a person's approval: the step parks on them beside any@@ -159,18 +159,6 @@ export function humanInputContext(};}-const APPROVAL_STATE_KEY = "eve.runtime.hitl.approvalState";--/**- * Drops what a cleared context owned: sign-in attempts and responders' approval progress. `clear`- * reported each close; relay routes for live tasks stay.- */-export function discardClearedHumanInput<T extends HarnessSessionBase>(session: T): T {- const { [APPROVAL_STATE_KEY]: _approvals, ...state } =- clearPendingAuthorization(session.state) ?? {};- return { ...session, state: Object.keys(state).length > 0 ? state : undefined };-}-/*** The approvals whose tool defines a response policy. Every park records them, so no Approve or* Cancel of such an approval skips the policy.@@ -217,3 +205,5 @@ export function takeDeferredMessage<T extends HarnessSessionBase>(session: writeTurnState(session, isEmptyInput(rest) ? turn : { ...turn, queued: rest }),};}++export { readHitlState, holdsHitlRequests } from "./requests.js";diff --git a/packages/eve/src/harness/proxy-input-requests.test.ts b/packages/eve/src/harness/hitl/relays.test.tssimilarity index 65%rename from packages/eve/src/harness/proxy-input-requests.test.tsrename to packages/eve/src/harness/hitl/relays.test.tsindex 6b0dde252..19a724355 100644--- a/packages/eve/src/harness/proxy-input-requests.test.ts+++ b/packages/eve/src/harness/hitl/relays.test.ts@@ -1,13 +1,11 @@import { describe, expect, it } from "vitest";+import { withRelays } from "#internal/testing/session-machine.js";-import {- getProxyInputRequests,- hasProxyInputRequests,- toProxyInputRequestEntries,- upsertProxyInputRequests,-} from "#harness/proxy-input-requests.js";+import { readHitlState } from "./requests.js";++import { parseProxyInputRequest, toProxyInputRequestEntries } from "./relays.js";import type { SubagentInputRequestHookPayload } from "#channel/types.js";-import type { InputRequest, InputRequestKind } from "#shared/input.js";+import { inputOptionSchema, type InputRequest, type InputRequestKind } from "#shared/input.js";import type { HarnessSession } from "#harness/types.js";const REQUEST_EVENT = { sequence: 0, stepIndex: 0, turnId: "turn_0" };@@ -39,16 +37,15 @@ function createRequest(requestId: string, kind: InputRequestKind): InputRequestdescribe("upsertProxyInputRequests", () => {it("records a fresh batch of proxy entries", () => {const session = createSession();- const next = upsertProxyInputRequests({+ const next = withRelays(session, {entries: [["req-1", { childContinuationToken: "child-a", event: REQUEST_EVENT, kind: "question" }],],forChildContinuationToken: "child-a",- session,});- expect(hasProxyInputRequests(next.state)).toBe(true);- expect(getProxyInputRequests(next.state).get("req-1")).toEqual({+ expect(readHitlState(next.state).relays.size > 0).toBe(true);+ expect(readHitlState(next.state).relays.get("req-1")).toEqual({childContinuationToken: "child-a",event: REQUEST_EVENT,kind: "question",@@ -56,23 +53,21 @@ describe("upsertProxyInputRequests", () => {});it("replaces prior entries for the same child continuation token", () => {- let session = upsertProxyInputRequests({+ let session = withRelays(createSession(), {entries: [["req-1", { childContinuationToken: "child-a", event: REQUEST_EVENT, kind: "question" }],],forChildContinuationToken: "child-a",- session: createSession(),});- session = upsertProxyInputRequests({+ session = withRelays(session, {entries: [["req-2", { childContinuationToken: "child-a", event: REQUEST_EVENT, kind: "question" }],],forChildContinuationToken: "child-a",- session,});- const entries = getProxyInputRequests(session.state);+ const entries = readHitlState(session.state).relays;expect(entries.size).toBe(1);expect(entries.get("req-1")).toBeUndefined();expect(entries.get("req-2")).toEqual({@@ -83,7 +78,7 @@ describe("upsertProxyInputRequests", () => {});it("keeps independent questions at the same answer destination", () => {- let session = upsertProxyInputRequests({+ let session = withRelays(createSession(), {entries: [["alice",@@ -97,9 +92,8 @@ describe("upsertProxyInputRequests", () => {],forChildContinuationToken: "shared-inbox",inputSource: "workflow-alice",- session: createSession(),});- session = upsertProxyInputRequests({+ session = withRelays(session, {entries: [["bob",@@ -113,10 +107,9 @@ describe("upsertProxyInputRequests", () => {],forChildContinuationToken: "shared-inbox",inputSource: "workflow-bob",- session,});- expect([...getProxyInputRequests(session.state).keys()]).toEqual(["alice", "bob"]);+ expect([...readHitlState(session.state).relays.keys()]).toEqual(["alice", "bob"]);});it("preserves remote response coordinates through a durable proxy snapshot", () => {@@ -135,13 +128,12 @@ describe("upsertProxyInputRequests", () => {remote,subagentName: "research",};- const session = upsertProxyInputRequests({+ const session = withRelays(createSession(), {entries: toProxyInputRequestEntries(payload),forChildContinuationToken: payload.childContinuationToken,- session: createSession(),});expect(- getProxyInputRequests(JSON.parse(JSON.stringify(session.state))).get("req-remote"),+ readHitlState(JSON.parse(JSON.stringify(session.state))).relays.get("req-remote"),).toMatchObject({remote,childContinuationToken: "remote-reply",@@ -149,16 +141,15 @@ describe("upsertProxyInputRequests", () => {});it("drops a prior child's batch when its request ID is claimed by another child", () => {- let session = upsertProxyInputRequests({+ let session = withRelays(createSession(), {entries: [["req-1", { childContinuationToken: "child-a", event: REQUEST_EVENT, kind: "question" }],["req-2", { childContinuationToken: "child-a", event: REQUEST_EVENT, kind: "question" }],],forChildContinuationToken: "child-a",- session: createSession(),});- session = upsertProxyInputRequests({+ session = withRelays(session, {entries: [["req-1",@@ -166,25 +157,23 @@ describe("upsertProxyInputRequests", () => {],],forChildContinuationToken: "child-b",- session,});- expect(Object.fromEntries(getProxyInputRequests(session.state))).toEqual({+ expect(Object.fromEntries(readHitlState(session.state).relays)).toEqual({"req-1": { childContinuationToken: "child-b", event: REQUEST_EVENT, kind: "tool-approval" },"req-2": { childContinuationToken: "child-a", event: REQUEST_EVENT, kind: "question" },});});it("keeps entries from other children when upserting", () => {- let session = upsertProxyInputRequests({+ let session = withRelays(createSession(), {entries: [["req-a", { childContinuationToken: "child-a", event: REQUEST_EVENT, kind: "question" }],],forChildContinuationToken: "child-a",- session: createSession(),});- session = upsertProxyInputRequests({+ session = withRelays(session, {entries: [["req-b",@@ -192,10 +181,9 @@ describe("upsertProxyInputRequests", () => {],],forChildContinuationToken: "child-b",- session,});- const entries = getProxyInputRequests(session.state);+ const entries = readHitlState(session.state).relays;expect(entries.size).toBe(2);expect(entries.get("req-a")).toEqual({childContinuationToken: "child-a",@@ -227,13 +215,12 @@ describe("toProxyInputRequestEntries", () => {kind: "subagent-input-request",subagentName: "delegate",});- const session = upsertProxyInputRequests({- entries,+ const session = withRelays(createSession(), {+ entries: entries,forChildContinuationToken: "reusable-alias",- session: createSession(),});- expect(getProxyInputRequests(JSON.parse(JSON.stringify(session.state))).get("req-1")).toEqual(+ expect(readHitlState(JSON.parse(JSON.stringify(session.state))).relays.get("req-1")).toEqual(expect.objectContaining({ childSessionInbox }),);});@@ -285,20 +272,22 @@ describe("toProxyInputRequestEntries", () => {describe("getProxyInputRequests type safety", () => {it("returns an empty map when the session carries no proxy state", () => {- const entries = getProxyInputRequests(createSession().state);+ const entries = readHitlState(createSession().state).relays;expect(entries.size).toBe(0);});it("ignores malformed values in the state map", () => {const session = createSession({- "eve.runtime.proxyInputRequests": {- "req-1": 42,- "req-2": { childContinuationToken: 42, event: REQUEST_EVENT, kind: "question" },- "req-3": { childContinuationToken: "child-c", kind: "other" },- "req-4": { childContinuationToken: "child-d", event: REQUEST_EVENT, kind: "question" },+ "eve.runtime.hitl.requests": {+ relays: {+ "req-1": 42,+ "req-2": { childContinuationToken: 42, event: REQUEST_EVENT, kind: "question" },+ "req-3": { childContinuationToken: "child-c", kind: "other" },+ "req-4": { childContinuationToken: "child-d", event: REQUEST_EVENT, kind: "question" },+ },},});- const entries = getProxyInputRequests(session.state);+ const entries = readHitlState(session.state).relays;expect(entries.size).toBe(1);expect(entries.get("req-4")).toEqual({childContinuationToken: "child-d",@@ -309,25 +298,27 @@ describe("getProxyInputRequests type safety", () => {it("ignores a legacy array-shaped value", () => {const session = createSession({- "eve.runtime.proxyInputRequests": [{ requestId: "req-1" }],+ "eve.runtime.hitl.requests": { relays: [{ requestId: "req-1" }] },});- expect(getProxyInputRequests(session.state).size).toBe(0);+ expect(readHitlState(session.state).relays.size).toBe(0);});it("keeps legacy routes and ignores malformed optional batch metadata", () => {const session = createSession({- "eve.runtime.proxyInputRequests": {- legacy: { childContinuationToken: "child-a", event: REQUEST_EVENT, kind: "question" },- malformed: {- batch: { approvalRequestIds: ["other"], requestIds: ["malformed"] },- childContinuationToken: "child-a",- event: REQUEST_EVENT,- kind: "tool-approval",+ "eve.runtime.hitl.requests": {+ relays: {+ legacy: { childContinuationToken: "child-a", event: REQUEST_EVENT, kind: "question" },+ malformed: {+ batch: { approvalRequestIds: ["other"], requestIds: ["malformed"] },+ childContinuationToken: "child-a",+ event: REQUEST_EVENT,+ kind: "tool-approval",+ },},},});- expect([...getProxyInputRequests(session.state)]).toEqual([+ expect([...readHitlState(session.state).relays]).toEqual([["legacy", { childContinuationToken: "child-a", event: REQUEST_EVENT, kind: "question" }],["malformed",@@ -336,3 +327,69 @@ describe("getProxyInputRequests type safety", () => {]);});});++describe("parseProxyInputRequest", () => {+ it("keeps reply options shaped like input options and drops a route with any other", () => {+ const parse = (options: unknown) =>+ parseProxyInputRequest(+ {+ childContinuationToken: "child",+ event: REQUEST_EVENT,+ kind: "question",+ reply: { options },+ },+ "req-1",+ );+ const options = [+ { id: "a", label: "A" },+ { description: "Ship it.", id: "b", label: "B", style: "danger" },+ ];+ expect(parse(options)?.reply?.options).toEqual(options);+ for (const malformed of [+ [{ id: "a" }],+ [{ id: "a", label: "A", style: "loud" }],+ [{ id: "a", label: "A", value: 1 }],+ { id: "a", label: "A" },+ Array(1),+ ]) {+ expect(parse(malformed)).toBeUndefined();+ }+ });++ it("accepts exactly the reply options inputOptionSchema accepts", () => {+ const parse = (options: unknown) =>+ parseProxyInputRequest(+ {+ childContinuationToken: "child",+ event: REQUEST_EVENT,+ kind: "question",+ reply: { options },+ },+ "req-1",+ );+ const option = { id: "a", label: "A" };+ for (const options of [+ [],+ [option],+ [{ ...option, description: "d", style: "primary" }],+ [{ ...option, description: undefined, style: undefined }],+ [{ ...option, description: 1 }],+ [{ ...option, style: "loud" }],+ [{ ...option, value: 1 }],+ [{ id: "a" }],+ [{ label: "A" }],+ [null],+ ["a"],+ [[option]],+ [option, undefined],+ Array(1),+ option,+ "a",+ null,+ ]) {+ expect(parse(options) !== undefined, JSON.stringify(options)).toBe(+ inputOptionSchema.array().safeParse(options).success,+ );+ }+ });+});diff --git a/packages/eve/src/harness/proxy-input-requests.ts b/packages/eve/src/harness/hitl/relays.tssimilarity index 68%rename from packages/eve/src/harness/proxy-input-requests.tsrename to packages/eve/src/harness/hitl/relays.tsindex 8ac0e077d..34bea59d1 100644--- a/packages/eve/src/harness/proxy-input-requests.ts+++ b/packages/eve/src/harness/hitl/relays.ts@@ -1,16 +1,13 @@import type { SubagentInputRequestHookPayload } from "#channel/types.js";import type { InputResolvedStreamEvent } from "#protocol/message.js";import type { StepCoordinates as PendingInputBatchEvent } from "#harness/session-machine/view.js";-import type { HarnessSessionBase, SessionStateMap } from "#harness/types.js";-import { inputOptionSchema, type InputOption, type InputRequestKind } from "#shared/input.js";+import type { InputOption, InputRequestKind } from "#shared/input.js";import {isSessionInboxAddress,type SessionInboxAddress,} from "#execution/session-inbox/address.js";import type { RemoteAgentBinding } from "#eve-channel/support.js";-const PROXY_INPUT_REQUESTS_KEY = "eve.runtime.proxyInputRequests";-const PROXY_INPUT_REQUEST_KINDS = {question: true,"session-limit": true,@@ -83,114 +80,6 @@ export function resolvedForParent(return resolutions.length === 0 ? undefined : { ...data, resolutions };}-/** `requestId → route` map stored on the parent session. */-type ProxyInputRequestMap = Readonly<Record<string, ProxyInputRequest>>;--/**- * Returns the proxy-routing map as a fresh `Map`. Never returns a live- * reference so accidental mutation cannot corrupt session state.- */-export function getProxyInputRequests(- state: SessionStateMap | undefined,-): ReadonlyMap<string, ProxyInputRequest> {- return new Map(Object.entries(readMap(state)));-}--/**- * Returns true when the session is currently proxying one or more- * HITL requests on behalf of a descendant subagent.- */-export function hasProxyInputRequests(state: SessionStateMap | undefined): boolean {- for (const _ of Object.keys(readMap(state))) {- return true;- }- return false;-}--/**- * Replaces prior entries for the destination and input source with the provided- * ones. A child raising a fresh batch overwrites its prior batch so the- * parent never keeps stale request metadata. Other sources' routes stay- * independently answerable.- */-export function upsertProxyInputRequests<S extends HarnessSessionBase>(input: {- readonly inputSource?: string;- readonly entries: readonly (readonly [requestId: string, route: ProxyInputRequest])[];- readonly forChildContinuationToken: string;- readonly session: S;-}): S {- return {- ...input.session,- state: upsertProxyInputRequestState({- entries: input.entries,- forChildContinuationToken: input.forChildContinuationToken,- inputSource: input.inputSource,- state: input.session.state,- }),- };-}--/** State-only variant for control-plane steps that already hold a durable projection. */-export function upsertProxyInputRequestState(input: {- readonly inputSource?: string;- readonly entries: readonly (readonly [requestId: string, route: ProxyInputRequest])[];- readonly forChildContinuationToken: string;- readonly state: SessionStateMap | undefined;-}): SessionStateMap | undefined {- const next: Record<string, ProxyInputRequest> = {};-- for (const [requestId, route] of Object.entries(readMap(input.state))) {- if (- route.childContinuationToken !== input.forChildContinuationToken ||- route.inputSource !== input.inputSource- ) {- next[requestId] = route;- }- }-- for (const [requestId, route] of input.entries) {- next[requestId] = route;- }-- const state = { ...input.state };- if (Object.keys(next).length === 0) {- delete state[PROXY_INPUT_REQUESTS_KEY];- } else {- state[PROXY_INPUT_REQUESTS_KEY] = next;- }- return Object.keys(state).length > 0 ? state : undefined;-}--/** Removes every proxy route the predicate selects. */-export function clearProxyInputRequestsWhere<T extends { readonly state?: SessionStateMap }>(- session: T,- select: (route: ProxyInputRequest, requestId: string) => boolean,-): T {- const requestIds = Object.entries(readMap(session.state))- .filter(([requestId, route]) => select(route, requestId))- .map(([requestId]) => requestId);- return retireProxyInputRequests(session, requestIds);-}--/** Removes only the request IDs whose responses were successfully forwarded. */-export function retireProxyInputRequests<T extends { readonly state?: SessionStateMap }>(- session: T,- requestIds: readonly string[],-): T {- const current = readMap(session.state);- const next = { ...current };- let changed = false;-- for (const requestId of requestIds) {- if (Object.hasOwn(next, requestId)) {- delete next[requestId];- changed = true;- }- }-- return changed ? writeMap(session, next) : session;-}-/*** Projects a {@link SubagentInputRequestHookPayload} into the* `(requestId, route)` tuples the session stores.@@ -238,42 +127,11 @@ export function toProxyInputRequestEntries(});}-function readMap(state: SessionStateMap | undefined): ProxyInputRequestMap {- const raw = state?.[PROXY_INPUT_REQUESTS_KEY];-- if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {- return {};- }-- const result: Record<string, ProxyInputRequest> = {};- for (const [key, value] of Object.entries(raw)) {- const request = parseProxyInputRequest(value, key);- if (request !== undefined) {- result[key] = request;- }- }- return result;-}--function writeMap<T extends { readonly state?: SessionStateMap }>(- session: T,- entries: Record<string, ProxyInputRequest>,-): T {- const state = { ...session.state };-- if (Object.keys(entries).length === 0) {- delete state[PROXY_INPUT_REQUESTS_KEY];- return {- ...session,- state: Object.keys(state).length > 0 ? state : undefined,- };- }-- state[PROXY_INPUT_REQUESTS_KEY] = entries;- return { ...session, state };-}--function parseProxyInputRequest(value: unknown, requestId: string): ProxyInputRequest | undefined {+/** Reads one stored route, or `undefined` when it is malformed. */+export function parseProxyInputRequest(+ value: unknown,+ requestId: string,+): ProxyInputRequest | undefined {if (value === null || typeof value !== "object" || Array.isArray(value)) {return undefined;}@@ -385,9 +243,9 @@ function parseProxyInputReply(value: unknown): ProxyInputReply | undefined {}const options = Reflect.get(value, "options");if (options !== undefined) {- const parsed = inputOptionSchema.array().safeParse(options);- if (!parsed.success) return undefined;- reply.options = parsed.data;+ // `Array.from` turns holes into `undefined`, which `every` alone would skip.+ if (!Array.isArray(options) || !Array.from(options).every(isInputOption)) return undefined;+ reply.options = options;}return reply;}@@ -407,6 +265,24 @@ function parseProxyInputRequestBatch(value: unknown): ProxyInputRequestBatch | ureturn { approvalRequestIds: value.approvalRequestIds, requestIds: value.requestIds };}+// `inputOptionSchema`, checked by hand: the requests module imports this one, and the+// workflow bundle reads session state without pulling in zod.+const INPUT_OPTION_FIELDS: Readonly<Record<string, (value: unknown) => boolean>> = {+ description: (value) => value === undefined || typeof value === "string",+ id: (value) => typeof value === "string",+ label: (value) => typeof value === "string",+ style: (value) =>+ value === undefined || value === "primary" || value === "danger" || value === "default",+};++function isInputOption(value: unknown): value is InputOption {+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;+ return (+ Object.keys(value).every((key) => Object.hasOwn(INPUT_OPTION_FIELDS, key)) &&+ Object.entries(INPUT_OPTION_FIELDS).every(([key, valid]) => valid(Reflect.get(value, key)))+ );+}+function isStringArray(value: unknown): value is string[] {return Array.isArray(value) && value.every((entry) => typeof entry === "string");}diff --git a/packages/eve/src/harness/hitl/requests.test.ts b/packages/eve/src/harness/hitl/requests.test.tsnew file mode 100644index 000000000..b3d76d67f--- /dev/null+++ b/packages/eve/src/harness/hitl/requests.test.ts@@ -0,0 +1,145 @@+import { describe, expect, it } from "vitest";++import type { AuthorizationChallenge } from "#harness/authorization.js";+import type { SessionStateMap } from "#harness/types.js";+import {+ discardClearedHitlState,+ holdsHitlRequests,+ readHitlState,+ writeHitlState,+} from "./requests.js";+import { type ProxyInputRequest } from "./relays.js";++const EVENT = { sequence: 1, stepIndex: 0, turnId: "turn_1" };++function signIn(name: string, attemptId: string): AuthorizationChallenge {+ return {+ attemptId,+ challenge: { instructions: `Sign in to ${name}.` },+ hookUrl: `https://example.com/${attemptId}`,+ name,+ principal: { id: "alice", type: "user" },+ };+}++function route(token: string, inputSource?: string): ProxyInputRequest {+ return {+ childContinuationToken: token,+ event: EVENT,+ ...(inputSource !== undefined && { inputSource }),+ kind: "question",+ reply: { allowFreeform: true },+ };+}++function save(state: SessionStateMap | undefined, change: Parameters<typeof writeHitlState>[1]) {+ return writeHitlState({ state }, change).state;+}++describe("writeHitlState", () => {+ it("writes the sign-ins and the relay routes a transition changes", () => {+ const state = save(undefined, {+ relays: {+ upsert: { entries: [["q-1", route("child")]], forChildContinuationToken: "child" },+ },+ signIns: [signIn("github", "a-1")],+ });+ expect(Object.keys(state ?? {})).toEqual(["eve.runtime.hitl.requests"]);+ const hitl = readHitlState(state);+ expect(hitl.signIns.map((challenge) => challenge.attemptId)).toEqual(["a-1"]);+ expect([...hitl.relays.keys()]).toEqual(["q-1"]);+ });++ it("leaves records the change doesn't name", () => {+ const before = save(undefined, {+ relays: {+ upsert: { entries: [["q-1", route("child")]], forChildContinuationToken: "child" },+ },+ signIns: [signIn("github", "a-1")],+ });+ const after = readHitlState(save(before, { relays: { retire: ["q-unknown"] } }));+ expect(after.signIns).toHaveLength(1);+ expect(after.relays.size).toBe(1);+ });++ it("withdraws every sign-in on an empty list, and retires the routes it names", () => {+ const before = save(undefined, {+ relays: {+ upsert: {+ entries: [+ ["q-1", route("child")],+ ["q-2", route("child")],+ ],+ forChildContinuationToken: "child",+ },+ },+ signIns: [signIn("github", "a-1")],+ });+ const after = save(before, { relays: { retire: ["q-1"] }, signIns: [] });+ expect(readHitlState(after).signIns).toEqual([]);+ expect([...readHitlState(after).relays.keys()]).toEqual(["q-2"]);+ });++ it("replaces only the routes of the batch's own input source", () => {+ const first = save(undefined, {+ relays: {+ upsert: {+ entries: [["q-a", route("child", "a")]],+ forChildContinuationToken: "child",+ inputSource: "a",+ },+ },+ });+ const second = save(first, {+ relays: {+ upsert: {+ entries: [["q-b", route("child", "b")]],+ forChildContinuationToken: "child",+ inputSource: "b",+ },+ },+ });+ expect([...readHitlState(second).relays.keys()].sort()).toEqual(["q-a", "q-b"]);+ });+});++describe("holdsHitlRequests", () => {+ it("is false for a session with no sign-in or relay records", () => {+ expect(holdsHitlRequests(undefined)).toBe(false);+ expect(holdsHitlRequests({ "eve.unrelated": true })).toBe(false);+ expect(holdsHitlRequests({ "eve.runtime.hitl.requests": { approvals: {} } })).toBe(false);+ });++ it("is true for a requests record it can't read", () => {+ expect(holdsHitlRequests({ "eve.runtime.hitl.requests": [] })).toBe(true);+ expect(holdsHitlRequests({ "eve.runtime.hitl.requests": { relays: 42 } })).toBe(true);+ });++ it("is true for a pending sign-in or relayed request", () => {+ expect(holdsHitlRequests(save(undefined, { signIns: [signIn("github", "a-1")] }))).toBe(true);+ const relayed = save(undefined, {+ relays: {+ upsert: { entries: [["q-1", route("child")]], forChildContinuationToken: "child" },+ },+ });+ expect(holdsHitlRequests(relayed)).toBe(true);+ });+});++describe("discardClearedHitlState", () => {+ it("drops approvals and sign-ins and keeps relayed requests", () => {+ const state = save(+ { "eve.runtime.hitl.requests": { approvals: { activeCandidates: {} } } },+ {+ relays: {+ upsert: { entries: [["q-1", route("child")]], forChildContinuationToken: "child" },+ },+ signIns: [signIn("github", "a-1")],+ },+ );+ const cleared = discardClearedHitlState({ state } as Parameters<+ typeof discardClearedHitlState+ >[0]).state;+ expect(cleared).toEqual({ "eve.runtime.hitl.requests": { relays: { "q-1": route("child") } } });+ });+});diff --git a/packages/eve/src/harness/hitl/requests.ts b/packages/eve/src/harness/hitl/requests.tsnew file mode 100644index 000000000..9661d733b--- /dev/null+++ b/packages/eve/src/harness/hitl/requests.ts@@ -0,0 +1,301 @@+import type { AuthorizationChallenge } from "#harness/authorization.js";+import { resolveActiveAuthorizationChallenges } from "./sign-ins.js";+import type { HarnessSessionBase, SessionStateMap } from "#harness/types.js";+import { isObject } from "#shared/guards.js";++import type { ActiveApprovalCandidate, DurableApprovalState } from "./candidates.js";+import { parseProxyInputRequest, type ProxyInputRequest } from "./relays.js";++// Storage stays in hitl/ to keep the rule 50 import seam around the request codecs.+// Sign-ins and relays use machine transitions; approval writes through candidates.ts remain+// direct, and checkpoint upgrades migrate legacy storage outside the machine.+// The module that owns the human-in-the-loop storage key: the requests the+// session holds, i.e. responders' approval candidates, the sign-ins it waits on, and the requests+// it relays for a workflow run or a child session. Nothing else names their session-state key;+// `candidates.ts` and `relays.ts` model the records it stores.++/** The session-state key of the human-in-the-loop requests. */+const REQUESTS_KEY = "eve.runtime.hitl.requests";++/** Where builds before checkpoint version 15 kept the requests. Only checkpoint upgrades read them. */+export const LEGACY_HITL_STATE_KEYS = {+ approvals: "eve.runtime.hitl.approvalState",+ signIns: "eve.runtime.pendingAuthorization",+ relays: "eve.runtime.proxyInputRequests",+} as const;++/**+ * A read-only snapshot of the human-in-the-loop records, the one way code outside `harness/hitl/`+ * reads them.+ */+export interface HitlState {+ /** The sign-in attempts the session waits on. */+ readonly signIns: readonly AuthorizationChallenge[];+ /** Requests this session relays for a child session or a workflow run, by `requestId`. */+ readonly relays: ReadonlyMap<string, ProxyInputRequest>;+}++/** Each record is parsed on first read: most readers want one. */+export function readHitlState(state: SessionStateMap | undefined): HitlState {+ let signIns: readonly AuthorizationChallenge[] | undefined;+ let relays: ReadonlyMap<string, ProxyInputRequest> | undefined;+ return {+ get signIns() {+ return (signIns ??= readSignIns(state));+ },+ get relays() {+ return (relays ??= new Map(Object.entries(readRelays(state))));+ },+ };+}++/**+ * Whether the session holds a sign-in or relayed request, or a record of them it can't read.+ * Settling the last one deletes its record; a malformed record that ordinary readers read as+ * empty must not let a session hand off.+ */+export function holdsHitlRequests(state: SessionStateMap | undefined): boolean {+ const requests = state?.[REQUESTS_KEY];+ if (requests === undefined) return false;+ if (!isObject(requests) || Array.isArray(requests)) return true;+ const { signIns, relays } = requests as StoredRequests;+ if (signIns !== undefined) return true;+ return relays !== undefined && (!isObject(relays) || Object.keys(relays).length > 0);+}++/** What a session-machine transition changes in these records. */+export interface HitlStateChange {+ /** Every sign-in the session waits on once the change applies; `[]` withdraws them all. */+ readonly signIns?: readonly AuthorizationChallenge[];+ readonly relays?: RelayChange;+}++/** Relay routes a transition records or retires. */+export interface RelayChange {+ /** A child's fresh batch: it replaces the routes that child's input source held. */+ readonly upsert?: {+ readonly entries: readonly (readonly [requestId: string, route: ProxyInputRequest])[];+ readonly forChildContinuationToken: string;+ readonly inputSource?: string;+ };+ /** Routes whose answers went down to the asker, or whose request closed. */+ readonly retire?: readonly string[];+}++/** Writes a transition's change. Production callers are the machine save and its closed-route cleanup. */+export function writeHitlState<T extends { readonly state?: SessionStateMap }>(+ session: T,+ change: HitlStateChange,+): T {+ let state = session.state;+ if (change.signIns !== undefined) {+ state = writeSignIns(state, resolveActiveAuthorizationChallenges(change.signIns));+ }+ if (change.relays?.upsert !== undefined) state = upsertRelays(state, change.relays.upsert);+ if (change.relays?.retire !== undefined) state = retireRelays(state, change.relays.retire);+ return state === session.state ? session : { ...session, state };+}++// ---------------------------------------------------------------------------+// Requests+// ---------------------------------------------------------------------------++// Every request the session holds sits under one key, a field per kind, so no kind's ids can+// collide with another's.+interface StoredRequests {+ readonly approvals?: unknown;+ /** The sign-in attempts the session waits on. */+ readonly signIns?: unknown;+ /** Workflow runs' `ctx.ask()` questions and child sessions' requests, by request id. */+ readonly relays?: unknown;+}++function readRequests(state: SessionStateMap | undefined): StoredRequests {+ const requests = state?.[REQUESTS_KEY];+ return isObject(requests) ? requests : {};+}++/** Sets one kind's record; `undefined` drops it, and the key once no kind is left. */+function writeRequests(+ state: SessionStateMap | undefined,+ kind: keyof StoredRequests,+ value: unknown,+): SessionStateMap | undefined {+ const { [kind]: current, ...others } = readRequests(state);+ if (current === undefined && value === undefined) return state;+ const requests = value === undefined ? others : { ...others, [kind]: value };+ const { [REQUESTS_KEY]: _requests, ...rest } = state ?? {};+ if (Object.keys(requests).length > 0) return { ...rest, [REQUESTS_KEY]: requests };+ return Object.keys(rest).length > 0 ? rest : undefined;+}++/**+ * Moves the records builds before checkpoint version 15 kept under+ * {@link LEGACY_HITL_STATE_KEYS} into the requests record as they were stored; each reader is as+ * lenient as its old one. Only the checkpoint upgrade calls it.+ */+export function upgradeLegacyHitlState(+ state: Readonly<Record<string, unknown>>,+): Record<string, unknown> {+ const {+ [LEGACY_HITL_STATE_KEYS.approvals]: approvals,+ [LEGACY_HITL_STATE_KEYS.signIns]: signIns,+ [LEGACY_HITL_STATE_KEYS.relays]: relays,+ ...rest+ } = state;+ let next: SessionStateMap | undefined = rest;+ next = writeRequests(next, "approvals", approvals);+ next = writeRequests(+ next,+ "signIns",+ isObject(signIns) && signIns.challenges !== undefined ? signIns.challenges : signIns,+ );+ const noRelays = isObject(relays) && Object.keys(relays).length === 0;+ next = writeRequests(next, "relays", noRelays ? undefined : relays);+ return next ?? {};+}++// ---------------------------------------------------------------------------+// Approval candidates+// ---------------------------------------------------------------------------++/**+ * A candidate is an Approve unless it records Cancel: candidates persisted+ * before Cancel was authorized carry no decision, and their responder pressed+ * Approve.+ */+function readActiveCandidates(+ candidates: Readonly<Record<string, ActiveApprovalCandidate>>,+): Readonly<Record<string, ActiveApprovalCandidate>> {+ return Object.fromEntries(+ Object.entries(candidates).map(([candidateId, candidate]) => [+ candidateId,+ { ...candidate, decision: candidate.decision === "cancel" ? "cancel" : "approve" },+ ]),+ );+}++/** The approval records. Only `candidates.ts` calls it. */+export function readApprovalState(state: SessionStateMap | undefined): DurableApprovalState {+ const value = readRequests(state).approvals;+ if (typeof value !== "object" || value === null) {+ return {+ activeCandidates: {},+ candidateHistory: [],+ nextCandidateSequence: 0,+ settlements: {},+ };+ }+ const candidate = value as Partial<DurableApprovalState>;+ return {+ activeCandidates:+ typeof candidate.activeCandidates === "object" && candidate.activeCandidates !== null+ ? readActiveCandidates(candidate.activeCandidates)+ : {},+ candidateHistory: Array.isArray(candidate.candidateHistory) ? candidate.candidateHistory : [],+ nextCandidateSequence:+ typeof candidate.nextCandidateSequence === "number" &&+ Number.isSafeInteger(candidate.nextCandidateSequence) &&+ candidate.nextCandidateSequence >= 0+ ? candidate.nextCandidateSequence+ : deriveNextCandidateSequence(candidate),+ settlements:+ typeof candidate.settlements === "object" && candidate.settlements !== null+ ? candidate.settlements+ : {},+ };+}++function deriveNextCandidateSequence(state: Partial<DurableApprovalState>): number {+ return (+ Object.keys(state.activeCandidates ?? {}).length ++ (Array.isArray(state.candidateHistory) ? state.candidateHistory.length : 0)+ );+}++/** Saves the approval records. Only `candidates.ts` calls it. */+export function writeApprovalState(+ state: SessionStateMap | undefined,+ approvalState: DurableApprovalState,+): SessionStateMap {+ return writeRequests(state, "approvals", approvalState) ?? {};+}++/**+ * Drops what a cleared context owned: sign-in attempts and responders' approval progress. `clear`+ * reported each close; relay routes for live tasks stay.+ */+export function discardClearedHitlState<T extends HarnessSessionBase>(session: T): T {+ const state = writeRequests(writeSignIns(session.state, []), "approvals", undefined);+ return { ...session, state };+}++// ---------------------------------------------------------------------------+// Pending sign-ins+// ---------------------------------------------------------------------------++function readSignIns(state: SessionStateMap | undefined): readonly AuthorizationChallenge[] {+ const value = readRequests(state).signIns;+ return Array.isArray(value) ? value : [];+}++function writeSignIns(+ state: SessionStateMap | undefined,+ challenges: readonly AuthorizationChallenge[],+): SessionStateMap | undefined {+ return writeRequests(state, "signIns", challenges.length > 0 ? challenges : undefined);+}++// ---------------------------------------------------------------------------+// Relayed requests+// ---------------------------------------------------------------------------++function readRelays(+ state: SessionStateMap | undefined,+): Readonly<Record<string, ProxyInputRequest>> {+ const raw = readRequests(state).relays;+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return {};+ const result: Record<string, ProxyInputRequest> = {};+ for (const [requestId, value] of Object.entries(raw)) {+ const request = parseProxyInputRequest(value, requestId);+ if (request !== undefined) result[requestId] = request;+ }+ return result;+}++function writeRelays(+ state: SessionStateMap | undefined,+ relays: Readonly<Record<string, ProxyInputRequest>>,+): SessionStateMap | undefined {+ return writeRequests(state, "relays", Object.keys(relays).length > 0 ? relays : undefined);+}++/**+ * A child raising a fresh batch replaces the routes it held for that input source, so the parent+ * never keeps stale request metadata. Other sources' routes stay independently answerable.+ */+function upsertRelays(+ state: SessionStateMap | undefined,+ upsert: NonNullable<RelayChange["upsert"]>,+): SessionStateMap | undefined {+ const kept = Object.entries(readRelays(state)).filter(+ ([, route]) =>+ route.childContinuationToken !== upsert.forChildContinuationToken ||+ route.inputSource !== upsert.inputSource,+ );+ return writeRelays(state, Object.fromEntries([...kept, ...upsert.entries]));+}++function retireRelays(+ state: SessionStateMap | undefined,+ requestIds: readonly string[],+): SessionStateMap | undefined {+ const relays = readRelays(state);+ if (!requestIds.some((requestId) => Object.hasOwn(relays, requestId))) return state;+ return writeRelays(+ state,+ Object.fromEntries(+ Object.entries(relays).filter(([requestId]) => !requestIds.includes(requestId)),+ ),+ );+}diff --git a/packages/eve/src/harness/hitl/sign-ins.ts b/packages/eve/src/harness/hitl/sign-ins.tsnew file mode 100644index 000000000..217a35999--- /dev/null+++ b/packages/eve/src/harness/hitl/sign-ins.ts@@ -0,0 +1,65 @@+import type { AuthorizationChallenge } from "#harness/authorization.js";+import type { ConnectionPrincipal } from "#shared/connection-types.js";++// Which sign-in attempts replace which. Pure: the session state that holds them is+// `requests.ts`'s.++/** The pending sign-ins once `challenges` are asked for: each replaces the attempt it supersedes. */+export function withSignIns(+ previous: readonly AuthorizationChallenge[],+ challenges: readonly AuthorizationChallenge[],+): readonly AuthorizationChallenge[] {+ const active = resolveActiveAuthorizationChallenges(challenges);+ const superseded = supersededChallenges(previous, active);+ return [...previous.filter((challenge) => !superseded.includes(challenge)), ...active];+}++/** Keeps the last challenge for each sign-in and principal. */+export function resolveActiveAuthorizationChallenges(+ challenges: readonly AuthorizationChallenge[],+): readonly AuthorizationChallenge[] {+ return challenges.filter(+ (candidate, index) =>+ !challenges.slice(index + 1).some((replacement) => sameSignIn(candidate, replacement)),+ );+}++/** The attempts in `previous` that `replacements` replace: the same sign-in and principal. */+export function supersededChallenges(+ previous: readonly AuthorizationChallenge[],+ replacements: readonly AuthorizationChallenge[],+): readonly AuthorizationChallenge[] {+ return previous.filter((candidate) =>+ replacements.some((replacement) => sameSignIn(candidate, replacement)),+ );+}++/**+ * Same scope, or the same grant from another scope, such as two tools and a+ * connection that all use one Vercel Connect connector. Approval sign-ins+ * stay per candidate because each one settles its own approval.+ */+function sameSignIn(+ left: Pick<AuthorizationChallenge, "candidateId" | "grant" | "name" | "principal">,+ right: Pick<AuthorizationChallenge, "candidateId" | "grant" | "name" | "principal">,+): boolean {+ const sameGrant =+ left.grant !== undefined &&+ left.grant === right.grant &&+ left.candidateId === right.candidateId;+ return (left.name === right.name || sameGrant) && samePrincipal(left.principal, right.principal);+}++function samePrincipal(+ left: ConnectionPrincipal | undefined,+ right: ConnectionPrincipal | undefined,+): boolean {+ if (left === undefined || right === undefined) return left === right;+ if (left.type === "app" || right.type === "app") return left.type === right.type;+ return left.id === right.id && left.issuer === right.issuer;+}++/** The key a sign-in callback names its attempt by. */+export function signInAttemptKey(challenge: AuthorizationChallenge): string {+ return challenge.attemptId ?? challenge.candidateId ?? challenge.name;+}diff --git a/packages/eve/src/harness/inline-tool-authorization.ts b/packages/eve/src/harness/inline-tool-authorization.tsindex 2fe9146d2..f574982ff 100644--- a/packages/eve/src/harness/inline-tool-authorization.ts+++ b/packages/eve/src/harness/inline-tool-authorization.ts@@ -5,8 +5,8 @@ import {type AuthorizationSignal,isAuthorizationSignal,isPendingAuthorizationToolOutput,- resolveActiveAuthorizationChallenges,} from "#harness/authorization.js";+import { resolveActiveAuthorizationChallenges } from "#harness/hitl/sign-ins.js";import { readToolInterrupt } from "#harness/tool-interrupts.js";/** Returns whether an inline tool result represents a pending authorization interrupt. */diff --git a/packages/eve/src/harness/issue-3494-adversarial.integration.test.ts b/packages/eve/src/harness/issue-3494-adversarial.integration.test.tsindex 27e6fad01..f6d405da0 100644--- a/packages/eve/src/harness/issue-3494-adversarial.integration.test.ts+++ b/packages/eve/src/harness/issue-3494-adversarial.integration.test.ts@@ -6,7 +6,10 @@ import {getApprovalAuditState,markApprovalCandidateAuthorizationRequired,} from "#harness/hitl/candidates.js";-import { setPendingAuthorization } from "#harness/authorization.js";++import { withSignIns } from "#harness/hitl/sign-ins.js";+import { readHitlState, writeHitlState } from "#harness/hitl/requests.js";+import { z } from "zod";import { ContextContainer, contextStorage } from "#context/container.js";import { SessionKey } from "#context/keys.js";@@ -611,17 +614,15 @@ it("keeps the turn held while a responder signs in, and fails the sign-in on expchallenge: { url: "https://example.com/sign-in" },},];- f.updateSession((session) => ({- ...session,- state: setPendingAuthorization(- markApprovalCandidateAuthorizationRequired({- state: session.state,- candidateId: candidate.candidateId,- authorizationChallenges: challenges,- }),- { challenges },- ),- }));+ f.updateSession((session) => {+ const state = markApprovalCandidateAuthorizationRequired({+ state: session.state,+ candidateId: candidate.candidateId,+ authorizationChallenges: challenges,+ });+ const signIns = withSignIns(readHitlState(state).signIns, challenges);+ return { ...session, state: writeHitlState({ state }, { signIns }).state };+ });f.record(createAuthorizationRequiredEvent({attemptId: "notes-attempt",diff --git a/packages/eve/src/harness/session-machine/commit.ts b/packages/eve/src/harness/session-machine/commit.tsindex 2237a2641..eed65762f 100644--- a/packages/eve/src/harness/session-machine/commit.ts+++ b/packages/eve/src/harness/session-machine/commit.ts@@ -1,30 +1,22 @@import { getSessionUsage } from "#harness/turn-tag-state.js";import type { ModelMessage } from "ai";-import {- getPendingAuthorization,- setPendingAuthorization,- type AuthorizationChallenge,-} from "#harness/authorization.js";-import {- clearProxyInputRequestsWhere,- getProxyInputRequests,-} from "#harness/proxy-input-requests.js";+import type { AuthorizationChallenge } from "#harness/authorization.js";import { validateHarnessModelMessages } from "#harness/messages.js";import type { HarnessSession, HarnessSessionBase, SessionStateMap } from "#harness/types.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";import type { SessionProjection } from "#protocol/session-projection.js";+import { readHitlState, writeHitlState, type RelayChange } from "#harness/hitl/requests.js";import { readTurnState, writeTurnState, type TurnState } from "./state.js";import type { SessionView } from "./view.js";-import { clearPendingAuthorization } from "#harness/authorization.js";// The save side of the machine. A transition returns the events that report what changed and// the execution state that follows; `applyTransition` publishes the events in order (the publish-// sink folds each into the projection) and writes the rest. Nothing else writes `TurnState`.+// sink folds each into the projection) and writes the rest. The turn state also has direct lifecycle helpers.// A private record lives only while the projection shows its owner open, so closing an owner is// one event: a transition reports it, and the save drops the record here.-/** What a transition returns. Nothing else changes session state. */+/** What a machine transition returns; approval storage still has direct writers. */export interface Transition {readonly turn: TurnState;readonly events: readonly UnstampedMessageStreamEvent[];@@ -34,6 +26,8 @@ export interface Transition {readonly clearsHistory?: true;/** Every sign-in the session waits on once the transition applies; `[]` withdraws them all. */readonly signIns?: readonly AuthorizationChallenge[];+ /** Relay routes the transition records or retires. */+ readonly relays?: RelayChange;}/** Publishes one event; `messages` is the conversation hooks see with it. */@@ -46,10 +40,11 @@ export function sessionView(projection: SessionProjection,state: SessionStateMap | undefined,): SessionView {+ const hitl = readHitlState(state);return {projection,- relayedRequestIds: new Set(getProxyInputRequests(state).keys()),- signIns: getPendingAuthorization(state)?.challenges ?? [],+ relayedRequestIds: new Set(hitl.relays.keys()),+ signIns: hitl.signIns,turn: readTurnState(state),usage: getSessionUsage({ state }),};@@ -69,24 +64,33 @@ const READS_HISTORY: ReadonlySet<string> = new Set([* Publishes a transition's events, then saves what it changed. A transition that changes history* needs a session restored with it.*/-export async function applyTransition<T extends HarnessSessionBase>(+export async function applyTransition<T extends { readonly state?: SessionStateMap }>(session: T,transition: Transition,publish: Publish,messages?: readonly ModelMessage[],): Promise<T> {+ await publishTransition(transition, publish, messages);+ return saveTransition(session, transition);+}++/** Publishes a transition's events, in order. */+export async function publishTransition(+ transition: Transition,+ publish: Publish,+ messages?: readonly ModelMessage[],+): Promise<void> {for (const event of transition.events) {await publish(event, READS_HISTORY.has(event.type) ? messages : undefined);}- const state =- transition.signIns === undefined- ? session.state- : transition.signIns.length === 0- ? clearPendingAuthorization(session.state)- : setPendingAuthorization(clearPendingAuthorization(session.state), {- challenges: transition.signIns,- });- const next = writeTurnState({ ...session, state }, transition.turn);+}++/** Saves what a transition changes once its events are published. */+export function saveTransition<T extends { readonly state?: SessionStateMap }>(+ session: T,+ transition: Transition,+): T {+ const next = writeTurnState(writeHitlState(session, transition), transition.turn);const commit = transition.commit ?? [];if (transition.clearsHistory !== true && commit.length === 0) return next;if (!("history" in session)) {@@ -104,8 +108,9 @@ export function dropClosedRecords<T extends HarnessSessionBase>(session: T,projection: SessionProjection,): T {- return clearProxyInputRequestsWhere(session, (_route, requestId) => {+ const closed = [...readHitlState(session.state).relays.keys()].filter((requestId) => {const input = projection.inputs[requestId];return input === undefined || input.status === "settled";});+ return writeHitlState(session, { relays: { retire: closed } });}diff --git a/packages/eve/src/harness/session-machine/transitions.ts b/packages/eve/src/harness/session-machine/transitions.tsindex 033d29f6a..3b61a5fa4 100644--- a/packages/eve/src/harness/session-machine/transitions.ts+++ b/packages/eve/src/harness/session-machine/transitions.ts@@ -50,6 +50,8 @@ import type { JsonObject, JsonValue } from "#shared/json.js";import type { TokenUsage } from "#shared/token-usage.js";import type { Transition } from "./commit.js";import { inputWithdrawn, signInWithdrawn } from "./events.js";+import { signInAttemptKey } from "#harness/hitl/sign-ins.js";+import { toProxyInputRequestEntries, type WorkflowAskRoute } from "#harness/hitl/relays.js";import type { StepCoordinates, SuspendedStep, TurnState } from "./state.js";import {activeTurnId,@@ -513,6 +515,9 @@ export function relay(input: {readonly payload: SubagentInputRequestHookPayload | SubagentAuthorizationEventHookPayload;readonly replacedRequestIds?: Iterable<string>;+ /** The workflow tool run that relays the request, and the hook its `ctx.ask()` answers reach. */+ readonly runId?: string;+ readonly workflowAsk?: WorkflowAskRoute;},): Transition {const { payload } = input;@@ -537,7 +542,29 @@ export function relay(if (event.type !== "authorization.required") return unchanged(view, events);}events.push(...hold(view, { on: "input" }).events);- return unchanged(view, events);+ if (payload.kind !== "subagent-input-request") return unchanged(view, events);+ // A child's fresh batch replaces the routes its prior one held.+ const entries = toProxyInputRequestEntries(payload).map(+ ([requestId, route]) =>+ [+ requestId,+ {+ ...route,+ ...(input.workflowAsk !== undefined && { workflowAsk: input.workflowAsk }),+ ...(input.runId !== undefined && { runId: input.runId }),+ },+ ] as const,+ );+ return {+ ...unchanged(view, events),+ relays: {+ upsert: {+ entries,+ forChildContinuationToken: payload.childContinuationToken,+ inputSource: payload.inputSource,+ },+ },+ };}/**@@ -558,12 +585,20 @@ export function routeAnswer(readonly event: StepCoordinates;readonly resolutions: readonly InputResolution[];}[];+ /**+ * Answers left other relayed requests pending, and nothing for the turn itself: the open+ * turn stays held, as after a partial approval answer.+ */+ readonly holds?: boolean;},): Transition {const events: UnstampedMessageStreamEvent[] = input.children.filter((child) => child.resolutions.length > 0).map((child) => createInputResolvedEvent({ resolutions: child.resolutions, ...child.event }));- return unchanged(view, events);+ if (input.holds === true) events.push(...hold(view, { on: "input" }).events);+ // The answered routes retire, so a later delivery can't route through them.+ const retire = input.children.flatMap((child) => child.resolutions.map((r) => r.requestId));+ return { ...unchanged(view, events), ...(retire.length > 0 && { relays: { retire } }) };}/**@@ -600,6 +635,21 @@ export function runSignIn(// Sign-ins// ---------------------------------------------------------------------------+/**+ * Sign-in callbacks matched the attempts `attemptIds` name: the session stops waiting on them.+ * Their completions report once the turn they resume runs (`completeSignIn`).+ */+export function matchSignIns(+ view: SessionView,+ input: { readonly attemptIds: readonly string[] },+): Transition {+ const matched = new Set(input.attemptIds);+ return {+ ...unchanged(view, []),+ signIns: view.signIns.filter((challenge) => !matched.has(signInAttemptKey(challenge))),+ };+}+/** Sign-in callbacks arrived: each completion is reported at the coordinates of the turn that asked. */export function completeSignIn(view: SessionView,diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.tsindex 43fdc92eb..aea9765b5 100644--- a/packages/eve/src/harness/tool-loop.test.ts+++ b/packages/eve/src/harness/tool-loop.test.ts@@ -54,11 +54,10 @@ import {createUserMessage,type HarnessModelMessage,} from "#harness/messages.js";-import {- getPendingAuthorization,- modelFacingAuthorizationOutput,- requestAuthorization,-} from "#harness/authorization.js";++import { readHitlState } from "#harness/hitl/requests.js";++import { modelFacingAuthorizationOutput, requestAuthorization } from "#harness/authorization.js";import { applyTransition, sessionView } from "#harness/session-machine/commit.js";import { requireSignIn } from "#harness/hitl/approvals.js";import { createAuthorizationRequiredEvent } from "#protocol/message.js";@@ -6412,9 +6411,7 @@ describe("createToolLoopHarness", () => {expect(result.next).toBeNull();expect(result.settledTurn).toBeUndefined();- expect(getPendingAuthorization(result.session.state)).toEqual({- challenges: full.challenges,- });+ expect(readHitlState(result.session.state).signIns).toEqual(full.challenges);expect(events.filter((event) => event.type === "authorization.required")).toEqual([expect.objectContaining({data: expect.objectContaining({@@ -6533,9 +6530,7 @@ describe("createToolLoopHarness", () => {expect(result.next).toBeNull();expect(result.settledTurn).toBeUndefined();- expect(getPendingAuthorization(result.session.state)).toEqual({- challenges: full.challenges,- });+ expect(readHitlState(result.session.state).signIns).toEqual(full.challenges);const authRequired = events.filter((event) => event.type === "authorization.required");expect(authRequired).toHaveLength(1);diff --git a/packages/eve/src/internal/testing/session-machine.ts b/packages/eve/src/internal/testing/session-machine.tsindex 0819aa21f..073316c6a 100644--- a/packages/eve/src/internal/testing/session-machine.ts+++ b/packages/eve/src/internal/testing/session-machine.ts@@ -5,6 +5,7 @@ import { grantedApprovalKeys, parkOnApprovals } from "#harness/hitl/approvals.jsimport { suspendStep } from "#harness/session-machine/transitions.js";import { withoutApprovalParts } from "#harness/step/after-model.js";import { sessionView } from "#harness/session-machine/commit.js";+import { writeHitlState, type RelayChange } from "#harness/hitl/requests.js";import { readTurnState, writeTurnState } from "#harness/session-machine/state.js";import {ensureSessionProjection,@@ -172,3 +173,11 @@ export function grantedKeys(approvalKey,);}++/** `session` relaying requests for a child, as the session machine records them. */+export function withRelays<T extends { readonly state?: SessionStateMap }>(+ session: T,+ upsert: NonNullable<RelayChange["upsert"]>,+): T {+ return writeHitlState(session, { relays: { upsert } });+}diff --git a/packages/eve/src/subagents/adapter.ts b/packages/eve/src/subagents/adapter.tsindex 5387a8dc5..7a628f899 100644--- a/packages/eve/src/subagents/adapter.ts+++ b/packages/eve/src/subagents/adapter.ts@@ -5,7 +5,7 @@ import type {SubagentInputRequestHookPayload,} from "#channel/types.js";import { ContinuationTokenKey, SessionIdKey, SessionInboxKey } from "#context/keys.js";-import { resolvedForParent } from "#harness/proxy-input-requests.js";+import { resolvedForParent } from "#harness/hitl/relays.js";import { SUBAGENT_ADAPTER_KIND, isSubagentAdapterState } from "#subagents/adapter-state.js";import { createErrorId, createLogger } from "#internal/logging.js";diff --git a/packages/eve/src/subagents/event-proxy-step.integration.test.ts b/packages/eve/src/subagents/event-proxy-step.integration.test.tsindex f4560cb1e..83654fc49 100644--- a/packages/eve/src/subagents/event-proxy-step.integration.test.ts+++ b/packages/eve/src/subagents/event-proxy-step.integration.test.ts@@ -1,5 +1,7 @@import { describe, expect, it, vi } from "vitest";+import { readHitlState } from "#harness/hitl/requests.js";+import type { ChannelAdapter } from "#channel/adapter.js";import type { SubagentInputRequestHookPayload } from "#channel/types.js";import { ContextContainer } from "#context/container.js";@@ -16,7 +18,7 @@ import { openSessionEventPublisher } from "#execution/publish-session-events.js"import { enterSessionProjection } from "#harness/session-machine/current.js";import { positionOf, withOpenTurn } from "#internal/testing/session-machine.js";import { createSessionLimitContinuationRequest } from "#harness/hitl/budget-request.js";-import { getProxyInputRequests } from "#harness/proxy-input-requests.js";+import { createAuthorizationRequiredEvent, type MessageStreamEvent } from "#protocol/message.js";import type { HookContext } from "#public/definitions/hook.js";import { createRuntimeHookRegistry } from "#runtime/hooks/registry.js";@@ -238,7 +240,7 @@ describe("proxied stream hooks", () => {});expect(f.events.at(-1)).toMatchObject({ data: event.data, type: event.type });const after = closed.sessionState.snapshot.session.state;- expect(getProxyInputRequests(after).has("approval-1")).toBe(false);+ expect(readHitlState(after).relays.has("approval-1")).toBe(false);expect(routeDeliverPayload({ ...answer, state: after })).toMatchObject({forChildren: [],forSelf: { message: "approve" },@@ -531,7 +533,7 @@ describe("proxied stream hooks", () => {inputSource: JSON.stringify([`child-${name}`, null]),})),);- expect([...getProxyInputRequests(session.state).keys()]).toEqual([+ expect([...readHitlState(session.state).relays.keys()]).toEqual(["approval-Alice","approval-Bob",]);@@ -577,7 +579,7 @@ describe("proxied stream hooks", () => {expect(f.order).not.toContain("channel:input.requested");expect(f.events).toHaveLength(0);expect(f.sessionWritable.locked).toBe(false);- expect(getProxyInputRequests(f.durableSession.state).size).toBe(0);+ expect(readHitlState(f.durableSession.state).relays.size).toBe(0);} finally {vi.unstubAllGlobals();}diff --git a/packages/eve/src/subagents/event-proxy-step.ts b/packages/eve/src/subagents/event-proxy-step.tsindex 24ed85fec..cf21b7d74 100644--- a/packages/eve/src/subagents/event-proxy-step.ts+++ b/packages/eve/src/subagents/event-proxy-step.ts@@ -3,7 +3,6 @@ import type {SubagentInputRequestHookPayload,} from "#channel/types.js";import {- publishFromSessionStep,restoreSessionStep,type PublishedSessionEvents,type RestoredSessionStep,@@ -13,15 +12,10 @@ import {withSessionStateDelta,type SessionStateTransition,} from "#execution/session/state-delta.js";-import {- getProxyInputRequests,- toProxyInputRequestEntries,- upsertProxyInputRequests,-} from "#harness/proxy-input-requests.js";-import { currentProjection } from "#harness/session-machine/current.js";-import { applyTransition, sessionView } from "#harness/session-machine/commit.js";+import { commitSessionStep } from "#execution/publish-session-events.js";+import { readHitlState } from "#harness/hitl/index.js";+import type { WorkflowAskRoute } from "#harness/hitl/relays.js";import { relay } from "#harness/session-machine/transitions.js";-import type { WorkflowAskRoute } from "#harness/proxy-input-requests.js";type SubagentEventHookPayload =| SubagentAuthorizationEventHookPayload@@ -59,61 +53,36 @@ export async function emitProxiedSubagentEvent(readonly hookPayload: SubagentEventHookPayload;},): Promise<PublishedSessionEvents> {- const { ctx, hookPayload, runId, workflowAsk } = input;- const { published } = await publishFromSessionStep(input, {- origin: "relayed",- inputSource:- hookPayload.kind === "subagent-input-request"- ? JSON.stringify([hookPayload.childContinuationToken, hookPayload.inputSource ?? null])- : undefined,- async publish(emit, session) {- const view = sessionView(currentProjection(ctx), session.state);- const routes =+ const { hookPayload, runId, workflowAsk } = input;+ // A child's fresh batch replaces its prior one, whose routes stop working, so readers+ // must stop offering what it held.+ const incoming = new Set(+ hookPayload.kind === "subagent-input-request"+ ? hookPayload.event.requests.map((request) => request.requestId)+ : [],+ );+ const replaced =+ hookPayload.kind !== "subagent-input-request"+ ? []+ : [...readHitlState(input.durableSession.state).relays]+ .filter(+ ([requestId, route]) =>+ route.childContinuationToken === hookPayload.childContinuationToken &&+ route.inputSource === hookPayload.inputSource &&+ !incoming.has(requestId),+ )+ .map(([requestId]) => requestId);+ return await commitSessionStep(+ input,+ (view) => [+ relay(view, { payload: hookPayload, replacedRequestIds: replaced, runId, workflowAsk }),+ ],+ {+ origin: "relayed",+ inputSource:hookPayload.kind === "subagent-input-request"- ? toProxyInputRequestEntries(hookPayload)- : undefined;- // A child's fresh batch replaces its prior one, whose routes stop working, so readers- // must stop offering what it held.- const incoming = new Set(routes?.map(([requestId]) => requestId));- const replaced =- hookPayload.kind !== "subagent-input-request"- ? []- : [...getProxyInputRequests(session.state)]- .filter(- ([requestId, route]) =>- route.childContinuationToken === hookPayload.childContinuationToken &&- route.inputSource === hookPayload.inputSource &&- !incoming.has(requestId),- )- .map(([requestId]) => requestId);- // A relay changes no execution state, only what the session reports.- await applyTransition(- session,- relay(view, { payload: hookPayload, replacedRequestIds: replaced }),- emit,- );- return routes;+ ? JSON.stringify([hookPayload.childContinuationToken, hookPayload.inputSource ?? null])+ : undefined,},- updateSession(session, routes) {- if (routes === undefined || hookPayload.kind !== "subagent-input-request") {- return { session };- }- return {- session: upsertProxyInputRequests({- entries: routes.map(([requestId, route]) => [- requestId,- {- ...route,- ...(workflowAsk !== undefined && { workflowAsk }),- ...(runId !== undefined && { runId }),- },- ]),- forChildContinuationToken: hookPayload.childContinuationToken,- inputSource: hookPayload.inputSource,- session,- }),- };- },- });- return published;+ );}diff --git a/packages/eve/src/subagents/hitl-proxy.integration.test.ts b/packages/eve/src/subagents/hitl-proxy.integration.test.tsindex 0578fe18f..0307ebb67 100644--- a/packages/eve/src/subagents/hitl-proxy.integration.test.ts+++ b/packages/eve/src/subagents/hitl-proxy.integration.test.ts@@ -1,6 +1,8 @@-import { toProxyInputRequestEntries } from "#harness/proxy-input-requests.js";+import { toProxyInputRequestEntries } from "#harness/hitl/relays.js";import { describe, expect, it } from "vitest";+import { readHitlState } from "#harness/hitl/requests.js";+import type { ChannelAdapter, ChannelAdapterContext } from "#channel/adapter.js";import { buildAdapterContext } from "#channel/adapter-context.js";import { callAdapterEventHandler } from "#channel/adapter.js";@@ -13,8 +15,8 @@ import { serializeContext } from "#context/serialize.js";import { applyTransition, sessionView } from "#harness/session-machine/commit.js";import { relay } from "#harness/session-machine/transitions.js";import { storedProjection } from "#harness/session-machine/view.js";-import { withOpenTurn } from "#internal/testing/session-machine.js";-import { hasProxyInputRequests, upsertProxyInputRequests } from "#harness/proxy-input-requests.js";+import { withOpenTurn, withRelays } from "#internal/testing/session-machine.js";+import type { HarnessEmitFn, HarnessSession } from "#harness/types.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";import type { InputRequest } from "#shared/input.js";@@ -327,10 +329,9 @@ describe("subagent HITL proxy → Slack-style text-approve regression (Finding #// The resolved responses now flow through the proxy router. With// the child's proxy entry recorded on the parent session, the// response routes back down to the right descendant.- const parkedSession = upsertProxyInputRequests({- entries,+ const parkedSession = withRelays(buildEmptySession("parent-token", "sess-parent"), {+ entries: entries,forChildContinuationToken: hookPayload.childContinuationToken,- session: buildEmptySession("parent-token", "sess-parent"),});const routed = routeDeliverPayload({@@ -415,18 +416,16 @@ describe("subagent HITL proxy → concurrent-descendant routing", () => {// entries (what the parent runtime would accumulate across the// two proxy steps).let parkedSession = buildEmptySession("parent-token", "sess-parent");- parkedSession = upsertProxyInputRequests({+ parkedSession = withRelays(parkedSession, {entries: entriesA,forChildContinuationToken: payloadA.childContinuationToken,- session: parkedSession,});- parkedSession = upsertProxyInputRequests({+ parkedSession = withRelays(parkedSession, {entries: entriesB,forChildContinuationToken: payloadB.childContinuationToken,- session: parkedSession,});- expect(hasProxyInputRequests(parkedSession.state)).toBe(true);+ expect(readHitlState(parkedSession.state).relays.size > 0).toBe(true);// One inbound deliver carrying responses for both descendants.// Simulates a UI that lets the user answer both prompts beforediff --git a/packages/eve/src/subagents/hitl-proxy.test.ts b/packages/eve/src/subagents/hitl-proxy.test.tsindex 65c44d35c..ce7c9e747 100644--- a/packages/eve/src/subagents/hitl-proxy.test.ts+++ b/packages/eve/src/subagents/hitl-proxy.test.ts@@ -1,12 +1,10 @@import { describe, expect, it } from "vitest";-import {- retireProxyInputRequests,- toProxyInputRequestEntries,- upsertProxyInputRequests,-} from "#harness/proxy-input-requests.js";+import { writeHitlState } from "#harness/hitl/requests.js";++import { toProxyInputRequestEntries } from "#harness/hitl/relays.js";import type { HarnessSession } from "#harness/types.js";-import { withParkedStep } from "#internal/testing/session-machine.js";+import { withParkedStep, withRelays } from "#internal/testing/session-machine.js";import type { InputRequest } from "#shared/input.js";import { routeDeliverPayload } from "#subagents/hitl-proxy.js";@@ -29,7 +27,7 @@ function createSession(state?: Record<string, unknown>): HarnessSession {describe("routeDeliverPayload", () => {it("keeps original child inboxes separate when they share a continuation alias", () => {- const session = upsertProxyInputRequests({+ const session = withRelays(createSession(), {entries: [["req-a",@@ -51,7 +49,6 @@ describe("routeDeliverPayload", () => {],],forChildContinuationToken: "child-alias",- session: createSession(),});const routed = routeDeliverPayload({@@ -79,15 +76,8 @@ describe("routeDeliverPayload", () => {});it("routes responses to matching descendants and keeps unknown ones on forSelf", () => {- const session = upsertProxyInputRequests({- entries: [- [- "req-a",- { childContinuationToken: "child-a", event: REQUEST_EVENT, kind: "tool-approval" },- ],- ],- forChildContinuationToken: "child-a",- session: upsertProxyInputRequests({+ const session = withRelays(+ withRelays(createSession(), {entries: [["req-b",@@ -95,9 +85,17 @@ describe("routeDeliverPayload", () => {],],forChildContinuationToken: "child-b",- session: createSession(),}),- });+ {+ entries: [+ [+ "req-a",+ { childContinuationToken: "child-a", event: REQUEST_EVENT, kind: "tool-approval" },+ ],+ ],+ forChildContinuationToken: "child-a",+ },+ );const routed = routeDeliverPayload({payload: {@@ -136,7 +134,7 @@ describe("routeDeliverPayload", () => {});it("returns forSelf as undefined when every response routes to a descendant", () => {- const session = upsertProxyInputRequests({+ const session = withRelays(createSession(), {entries: [["req-a",@@ -144,7 +142,6 @@ describe("routeDeliverPayload", () => {],],forChildContinuationToken: "child-a",- session: createSession(),});const routed = routeDeliverPayload({@@ -159,7 +156,7 @@ describe("routeDeliverPayload", () => {});it("asks the parent to cancel after routing Stop to a descendant session-limit request", () => {- const session = upsertProxyInputRequests({+ const session = withRelays(createSession(), {entries: [["req-limit",@@ -167,7 +164,6 @@ describe("routeDeliverPayload", () => {],],forChildContinuationToken: "child-a",- session: createSession(),});const routed = routeDeliverPayload({@@ -202,7 +198,7 @@ describe("routeDeliverPayload source coordinates", () => {it("keeps distinct input batches for one remote session separate", () => {let session = createSession();for (const [index, name] of ["alice", "bob"].entries()) {- session = upsertProxyInputRequests({+ session = withRelays(session, {entries: [[`ask-${name}`,@@ -221,7 +217,6 @@ describe("routeDeliverPayload source coordinates", () => {],forChildContinuationToken: "remote-inbox",inputSource: `workflow-${name}`,- session,});}const routed = routeDeliverPayload({@@ -267,7 +262,7 @@ describe("routeDeliverPayload message resolution", () => {): HarnessSession {let session = createSession();for (const [requestId, question] of questions) {- session = upsertProxyInputRequests({+ session = withRelays(session, {entries: [[requestId,@@ -288,7 +283,6 @@ describe("routeDeliverPayload message resolution", () => {],],forChildContinuationToken: `hook-${requestId}`,- session,});}return session;@@ -398,21 +392,8 @@ describe("routeDeliverPayload message resolution", () => {});it("does not answer a later question while a request it can't match comes first", () => {- const session = upsertProxyInputRequests({- entries: [- [- "ask-1",- {- workflowAsk: { control: "control-ask-1" },- reply: { allowFreeform: true },- childContinuationToken: "hook-ask-1",- event: REQUEST_EVENT,- kind: "question",- },- ],- ],- forChildContinuationToken: "hook-ask-1",- session: upsertProxyInputRequests({+ const session = withRelays(+ withRelays(createSession(), {entries: [["child-ask",@@ -420,9 +401,23 @@ describe("routeDeliverPayload message resolution", () => {],],forChildContinuationToken: "child-token",- session: createSession(),}),- });+ {+ entries: [+ [+ "ask-1",+ {+ workflowAsk: { control: "control-ask-1" },+ reply: { allowFreeform: true },+ childContinuationToken: "hook-ask-1",+ event: REQUEST_EVENT,+ kind: "question",+ },+ ],+ ],+ forChildContinuationToken: "hook-ask-1",+ },+ );const routed = routeDeliverPayload({payload: { message: "Use the canary pool" },resolveMessage: true,@@ -434,7 +429,7 @@ describe("routeDeliverPayload message resolution", () => {});function childPromptSession(requests: readonly InputRequest[]): HarnessSession {- return upsertProxyInputRequests({+ return withRelays(createSession(), {entries: toProxyInputRequestEntries({callId: "call-1",childContinuationToken: "child-token",@@ -444,7 +439,6 @@ describe("routeDeliverPayload message resolution", () => {subagentName: "reviewer",}),forChildContinuationToken: "child-token",- session: createSession(),});}@@ -494,7 +488,7 @@ describe("routeDeliverPayload message resolution", () => {const second = routeDeliverPayload({payload: { message: "cancel" },resolveMessage: true,- state: retireProxyInputRequests(session, ["approve-1"]).state,+ state: writeHitlState(session, { relays: { retire: ["approve-1"] } }).state,});expect(second.forChildren).toMatchObject([{@@ -521,7 +515,7 @@ describe("routeDeliverPayload message resolution", () => {});it("answers the first of two children's prompts with a typed reply", () => {- const session = upsertProxyInputRequests({+ const session = withRelays(childPromptSession([childPrompt("approve-1", "tool-approval")]), {entries: toProxyInputRequestEntries({callId: "call-2",childContinuationToken: "other-child-token",@@ -531,7 +525,6 @@ describe("routeDeliverPayload message resolution", () => {subagentName: "deployer",}),forChildContinuationToken: "other-child-token",- session: childPromptSession([childPrompt("approve-1", "tool-approval")]),});const routed = routeDeliverPayload({payload: { message: "approve" },diff --git a/packages/eve/src/subagents/hitl-proxy.ts b/packages/eve/src/subagents/hitl-proxy.tsindex ce0faf6cd..e43dbeb42 100644--- a/packages/eve/src/subagents/hitl-proxy.ts+++ b/packages/eve/src/subagents/hitl-proxy.ts@@ -4,8 +4,9 @@ import { resolveInputOutcome } from "#harness/input-request-resolution.js";import { firstOpenInput } from "#harness/open-input-request.js";import { storedProjection } from "#harness/session-machine/view.js";import type { StepCoordinates as PendingInputBatchEvent } from "#harness/session-machine/view.js";-import { getProxyInputRequests, resolvedByChild } from "#harness/proxy-input-requests.js";-import type { WorkflowAskRoute, ProxyInputRequest } from "#harness/proxy-input-requests.js";+import { readHitlState } from "#harness/hitl/index.js";+import { resolvedByChild } from "#harness/hitl/relays.js";+import type { WorkflowAskRoute, ProxyInputRequest } from "#harness/hitl/relays.js";import type { SessionStateMap } from "#harness/types.js";import type { InputResolution } from "#protocol/message.js";import type { InputResponse } from "#shared/input.js";@@ -85,7 +86,7 @@ export function routeDeliverPayload(input: {readonly resolveMessage?: boolean;readonly state: SessionStateMap | undefined;}): RoutedDeliverPayload {- const entries = getProxyInputRequests(input.state);+ const entries = readHitlState(input.state).relays;const routable = (requestId: string, route: ProxyInputRequest | undefined) =>route !== undefined && input.allowRoute?.(requestId, route) !== false;const message = resolveMessageAgainstFirstRequest({diff --git a/scripts/guard-invariants.mjs b/scripts/guard-invariants.mjsindex 1757ae2ae..d23b76f1b 100644--- a/scripts/guard-invariants.mjs+++ b/scripts/guard-invariants.mjs@@ -125,16 +125,17 @@* so telemetry ownership survives renamed and namespaced tools.* rule 50 — The human-in-the-loop lifecycle in `harness/hitl/` is* reached only through its `index.ts`, its request vocabulary- * (`approval-prompt`, `budget-request`), so replacing it changes one- * seam.+ * (`approval-prompt`, `budget-request`, `relays`, `sign-ins`) and+ * read surface via index.ts. Only commit.ts and checkpoint-migrations.ts+ * import requests.ts for saving and legacy upgrades.* rule 51 — Only the session machine (`harness/session-machine/`) and the* human-in-the-loop lifecycle it delegates to* (`harness/hitl/`) build lifecycle events and read the- * machine's private state. Every change to a turn, request,- * sign-in, task, or call outcome is a transition that returns its- * events, so nothing changes without readers hearing it. The model- * step's streamed content (its calls and their inline results) is- * built where it streams.+ * machine's private state. The guard checks only those imports;+ * it does not prove every state change emits events (approval+ * candidates are still written directly, and `matchSignIns`+ * emits none). The model step's streamed content (its calls and+ * their inline results) is built where it streams.* rule 52 — The tracing library in `packages/tracing/src/` imports only* itself and external packages. eve reaches it only through the* vendored root, delegation, otel, and ai-sdk entrypoints under@@ -550,7 +551,7 @@ function checkRule47(posix, lines, violations) {const HUMAN_INPUT_DIR = "packages/eve/src/harness/hitl/";const HUMAN_INPUT_PRIVATE_IMPORT_RE =- /["'](?:#harness\/|(?:\.\.?\/)+)hitl\/(?!(?:index|approval-prompt|budget-request)\.js["'])/;+ /["'](?:#harness\/|(?:\.\.?\/)+)hitl\/(?!(?:index|approval-prompt|budget-request|relays|sign-ins)\.js["'])/;/** @param {string} posix @param {string[]} lines @param {Violation[]} violations */function checkRule50(posix, lines, violations) {@@ -563,6 +564,12 @@ function checkRule50(posix, lines, violations) {return;lines.forEach((line, idx) => {if (!HUMAN_INPUT_PRIVATE_IMPORT_RE.test(line)) return;+ if (+ /["']#harness\/hitl\/requests\.js["']/.test(line) &&+ (posix === "packages/eve/src/harness/session-machine/commit.ts" ||+ posix === "packages/eve/src/execution/session/checkpoint-migrations.ts")+ )+ return;violations.push({rule: 50,file: posix,diff --git a/scripts/hitl-state-readers.test.mjs b/scripts/hitl-state-readers.test.mjsnew file mode 100644index 000000000..85b248bee--- /dev/null+++ b/scripts/hitl-state-readers.test.mjs@@ -0,0 +1,56 @@+import assert from "node:assert/strict";+import { readFile } from "node:fs/promises";+import test from "node:test";++test("rule 50 keeps requests storage private with only the save and migration exceptions", async () => {+ const source = await readFile(new URL("./guard-invariants.mjs", import.meta.url), "utf8");+ // The retired HITL accessor scanner stays gone; rule 52 now guards tracing imports.+ for (const retired of [+ "hitlStateAccessors",+ "hitl-state-readers.mjs",+ "HitlStateAccessorsByFile",+ ])+ assert.ok(!source.includes(retired), retired);+ const rule = source.slice(+ source.indexOf("const HUMAN_INPUT_PRIVATE_IMPORT_RE"),+ source.indexOf("// ---------- Rule 51"),+ );+ const expression = rule.match(/ (\/.*\/);/)[1];+ const pattern = new RegExp(expression.slice(1, -1));+ assert.ok(pattern.test('from "#harness/hitl/requests.js"'));+ assert.ok(pattern.test('from "../hitl/requests.js"'));+ assert.ok(!pattern.test('from "#harness/hitl/index.js"'));+ assert.ok(rule.includes('posix === "packages/eve/src/harness/session-machine/commit.ts"'));+ assert.ok(+ rule.includes('posix === "packages/eve/src/execution/session/checkpoint-migrations.ts"'),+ );+ const check = new Function(+ "HUMAN_INPUT_DIR",+ "HUMAN_INPUT_PRIVATE_IMPORT_RE",+ rule.slice(rule.indexOf("function checkRule50")) + "; return checkRule50;",+ )("packages/eve/src/harness/hitl/", pattern);+ for (const file of [+ "packages/eve/src/execution/new-step.ts",+ "packages/eve/src/harness/other.ts",+ ]) {+ const violations = [];+ check(+ file,+ ['import { writeHitlState as save } from "#harness/hitl/requests.js";'],+ violations,+ );+ assert.equal(violations.length, 1);+ assert.equal(violations[0].rule, 50);+ const readers = [];+ check(file, ['import { readHitlState } from "#harness/hitl/index.js";'], readers);+ assert.equal(readers.length, 0);+ }+ for (const file of [+ "packages/eve/src/harness/session-machine/commit.ts",+ "packages/eve/src/execution/session/checkpoint-migrations.ts",+ ]) {+ const violations = [];+ check(file, ['import * as requests from "#harness/hitl/requests.js";'], violations);+ assert.equal(violations.length, 0);+ }+});