Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): report relayed questions cancelled when the asking work ends (#4083)

Andrew Barba67ae5b596066
diff --git a/.changeset/task-run-end-withdraws-questions.md b/.changeset/task-run-end-withdraws-questions.md
new file mode 100644
index 000000000..dd83d6cb4
--- /dev/null
+++ b/.changeset/task-run-end-withdraws-questions.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+A question or approval that a task run or workflow tool call relays, from its own `ctx.ask()` or from a session it opened with `ctx.agent`, now emits `input.resolved` with `outcome: "cancelled"` when that run finishes before anyone answers. Every question or approval a session relays does the same when the turn is cancelled. Previously these requests were dropped silently or left in place, so channels and `useEveAgent` UIs kept offering them even though no answer could reach anyone.
diff --git a/docs/channels/custom.mdx b/docs/channels/custom.mdx
index 4d90abbd8..38fecf1fb 100644
--- a/docs/channels/custom.mdx
+++ b/docs/channels/custom.mdx
@@ -76,8 +76,12 @@ its event data contains `sessionId` directly.
A channel that renders questions and approvals from `input.requested` can handle
`input.resolved` to learn when each request ends, however it ended: answered from
-the channel, answered by a plain-text reply, or withdrawn. Each resolution carries
-the `requestId` and an `outcome` such as `answered`, `approved`, or `cancelled`.
+the channel, answered by a plain-text reply, or withdrawn. A request that a
+workflow tool run relays, from its own `ctx.ask()` or from a session it opened
+with `ctx.agent`, also resolves as `cancelled` when that run ends before anyone
+answers. Every request relayed from a task, workflow tool call, or subagent does
+the same when the turn is cancelled. Each resolution carries the `requestId` and
+an `outcome` such as `answered`, `approved`, or `cancelled`.
`channel.continuation.token` is always the channel-local address accepted by
`from()`, `resolveSession()`, and `alias()`. Framework namespace prefixes are not
diff --git a/docs/concepts/sessions-runs-and-streaming.md b/docs/concepts/sessions-runs-and-streaming.md
index 146d4d947..461cc1217 100644
--- a/docs/concepts/sessions-runs-and-streaming.md
+++ b/docs/concepts/sessions-runs-and-streaming.md
@@ -123,7 +123,7 @@ Note: consider the privacy, confidentiality, and user-experience implications fo
A delegated subagent publishes progress on its own child-session stream. When a subagent tool call or a workflow tool's `ctx.agent` opens a session, the parent emits `agent.started` with the call's `callId` and `turnId`, its `taskId` when the call runs as a task, the child's `sessionId`, and a `streamPath` that a client follows with `session.agent(started).stream()`. A subagent tool call is a [task](#task-events) whose `task.started` has `kind: "agent"`: its `task.started` and `task.settled` carry the call, and `task.settled.data.output` is the child's reply. A call that fails before the child session opens has no `agent.started`. A settled call does not end the child session; later calls with the same `taskId` reach it.
-A question or sign-in from inside a running call does not end the turn. This covers a workflow tool's `ctx.ask()`, including the built-in `ask_question` tool, and a delegated subagent's question or sign-in. The stream emits `input.requested` or `authorization.required`, then `turn.waiting` with the open turn's `turnId`. After the answer or sign-in, the turn resumes with the next `step.started` for the same `turnId`, and only `turn.completed`, `turn.failed`, or `turn.cancelled` ends it. When you answer a question that belongs to a workflow tool or a subagent, the session you answer on emits `input.resolved` for it as it routes the answer down. A tool approval the turn requests still ends the turn: `input.requested`, `turn.completed`, then `session.waiting`.
+A question or sign-in from inside a running call does not end the turn. This covers a workflow tool's `ctx.ask()`, including the built-in `ask_question` tool, and a delegated subagent's question or sign-in. The stream emits `input.requested` or `authorization.required`, then `turn.waiting` with the open turn's `turnId`. After the answer or sign-in, the turn resumes with the next `step.started` for the same `turnId`, and only `turn.completed`, `turn.failed`, or `turn.cancelled` ends it. When you answer a question that belongs to a workflow tool or a subagent, the session you answer on emits `input.resolved` for it as it routes the answer down. If the workflow tool run that relayed a question or approval ends before anyone answers, that session emits `input.resolved` with `outcome: "cancelled"` for it. This covers the run's own `ctx.ask()` questions and requests from sessions it opened with `ctx.agent`. A cancelled turn does the same for every question or approval the session relays. A tool approval the turn requests still ends the turn: `input.requested`, `turn.completed`, then `session.waiting`.
### Task events
diff --git a/packages/eve/src/execution/publish-session-events.integration.test.ts b/packages/eve/src/execution/publish-session-events.integration.test.ts
index a66625dd6..cfabf409c 100644
--- a/packages/eve/src/execution/publish-session-events.integration.test.ts
+++ b/packages/eve/src/execution/publish-session-events.integration.test.ts
@@ -88,7 +88,8 @@ it("relays a withdrawn workflow question's input.resolved to the stream and its
[
"ask-1",
{
- workflowAsk: { control: "control", question: {}, runId: "run-1" },
+ workflowAsk: { control: "control", question: {} },
+ runId: "run-1",
childContinuationToken: "ask-1",
event: { sequence: 1, stepIndex: 0, turnId: "turn-1" },
kind: "question",
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.ts
new file mode 100644
index 000000000..1b8a4a31d
--- /dev/null
+++ b/packages/eve/src/execution/session-workflow-tool-run.integration.test.ts
@@ -0,0 +1,126 @@
+import { describe, expect, it } from "vitest";
+
+import { handleWorkflowToolRunMessage } from "#execution/session-workflow-tool-run.js";
+import { SessionStateCursor } from "#execution/session/state-cursor.js";
+import { applyTaskRunMessageStep } from "#execution/tasks/steps.js";
+import {
+ createTask,
+ markTaskRunStarted,
+ readTaskTable,
+ recordTaskRun,
+ 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";
+import type { MessageStreamEvent } from "#protocol/message.js";
+import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
+
+const serializedContext = {
+ "eve.auth": null,
+ "eve.bundle": { source: createBundledRuntimeCompiledArtifactsSource() },
+ "eve.channel": { kind: "http", state: {} },
+ "eve.continuationToken": "test-token",
+ "eve.sessionId": "support-session",
+};
+
+describe("handleWorkflowToolRunMessage", () => {
+ it("withdraws a request from a run's agent session once the run ends", async () => {
+ // Alice's reviewer task asks her to approve creating an issue, then its
+ // run fails before she answers, which also ends the reviewer's session.
+ const created = createTask(readTaskTable(undefined), {
+ callId: "reviewer-call",
+ kind: "agent",
+ name: "reviewer",
+ resumable: true,
+ turnId: "turn_1",
+ });
+ const table = markTaskRunStarted(
+ recordTaskRun(created.table, created.taskId, {
+ hookToken: "reviewer-run-control",
+ runId: "reviewer-run",
+ }),
+ created.taskId,
+ "reviewer-run",
+ ).table;
+ const base = createTestSessionState({
+ emissionState: { sequence: 2, sessionStarted: true, stepIndex: 0, turnId: "turn_1" },
+ sessionId: "support-session",
+ });
+ const events: MessageStreamEvent[] = [];
+ const decoder = new TextDecoder();
+ const cursor = new SessionStateCursor({
+ inbox: { claimSessionHooks: async () => {} },
+ serializedContext,
+ sessionState: {
+ ...base,
+ snapshot: { session: writeTaskTable(base.snapshot.session, table) },
+ },
+ sessionWritable: new WritableStream<Uint8Array>({
+ write(chunk) {
+ events.push(JSON.parse(decoder.decode(chunk)) as MessageStreamEvent);
+ },
+ }),
+ });
+ const from: WorkflowToolRunRef = {
+ callId: "reviewer-call",
+ input: { message: "Review the release notes." },
+ runId: "reviewer-run",
+ sequence: 2,
+ stepIndex: 0,
+ taskId: created.taskId,
+ toolName: "reviewer",
+ turnId: "turn_1",
+ };
+
+ const runtime = await createTestRuntime({ agent: { name: "support" } });
+ await runtime.run(async () => {
+ await handleWorkflowToolRunMessage({
+ cursor,
+ message: {
+ from,
+ kind: "request",
+ replyTo: "reviewer-session-token",
+ request: {
+ kind: "input-batch",
+ requests: [
+ {
+ action: {
+ callId: "create-issue-call",
+ input: {},
+ kind: "tool-call",
+ toolName: "create_issue",
+ },
+ kind: "tool-approval",
+ options: [{ id: "approve", label: "Approve" }],
+ prompt: "Approve creating the release issue?",
+ requestId: "approval-1",
+ },
+ ],
+ },
+ requestCoordinates: { sequence: 2, stepIndex: 0, turnId: "turn_1" },
+ },
+ });
+ await cursor.advance((state) =>
+ applyTaskRunMessageStep({
+ ...state,
+ message: {
+ from,
+ kind: "outcome",
+ result: { error: "The reviewer's model call failed.", status: "failed" },
+ },
+ }),
+ );
+ });
+
+ expect(
+ filterEventsByType(events, "input.resolved").map((event) => event.data.resolutions),
+ ).toEqual([[{ kind: "tool-approval", outcome: "cancelled", requestId: "approval-1" }]]);
+ expect(
+ containsEventSequence(events, ["input.requested", "input.resolved", "task.settled"]),
+ ).toBe(true);
+ expect(getProxyInputRequests(cursor.sessionState.snapshot.session.state).size).toBe(0);
+ });
+});
diff --git a/packages/eve/src/execution/session-workflow-tool-run.ts b/packages/eve/src/execution/session-workflow-tool-run.ts
index 80b52e5a3..811758bfd 100644
--- a/packages/eve/src/execution/session-workflow-tool-run.ts
+++ b/packages/eve/src/execution/session-workflow-tool-run.ts
@@ -8,11 +8,13 @@ import type {
WorkflowToolRunAgentStartedMessage,
WorkflowToolRunMessage,
WorkflowToolRunOutcomeMessage,
- WorkflowToolRunRef,
WorkflowToolRunRequestMessage,
WorkflowToolRunWithdrawMessage,
} from "#execution/tools/workflow/messages.js";
-import { withdrawWorkflowToolRunQuestionStep } from "#execution/tools/workflow/withdraw-step.js";
+import {
+ withdrawFinishedRunQuestionsStep,
+ withdrawWorkflowToolRunQuestionStep,
+} from "#execution/tools/workflow/withdraw-step.js";
import type { SessionStateCursor } from "#execution/session/state-cursor.js";
import {
workflowToolRunOutcomeToToolResult,
@@ -82,27 +84,25 @@ export function batchAgentStarts(messages: readonly WorkflowToolRunMessage[]): B
/**
* Settles a workflow tool run outcome against the turn's recorded runs and
* returns the runtime action result the turn should accept, or `undefined`
- * when the outcome does not bind to a run this turn owns.
+ * when the outcome does not bind to a run this turn owns. Requests the run
+ * relayed are withdrawn first, since nobody can answer them anymore.
*/
async function handleWorkflowToolRunOutcome(
input: HandlerInput<WorkflowToolRunOutcomeMessage>,
): Promise<RuntimeActionResult | undefined> {
const { cursor, message } = input;
- const recorded = findBlockingWorkflowToolRun(
- cursor.sessionState.snapshot.session.state,
- message.from.callId,
- message.from.turnId,
- );
+ const state = cursor.sessionState.snapshot.session.state;
+ const recorded = findBlockingWorkflowToolRun(state, message.from.callId, message.from.turnId);
if (recorded?.address.runId !== message.from.runId) return undefined;
const result = workflowToolRunOutcomeToToolResult(message);
+ if (!isInboxToolResultFromRecordedWorkflowToolRun(state, result)) return undefined;
- return isInboxToolResultFromRecordedWorkflowToolRun(
- cursor.sessionState.snapshot.session.state,
- result,
- )
- ? result
- : undefined;
+ if (cursor.sessionState.hasProxyInputRequests) {
+ const { runId } = message.from;
+ await cursor.advance((current) => withdrawFinishedRunQuestionsStep({ ...current, runId }));
+ }
+ return result;
}
async function handleWorkflowToolRunRequest(
@@ -121,9 +121,10 @@ async function handleWorkflowToolRunRequest(
await cursor.advance((state) =>
runProxySubagentEventStep({
...(message.request.kind === "ask" && {
- workflowAsk: createWorkflowAskRoute(message.from, message.request),
+ workflowAsk: createWorkflowAskRoute(message.request),
}),
hookPayload: workflowToolRunRequestToInputRequestPayload(message),
+ runId: message.from.runId,
...state,
}),
);
@@ -148,10 +149,7 @@ async function handleWorkflowToolRunWithdraw(
);
}
-function createWorkflowAskRoute(
- from: WorkflowToolRunRef,
- ask: WorkflowToolAskRequest,
-): WorkflowAskRoute {
+function createWorkflowAskRoute(ask: WorkflowToolAskRequest): WorkflowAskRoute {
const { allowFreeform, options } = ask.request;
return {
control: ask.control,
@@ -159,6 +157,5 @@ function createWorkflowAskRoute(
...(allowFreeform !== undefined && { allowFreeform }),
...(options !== undefined && { options: [...options] }),
},
- runId: from.runId,
};
}
diff --git a/packages/eve/src/execution/session/turn-step.test.ts b/packages/eve/src/execution/session/turn-step.test.ts
index 88f531fd6..2f2aaa435 100644
--- a/packages/eve/src/execution/session/turn-step.test.ts
+++ b/packages/eve/src/execution/session/turn-step.test.ts
@@ -400,7 +400,8 @@ describe("routeProxiedDeliverStep", () => {
[
"ask-1",
{
- workflowAsk: { control: "control", question: { allowFreeform: true }, runId: "run-1" },
+ workflowAsk: { control: "control", question: { allowFreeform: true } },
+ runId: "run-1",
childContinuationToken: "ask-1",
event: REQUEST_EVENT,
kind: "question",
@@ -459,8 +460,8 @@ describe("routeProxiedDeliverStep", () => {
allowFreeform: false,
options: [{ id: "approve", label: "Approve" }],
},
- runId: "run-1",
},
+ runId: "run-1",
childContinuationToken: "ask-1",
event: REQUEST_EVENT,
kind: "question",
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.ts
index 6e717538f..6b19f4794 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
@@ -3,6 +3,13 @@ import { describe, expect, it } from "vitest";
import type { 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 { filterEventsByType } from "#internal/testing/events.js";
+import type { MessageStreamEvent } from "#protocol/message.js";
import {
accumulateTurnUsage,
getTurnUsageState,
@@ -22,17 +29,25 @@ const serializedContext = {
"eve.sessionId": "test-session",
};
-/** Runs the step in a real runtime, so it publishes through the session's real publication path. */
+/**
+ * Runs the step in a real runtime, so it publishes through the session's real
+ * publication path. Returns the step's result and the events it wrote.
+ */
async function settleCancelledTurn(
input: Omit<Parameters<typeof settleCancelledTurnStep>[0], "sessionWritable">,
) {
+ const events: MessageStreamEvent[] = [];
+ const decoder = new TextDecoder();
+ const sessionWritable = new WritableStream<Uint8Array>({
+ write(chunk) {
+ events.push(JSON.parse(decoder.decode(chunk)) as MessageStreamEvent);
+ },
+ });
const runtime = await createTestRuntime({ agent: { name: "settle-cancelled-turn" } });
- return await runtime.run(() =>
- runSessionStateStep(
- { ...input, sessionWritable: new WritableStream<Uint8Array>() },
- settleCancelledTurnStep,
- ),
+ const result = await runtime.run(() =>
+ runSessionStateStep({ ...input, sessionWritable }, settleCancelledTurnStep),
);
+ return { ...result, events };
}
function spend<T extends { readonly state?: SessionStateMap }>(
@@ -79,4 +94,63 @@ describe("settleCancelledTurnStep", () => {
);
},
);
+
+ it("withdraws every request the session relays before it reports the turn cancelled", async () => {
+ const base = createTestSessionState({
+ emissionState: { sequence: 3, sessionStarted: true, stepIndex: 1, turnId: "turn_1" },
+ sessionId: "support-session",
+ });
+ // Alice's turn relays a question from Bob's deploy task and an approval
+ // from the reviewer subagent when she cancels it.
+ const state = relay(
+ relay(base.snapshot.session.state, "deploy-run-ask-1", {
+ kind: "question",
+ runId: "deploy-run",
+ workflowAsk: { control: "deploy-run-control", question: {} },
+ }),
+ "reviewer-approval-1",
+ { kind: "tool-approval" },
+ );
+
+ const result = await settleCancelledTurn({
+ reportUsage: false,
+ serializedContext,
+ sessionState: { ...base, snapshot: { session: { ...base.snapshot.session, state } } },
+ });
+
+ expect(result.events.map((event) => event.type)).toEqual([
+ "input.resolved",
+ "input.resolved",
+ "turn.cancelled",
+ "session.waiting",
+ ]);
+ expect(
+ filterEventsByType(result.events, "input.resolved").map((event) => event.data.resolutions),
+ ).toEqual([
+ [{ 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);
+ });
});
+
+function relay(
+ state: SessionStateMap | undefined,
+ requestId: string,
+ route: Pick<ProxyInputRequest, "kind" | "runId" | "workflowAsk">,
+): SessionStateMap | undefined {
+ return upsertProxyInputRequestState({
+ entries: [
+ [
+ requestId,
+ {
+ ...route,
+ childContinuationToken: requestId,
+ event: { sequence: 2, stepIndex: 0, turnId: "turn_1" },
+ },
+ ],
+ ],
+ forChildContinuationToken: requestId,
+ state,
+ });
+}
diff --git a/packages/eve/src/execution/settle-cancelled-turn-step.ts b/packages/eve/src/execution/settle-cancelled-turn-step.ts
index 3268e65e5..354b9d631 100644
--- a/packages/eve/src/execution/settle-cancelled-turn-step.ts
+++ b/packages/eve/src/execution/settle-cancelled-turn-step.ts
@@ -8,10 +8,10 @@ import {
withSessionStateDelta,
type WithSessionStateDelta,
} from "#execution/session/state-delta.js";
+import { relayWithdrawnRequests } from "#execution/tools/workflow/withdraw-step.js";
import { emitCancelledTurn } from "#harness/cancelled-turn-emission.js";
import { clearPendingSessionLimitPrompt } from "#harness/input-requests.js";
import { getHarnessEmissionState, setHarnessEmissionState } from "#harness/emission.js";
-import { clearAllProxyInputRequests } from "#harness/proxy-input-requests.js";
import { removeBlockingWorkflowToolRuns } from "#harness/workflow-tool-runs.js";
import { getTurnUsageState, takeSessionUsageDelta } from "#harness/turn-tag-state.js";
import type { TokenUsage } from "#shared/token-usage.js";
@@ -35,10 +35,11 @@ interface CancelledTurnSettleInput {
}
/**
- * Settles one cancelled turn: emits `turn.cancelled` → `session.waiting`,
- * drops pending coordination state, and persists the between-turns
- * session. Runs in the owner, whose wake sources exclude the
- * cancel hook, so a queued cancel wake cannot re-dispatch it.
+ * Settles one cancelled turn: relays `input.resolved` for every request the
+ * session proxies, emits `turn.cancelled` → `session.waiting`, drops pending
+ * coordination state, and persists the between-turns session. Runs in the
+ * owner, whose wake sources exclude the cancel hook, so a queued cancel wake
+ * cannot re-dispatch it.
*/
export async function settleCancelledTurnStep(
input: CancelledTurnSettleInput,
@@ -51,7 +52,9 @@ export async function settleCancelledTurnStep(
export async function settleCancelledTurn(
input: CancelledTurnSettleInput,
): Promise<CancelledTurnSettleResult> {
- const step = await restoreSessionStep(input);
+ // The cancel stopped every descendant and task, so nobody can answer a request the session relays.
+ const relayed = await relayWithdrawnRequests(input, () => true);
+ const step = await restoreSessionStep({ ...relayed, sessionWritable: input.sessionWritable });
const durableState = step.durableSession.state;
const { published, result: usage } = await publishFromSessionStep(step, {
origin: "own",
@@ -68,10 +71,8 @@ export async function settleCancelledTurn(
input.sessionState.emissionState.turnId;
const cancelledSession = setHarnessEmissionState(
clearPendingSessionLimitPrompt(
- clearAllProxyInputRequests(
- commitCancelledCoordinationBatch(
- removeBlockingWorkflowToolRuns({ ...session, outputSchema: undefined }, owningTurnId),
- ),
+ commitCancelledCoordinationBatch(
+ removeBlockingWorkflowToolRuns({ ...session, outputSchema: undefined }, owningTurnId),
),
),
emissionState,
diff --git a/packages/eve/src/execution/tasks/session.test.ts b/packages/eve/src/execution/tasks/session.test.ts
index 7d27f668d..4fe3456d5 100644
--- a/packages/eve/src/execution/tasks/session.test.ts
+++ b/packages/eve/src/execution/tasks/session.test.ts
@@ -4,6 +4,7 @@ import type { DurableSession } from "#execution/durable-session-store.js";
import type { SessionInbox } from "#execution/session-inbox/inbox.js";
import { SessionStateCursor } from "#execution/session/state-cursor.js";
import { answerTaskCancel } from "#execution/tasks/session.js";
+import { applyTaskRunMessageStep } from "#execution/tasks/steps.js";
import {
createTask,
markTaskRunStarted,
@@ -18,18 +19,25 @@ import {
} from "#harness/proxy-input-requests.js";
import { createTestSessionState } from "#internal/testing/session-state.js";
-// No workflow runtime runs here: the run's cancel hook is a stub, and the stream is recorded.
+// No workflow runtime runs here: the run's cancel hook is a stub, and the
+// stream is recorded with each event's origin, since relayed input must not
+// 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 publish = async (
- target: { readonly serializedContext: Record<string, unknown>; readonly sessionState: unknown },
- events: readonly unknown[],
- ) => {
- published.push(...events);
- return { serializedContext: target.serializedContext, sessionState: target.sessionState };
- };
- return { publishSessionEvents: publish, relaySessionEvents: publish };
+ const publisher =
+ (origin: "own" | "relayed") =>
+ async (
+ target: {
+ readonly serializedContext: Record<string, unknown>;
+ readonly sessionState: unknown;
+ },
+ events: readonly unknown[],
+ ) => {
+ published.push(...events.map((event) => ({ event, origin })));
+ return { serializedContext: target.serializedContext, sessionState: target.sessionState };
+ };
+ return { publishSessionEvents: publisher("own"), relaySessionEvents: publisher("relayed") };
});
const REQUEST_EVENT = { sequence: 3, stepIndex: 1, turnId: "turn_1" };
@@ -48,15 +56,7 @@ describe("answerTaskCancel", () => {
);
session = withQuestion(session, "research-run");
session = withQuestion(session, "summarize-run");
- const cursor = new SessionStateCursor({
- inbox: { claimSessionHooks: vi.fn() } as Partial<SessionInbox> as SessionInbox,
- serializedContext: {},
- sessionState: {
- ...createTestSessionState({ sessionId: "session-1" }),
- snapshot: { session },
- },
- sessionWritable: new WritableStream<Uint8Array>(),
- });
+ const cursor = cursorFor(session);
await answerTaskCancel(cursor, {
callId: "cancel-call",
@@ -68,29 +68,113 @@ describe("answerTaskCancel", () => {
expect([...getProxyInputRequests(committed.state).keys()]).toEqual(["summarize-run-ask-1"]);
expect(published).toEqual([
{
- data: {
- ...REQUEST_EVENT,
- resolutions: [
- { kind: "question", outcome: "cancelled", requestId: "research-run-ask-1" },
- ],
+ event: {
+ data: {
+ ...REQUEST_EVENT,
+ resolutions: [
+ { kind: "question", outcome: "cancelled", requestId: "research-run-ask-1" },
+ ],
+ },
+ type: "input.resolved",
+ },
+ origin: "relayed",
+ },
+ {
+ event: {
+ data: {
+ callId: "research-call",
+ kind: "tool",
+ name: "research",
+ status: "cancelled",
+ taskId: research.taskId,
+ turnId: "turn_1",
+ },
+ type: "task.settled",
+ },
+ origin: "own",
+ },
+ ]);
+ });
+});
+
+describe("applyTaskRunMessageStep", () => {
+ it("withdraws the questions of a task() run that fails on its own, and only those", async () => {
+ const research = startedTask(readTaskTable(undefined), "research");
+ const summarize = startedTask(research.table, "summarize");
+ let session: DurableSession = writeTaskTable(
+ createTestSessionState({ sessionId: "session-1" }).snapshot.session,
+ summarize.table,
+ );
+ session = withQuestion(session, "research-run");
+ session = withQuestion(session, "summarize-run");
+ const cursor = cursorFor(session);
+
+ await cursor.advance((state) =>
+ applyTaskRunMessageStep({
+ ...state,
+ message: {
+ from: {
+ callId: "research-call",
+ input: {},
+ runId: "research-run",
+ sequence: 3,
+ stepIndex: 1,
+ taskId: research.taskId,
+ toolName: "research",
+ turnId: "turn_1",
+ },
+ kind: "outcome",
+ result: { error: "The research service is unavailable.", status: "failed" },
+ },
+ }),
+ );
+
+ const committed = cursor.sessionState.snapshot.session;
+ expect([...getProxyInputRequests(committed.state).keys()]).toEqual(["summarize-run-ask-1"]);
+ expect(published).toEqual([
+ {
+ event: {
+ data: {
+ ...REQUEST_EVENT,
+ resolutions: [
+ { kind: "question", outcome: "cancelled", requestId: "research-run-ask-1" },
+ ],
+ },
+ type: "input.resolved",
},
- type: "input.resolved",
+ origin: "relayed",
},
{
- data: {
- callId: "research-call",
- kind: "tool",
- name: "research",
- status: "cancelled",
- taskId: research.taskId,
- turnId: "turn_1",
+ event: {
+ data: {
+ callId: "research-call",
+ error: { message: "The research service is unavailable." },
+ kind: "tool",
+ name: "research",
+ status: "failed",
+ taskId: research.taskId,
+ turnId: "turn_1",
+ },
+ type: "task.settled",
},
- type: "task.settled",
+ origin: "own",
},
]);
});
});
+function cursorFor(session: DurableSession): SessionStateCursor {
+ return new SessionStateCursor({
+ inbox: { claimSessionHooks: vi.fn() } as Partial<SessionInbox> as SessionInbox,
+ serializedContext: {},
+ sessionState: {
+ ...createTestSessionState({ sessionId: "session-1" }),
+ snapshot: { session },
+ },
+ sessionWritable: new WritableStream<Uint8Array>(),
+ });
+}
+
/** A working `task()` task whose run has started. */
function startedTask(
table: TaskTable,
@@ -124,7 +208,8 @@ function withQuestion(session: DurableSession, runId: string): DurableSession {
childContinuationToken: requestId,
event: REQUEST_EVENT,
kind: "question",
- workflowAsk: { control: `${runId}-control`, question: {}, runId },
+ runId,
+ workflowAsk: { control: `${runId}-control`, question: {} },
},
],
],
diff --git a/packages/eve/src/execution/tasks/steps.ts b/packages/eve/src/execution/tasks/steps.ts
index 617c1743b..f5bc5c033 100644
--- a/packages/eve/src/execution/tasks/steps.ts
+++ b/packages/eve/src/execution/tasks/steps.ts
@@ -39,10 +39,13 @@ import type {
WorkflowToolRunOutcomeMessage,
} from "#execution/tools/workflow/messages.js";
import { workflowToolRunFailureOutput } from "#execution/tools/workflow/owner-inbox.js";
-import { withdrawWorkflowAsks } from "#execution/tools/workflow/withdraw-step.js";
-import { clearProxyInputRequestsWhere } from "#harness/proxy-input-requests.js";
+import { withdrawProxyInputRequests } from "#harness/proxy-input-requests.js";
import { resumeHook } from "#internal/workflow/runtime.js";
-import { createTaskSettledEvent, type TaskSettledStreamEvent } from "#protocol/message.js";
+import {
+ createTaskSettledEvent,
+ type TaskSettledStreamEvent,
+ type UnstampedMessageStreamEvent,
+} from "#protocol/message.js";
/** The messages a task's run sends that change its record. */
export type TaskRunMessage = Extract<
@@ -71,6 +74,7 @@ async function applyTaskRunMessage(
}
let table = readTaskTable(session.state);
const events: TaskSettledStreamEvent[] = [];
+ let withdrawn: readonly UnstampedMessageStreamEvent[] = [];
switch (message.kind) {
case "started": {
const started = markTaskRunStarted(table, taskId, message.from.runId);
@@ -97,22 +101,27 @@ async function applyTaskRunMessage(
const settled = settleRemainingTaskCalls(table, taskId, outcome);
events.push(...taskSettledEvents(record, settled.settled, outcome));
table = finishTaskRun(settled.table, taskId, message.from.runId);
- session = forgetRunQuestions(session, message.from.runId);
+ // Nobody can answer what a finished run relayed, so channels must stop offering it.
+ ({ events: withdrawn, session } = withdrawProxyInputRequests(
+ session,
+ (_requestId, route) => route.runId === message.from.runId,
+ ));
break;
}
}
- return await publishSessionEvents(
+ const relayed = await relaySessionEvents(
{ ...input, sessionState: saveTable(input.sessionState, session, table) },
- events,
+ withdrawn,
);
+ return await publishSessionEvents({ ...input, ...relayed }, events);
}
/**
* Cancels tasks: their calls settle as cancelled and their runs are told to
* stop. A run ends itself within its cleanup deadline and reports cancelled.
- * A `task()` run's cancel settles its questions, so the session withdraws
- * them in the same step and accepts no answer after it. A `serve()` run
- * withdraws its stretch's questions itself, and the session decides each one.
+ * A `task()` run's cancel settles every request it relayed, so the session
+ * withdraws them in the same step and accepts no answer after it. A `serve()`
+ * run withdraws its stretch's questions itself, and the session decides each one.
*/
export async function cancelTasksStep(
input: SessionStepState & { readonly taskIds: readonly string[] },
@@ -137,7 +146,10 @@ async function cancelTasks(
if (record?.resumable === false) stoppedRunIds.add(cancelled.send.run.runId);
await sendTaskRunCommands(cancelled.send);
}
- const withdrawn = withdrawWorkflowAsks(session, (_requestId, runId) => stoppedRunIds.has(runId));
+ const withdrawn = withdrawProxyInputRequests(
+ session,
+ (_requestId, route) => route.runId !== undefined && stoppedRunIds.has(route.runId),
+ );
const relayed = await relaySessionEvents(
{ ...input, sessionState: saveTable(input.sessionState, withdrawn.session, table) },
withdrawn.events,
@@ -241,11 +253,6 @@ function countTaskRunUsage(
};
}
-/** A finished run can no longer take answers, so its unanswered questions are dropped. */
-function forgetRunQuestions(session: DurableSession, runId: string): DurableSession {
- return clearProxyInputRequestsWhere(session, (route) => route.workflowAsk?.runId === runId);
-}
-
function saveTable(
state: DurableSessionState,
session: DurableSession,
diff --git a/packages/eve/src/execution/tools/workflow/ask.ts b/packages/eve/src/execution/tools/workflow/ask.ts
index 8ab4b4b9d..f71080d72 100644
--- a/packages/eve/src/execution/tools/workflow/ask.ts
+++ b/packages/eve/src/execution/tools/workflow/ask.ts
@@ -139,7 +139,7 @@ export class WorkflowToolRunAsks {
/**
* Waits until every withdrawal asked for has reached the run's inbox, so the
- * run's outcome, which drops its questions silently, cannot overtake one.
+ * session decides each one before the run's outcome withdraws the rest.
*/
async flush(): Promise<void> {
while (this.withdrawing.size > 0) await Promise.all(this.withdrawing);
diff --git a/packages/eve/src/execution/tools/workflow/withdraw-step.ts b/packages/eve/src/execution/tools/workflow/withdraw-step.ts
index 971f812b6..cdb44bf99 100644
--- a/packages/eve/src/execution/tools/workflow/withdraw-step.ts
+++ b/packages/eve/src/execution/tools/workflow/withdraw-step.ts
@@ -1,7 +1,6 @@
import {
readDurableSession,
replaceDurableSessionSnapshot,
- type DurableSession,
} from "#execution/durable-session-store.js";
import {
relaySessionEvents,
@@ -15,15 +14,18 @@ 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, retireProxyInputRequests } from "#harness/proxy-input-requests.js";
-import { createInputResolvedEvent, type UnstampedMessageStreamEvent } from "#protocol/message.js";
+import {
+ withdrawProxyInputRequests,
+ type ProxyInputRequest,
+} from "#harness/proxy-input-requests.js";
/**
* Decides a run's request to withdraw a question. A question the session
* still offers is retired and relayed `cancelled`, so channels stop offering
- * it. One it no longer offers was already answered or dropped with its turn.
- * Either way the run hears `withdrawn`, after any answer the session sent it
- * first, so the question resolves from the session's first decision.
+ * it. One it no longer offers was already answered or withdrawn when its turn
+ * was cancelled. Either way the run hears `withdrawn`, after any answer the
+ * session sent it first, so the question resolves from the session's first
+ * decision.
*/
export async function withdrawWorkflowToolRunQuestionStep(
input: WithdrawQuestionInput,
@@ -41,16 +43,43 @@ type WithdrawQuestionInput = SessionStepState & {
async function withdrawWorkflowToolRunQuestion(
input: WithdrawQuestionInput,
): Promise<PublishedSessionEvents> {
- const session = readDurableSession(input.sessionState);
- const withdrawn = withdrawWorkflowAsks(
- session,
- (requestId, runId) => requestId === input.requestId && runId === input.runId,
- );
const decision: WorkflowToolRunControlMessage = {
kind: "withdrawn",
requestId: input.requestId,
};
await ignoreGoneTarget(resumeHook(input.control, decision));
+ return await relayWithdrawnRequests(
+ input,
+ (requestId, route) =>
+ requestId === input.requestId &&
+ route.workflowAsk !== undefined &&
+ route.runId === input.runId,
+ );
+}
+
+/**
+ * Withdraws the requests a finished run left open: its own questions and those
+ * of the sessions it opened, which ended with it. Nobody can answer them now,
+ * so each is relayed `cancelled`.
+ */
+export async function withdrawFinishedRunQuestionsStep(
+ input: SessionStepState & { readonly runId: string },
+): Promise<SessionStateTransition> {
+ "use step";
+ return await withSessionStateDelta(input, (target) =>
+ relayWithdrawnRequests(target, (_requestId, route) => route.runId === target.runId),
+ );
+}
+
+/**
+ * Retires the relayed requests `select` picks and relays the `input.resolved`
+ * that reports each one `cancelled`, for a step that owns the session.
+ */
+export async function relayWithdrawnRequests(
+ input: SessionStepState,
+ select: (requestId: string, route: ProxyInputRequest) => boolean,
+): Promise<PublishedSessionEvents> {
+ const withdrawn = withdrawProxyInputRequests(readDurableSession(input.sessionState), select);
return await relaySessionEvents(
{
serializedContext: input.serializedContext,
@@ -63,26 +92,3 @@ async function withdrawWorkflowToolRunQuestion(
withdrawn.events,
);
}
-
-/**
- * Retires the `ctx.ask()` questions `select` picks and returns the
- * `input.resolved` events that report them `cancelled`.
- */
-export function withdrawWorkflowAsks(
- session: DurableSession,
- select: (requestId: string, runId: string) => boolean,
-): { readonly events: readonly UnstampedMessageStreamEvent[]; readonly session: DurableSession } {
- const requestIds: string[] = [];
- const events: UnstampedMessageStreamEvent[] = [];
- for (const [requestId, route] of getProxyInputRequests(session.state)) {
- if (route.workflowAsk === undefined || !select(requestId, route.workflowAsk.runId)) continue;
- requestIds.push(requestId);
- events.push(
- createInputResolvedEvent({
- resolutions: [{ kind: "question", outcome: "cancelled", requestId }],
- ...route.event,
- }),
- );
- }
- return { events, session: retireProxyInputRequests(session, requestIds) };
-}
diff --git a/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts b/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts
index c1d70115c..e5153df88 100644
--- a/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts
+++ b/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { start } from "#internal/workflow/runtime.js";
import {
captureTurnEvents,
+ containsEventSequence,
filterEventsByType,
readFirstTurnReply,
} from "#internal/testing/events.js";
@@ -20,7 +21,7 @@ import {
stepReferenceWorkflow,
workflowContextMisuseWorkflow,
} from "#internal/testing/workflow-tool-fixtures.js";
-import type { InputRequestedStreamEvent } from "#protocol/message.js";
+import type { InputRequestedStreamEvent, MessageStreamEvent } from "#protocol/message.js";
import {
buildWorkflowToolSerializedContext,
createWorkflowToolRuntime,
@@ -316,7 +317,7 @@ describe("workflow tools", () => {
});
}, 60_000);
- it("lets a deadline win a race against an unanswered ask", async () => {
+ it("lets a deadline win a race against an unanswered ask and withdraws the ask", async () => {
const runtime = await createWorkflowToolRuntime({
agentName: "workflow-tool-ask-deadline",
execute: askThenRaceWorkflow,
@@ -339,12 +340,16 @@ describe("workflow tools", () => {
try {
// Asking parks the turn; the sleep then wins and the same turn resumes.
const asked = await stream.nextTurn();
- expect(filterEventsByType(asked, "input.requested")).toHaveLength(1);
+ const requested = filterEventsByType(asked, "input.requested");
+ expect(requested).toHaveLength(1);
+ const requestId = requested[0]!.data.requests[0]!.requestId;
const outputs: string[] = [];
+ const resumedEvents: MessageStreamEvent[] = [];
// A replayed parked boundary may arrive before the deadline result.
for (let attempt = 0; attempt < 5 && outputs.length === 0; attempt += 1) {
const resumed = await stream.nextTurn();
+ resumedEvents.push(...resumed);
expect(filterEventsByType(resumed, "turn.failed")).toHaveLength(0);
expect(filterEventsByType(resumed, "session.failed")).toHaveLength(0);
outputs.push(
@@ -354,6 +359,15 @@ describe("workflow tools", () => {
);
}
expect(outputs.some((output) => output.includes('"decided":"timed out"'))).toBe(true);
+ // The run returned without the answer, so channels must stop offering its question.
+ expect(
+ filterEventsByType(resumedEvents, "input.resolved").map(
+ (event) => event.data.resolutions,
+ ),
+ ).toEqual([[{ kind: "question", outcome: "cancelled", requestId }]]);
+ expect(containsEventSequence(resumedEvents, ["input.resolved", "action.result"])).toBe(
+ true,
+ );
} finally {
stream.dispose();
await run.cancel();
diff --git a/packages/eve/src/harness/coordination.test.ts b/packages/eve/src/harness/coordination.test.ts
index 0a8f5f8c0..399052351 100644
--- a/packages/eve/src/harness/coordination.test.ts
+++ b/packages/eve/src/harness/coordination.test.ts
@@ -7,7 +7,6 @@ import {
resolveToolCallInputObject,
setPendingCoordinationBatch,
} from "#harness/coordination.js";
-import { getProxyInputRequests, upsertProxyInputRequests } from "#harness/proxy-input-requests.js";
import {
getBlockingWorkflowToolRuns,
registerWorkflowToolRun,
@@ -18,10 +17,6 @@ import { setTurnUsageState } from "#harness/turn-tag-state.js";
import type { HarnessSession } from "#harness/types.js";
import { isRuntimeWorkflowToolAction } from "#shared/action-types.js";
-const REQUEST_EVENT = { sequence: 0, stepIndex: 0, turnId: "turn_0" };
-
-const CHILD_CONTINUATION_TOKEN = "subagent:private-token";
-
describe("createRuntimeActionRequestFromToolCall", () => {
const loadSkillCall = {
input: { skill: "research" },
@@ -306,7 +301,7 @@ describe("coordination batch identity", () => {
});
describe("resolvePendingCoordination", () => {
- it("forgets a finished workflow tool run and withdraws only its unanswered requests", async () => {
+ it("forgets a finished workflow tool run", async () => {
const parked = setPendingCoordinationBatch({
event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
responseMessages: [],
@@ -322,41 +317,12 @@ describe("resolvePendingCoordination", () => {
},
],
});
- const withRun = registerWorkflowToolRun(parked, {
+ const session = registerWorkflowToolRun(parked, {
callId: "call-1",
toolName: "deploy",
origin: { turnId: "turn_0", stepIndex: 0 },
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({
- entries: [
- [
- answerToken,
- {
- workflowAsk: { control: "control", question: {}, runId: "run-1" },
- childContinuationToken: answerToken,
- event: REQUEST_EVENT,
- kind: "question",
- },
- ],
- ],
- forChildContinuationToken: answerToken,
- session: withRun,
- }),
- });
const resolved = await resolvePendingCoordination({
session,
@@ -369,7 +335,6 @@ describe("resolvePendingCoordination", () => {
expect(resolved.outcome).toBe("resolved");
expect(getBlockingWorkflowToolRuns(resolved.session.state)).toEqual([]);
- expect([...getProxyInputRequests(resolved.session.state).keys()]).toEqual(["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.ts
index 99781dfe7..9191ac512 100644
--- a/packages/eve/src/harness/coordination.ts
+++ b/packages/eve/src/harness/coordination.ts
@@ -10,7 +10,6 @@ import type {
} from "#shared/action-types.js";
import { markRuntimeWorkflowToolAction } from "#shared/action-types.js";
import { parseJsonObject, type JsonObject } from "#shared/json.js";
-import { clearProxyInputRequestsWhere } from "#harness/proxy-input-requests.js";
import {
findBlockingWorkflowToolRun,
removeBlockingWorkflowToolRuns,
@@ -254,7 +253,7 @@ export async function resolvePendingCoordination(input: {
}
let nextSession: HarnessSession = input.session;
- // Drop a finished run's unanswered requests so a late click cannot reach it.
+ // The session withdrew each finished run's open questions when its outcome arrived.
for (const result of readyResults) {
if (result.kind !== "tool-result") continue;
const record = findBlockingWorkflowToolRun(
@@ -263,14 +262,7 @@ export async function resolvePendingCoordination(input: {
batch.event.turnId,
);
if (record === undefined) continue;
- nextSession = removeBlockingWorkflowToolRuns(
- clearProxyInputRequestsWhere(
- nextSession,
- (route) => route.workflowAsk?.runId === record.address.runId,
- ),
- batch.event.turnId,
- record.callId,
- );
+ nextSession = removeBlockingWorkflowToolRuns(nextSession, batch.event.turnId, record.callId);
}
const state = { ...nextSession.state };
diff --git a/packages/eve/src/harness/proxy-input-requests.ts b/packages/eve/src/harness/proxy-input-requests.ts
index 91aad3255..0990cbef3 100644
--- a/packages/eve/src/harness/proxy-input-requests.ts
+++ b/packages/eve/src/harness/proxy-input-requests.ts
@@ -7,6 +7,7 @@ import {
type SessionInboxAddress,
} from "#execution/session-inbox/address.js";
import type { RemoteAgentBinding } from "#eve-channel/support.js";
+import { createInputResolvedEvent, type InputResolvedStreamEvent } from "#protocol/message.js";
const PROXY_INPUT_REQUESTS_KEY = "eve.runtime.proxyInputRequests";
@@ -25,7 +26,6 @@ export interface WorkflowAskRoute {
readonly control: string;
/** What a plain-text message may answer. */
readonly question: ProxyInputQuestion;
- readonly runId: string;
}
/** The parts of a `ctx.ask()` request a plain-text message is resolved against. */
@@ -39,6 +39,12 @@ export interface ProxyInputRequest {
readonly remote?: RemoteAgentBinding & { readonly sessionId: string };
readonly inputSource?: string;
readonly workflowAsk?: WorkflowAskRoute;
+ /**
+ * The workflow tool run that relayed the request: its own `ctx.ask()`
+ * question, or a request from a session it opened with `ctx.agent`. Nobody
+ * can answer the request once that run ends.
+ */
+ readonly runId?: string;
/** Batch semantics are optional so sessions written before this field remain routable. */
readonly batch?: ProxyInputRequestBatch;
readonly childContinuationToken: string;
@@ -136,24 +142,28 @@ export function upsertProxyInputRequestState(input: {
return Object.keys(state).length > 0 ? state : undefined;
}
-/** Removes every proxy route the predicate selects. */
-export function clearProxyInputRequestsWhere<T extends { readonly state?: SessionStateMap }>(
+/**
+ * Retires the requests `select` picks, which nobody can answer anymore, and
+ * returns the `input.resolved` events that report them `cancelled` so
+ * channels stop offering them. Publish the events as relayed.
+ */
+export function withdrawProxyInputRequests<T extends { readonly state?: SessionStateMap }>(
session: T,
- select: (route: ProxyInputRequest) => boolean,
-): T {
- const current = readMap(session.state);
- const next: Record<string, ProxyInputRequest> = {};
- let changed = false;
-
- for (const [requestId, route] of Object.entries(current)) {
- if (select(route)) {
- changed = true;
- continue;
- }
- next[requestId] = route;
+ select: (requestId: string, route: ProxyInputRequest) => boolean,
+): { readonly events: readonly InputResolvedStreamEvent[]; readonly session: T } {
+ const requestIds: string[] = [];
+ const events: InputResolvedStreamEvent[] = [];
+ for (const [requestId, route] of Object.entries(readMap(session.state))) {
+ if (!select(requestId, route)) continue;
+ requestIds.push(requestId);
+ events.push(
+ createInputResolvedEvent({
+ resolutions: [{ kind: route.kind, outcome: "cancelled", requestId }],
+ ...route.event,
+ }),
+ );
}
-
- return changed ? writeMap(session, next) : session;
+ return { events, session: retireProxyInputRequests(session, requestIds) };
}
/** Removes only the request IDs whose responses were successfully forwarded. */
@@ -175,17 +185,6 @@ export function retireProxyInputRequests<T extends { readonly state?: SessionSta
return changed ? writeMap(session, next) : session;
}
-/**
- * Removes every proxy entry. Called when a cancelled turn orphans its
- * descendants so stale HITL responses no longer route to them.
- */
-export function clearAllProxyInputRequests(session: HarnessSession): HarnessSession {
- if (!hasProxyInputRequests(session.state)) {
- return session;
- }
- return writeMap(session, {});
-}
-
/**
* Projects a {@link SubagentInputRequestHookPayload} into the
* `(requestId, route)` tuples the session stores.
@@ -290,6 +289,8 @@ function parseProxyInputRequest(value: unknown, requestId: string): ProxyInputRe
const batch = "batch" in value ? parseProxyInputRequestBatch(value.batch) : undefined;
const workflowAsk = "workflowAsk" in value ? parseWorkflowAskRoute(value.workflowAsk) : undefined;
if ("workflowAsk" in value && workflowAsk === undefined) return undefined;
+ const runId = "runId" in value ? value.runId : undefined;
+ if (runId !== undefined && (typeof runId !== "string" || runId.length === 0)) return undefined;
const question = "question" in value ? parseProxyInputQuestion(value.question) : undefined;
if ("question" in value && question === undefined) return undefined;
const childSessionInbox = "childSessionInbox" in value ? value.childSessionInbox : undefined;
@@ -297,6 +298,7 @@ function parseProxyInputRequest(value: unknown, requestId: string): ProxyInputRe
return undefined;
const request: {
workflowAsk?: WorkflowAskRoute;
+ runId?: string;
batch?: ProxyInputRequestBatch;
readonly childContinuationToken: string;
inputSource?: string;
@@ -313,6 +315,7 @@ function parseProxyInputRequest(value: unknown, requestId: string): ProxyInputRe
if (typeof inputSource === "string") request.inputSource = inputSource;
if (remote !== undefined) request.remote = remote;
if (workflowAsk !== undefined) request.workflowAsk = workflowAsk;
+ if (typeof runId === "string") request.runId = runId;
if (childSessionInbox !== undefined) request.childSessionInbox = childSessionInbox;
if (batch !== undefined && batch.requestIds.includes(requestId)) request.batch = batch;
if (question !== undefined) request.question = question;
@@ -332,12 +335,10 @@ function parseInputRequestEvent(value: unknown): PendingInputBatchEvent | undefi
function parseWorkflowAskRoute(value: unknown): WorkflowAskRoute | undefined {
if (value === null || typeof value !== "object") return undefined;
const control = Reflect.get(value, "control");
- const runId = Reflect.get(value, "runId");
if (typeof control !== "string" || control.length === 0) return undefined;
- if (typeof runId !== "string" || runId.length === 0) return undefined;
const question = parseProxyInputQuestion(Reflect.get(value, "question"));
if (question === undefined) return undefined;
- return { control, question, runId };
+ return { control, question };
}
function parseRemoteAgentBinding(
diff --git a/packages/eve/src/subagents/event-proxy-step.ts b/packages/eve/src/subagents/event-proxy-step.ts
index e49a541a1..72e6e9315 100644
--- a/packages/eve/src/subagents/event-proxy-step.ts
+++ b/packages/eve/src/subagents/event-proxy-step.ts
@@ -25,6 +25,7 @@ type SubagentEventHookPayload =
export async function runProxySubagentEventStep(
input: SessionStepState & {
readonly workflowAsk?: WorkflowAskRoute;
+ readonly runId?: string;
readonly hookPayload: SubagentEventHookPayload;
},
): Promise<SessionStateTransition> {
@@ -34,19 +35,25 @@ export async function runProxySubagentEventStep(
emitProxiedSubagentEvent({
...(await restoreSessionStep(target)),
workflowAsk: target.workflowAsk,
+ runId: target.runId,
hookPayload: target.hookPayload,
}),
);
}
-/** Relays one child event through the parent session's channel. */
+/**
+ * Relays one child event through the parent session's channel. `runId` names
+ * the workflow tool run that relayed an input request, so the session can
+ * withdraw it when that run ends.
+ */
export async function emitProxiedSubagentEvent(
input: RestoredSessionStep & {
readonly workflowAsk?: WorkflowAskRoute;
+ readonly runId?: string;
readonly hookPayload: SubagentEventHookPayload;
},
): Promise<PublishedSessionEvents> {
- const { hookPayload, workflowAsk } = input;
+ const { hookPayload, runId, workflowAsk } = input;
const { published } = await publishFromSessionStep(input, {
origin: "relayed",
inputSource:
@@ -66,10 +73,14 @@ export async function emitProxiedSubagentEvent(
}
return {
session: upsertProxyInputRequests({
- entries:
- workflowAsk === undefined
- ? entries
- : entries.map(([requestId, route]) => [requestId, { ...route, workflowAsk }]),
+ entries: entries.map(([requestId, route]) => [
+ requestId,
+ {
+ ...route,
+ ...(workflowAsk !== undefined && { workflowAsk }),
+ ...(runId !== undefined && { runId }),
+ },
+ ]),
forChildContinuationToken: hookPayload.childContinuationToken,
inputSource: hookPayload.inputSource,
session,
diff --git a/packages/eve/src/subagents/hitl-proxy.test.ts b/packages/eve/src/subagents/hitl-proxy.test.ts
index c63deb6f0..9e5ede361 100644
--- a/packages/eve/src/subagents/hitl-proxy.test.ts
+++ b/packages/eve/src/subagents/hitl-proxy.test.ts
@@ -274,9 +274,9 @@ describe("routeDeliverPayload message resolution", () => {
{ id: "2", label: "Production" },
],
},
- runId: `run-${requestId}`,
control: `control-${requestId}`,
},
+ runId: `run-${requestId}`,
childContinuationToken: `hook-${requestId}`,
event: REQUEST_EVENT,
kind: "question",