The Open Framework for Building Agents
fix(eve): forward remote subagent input through task sessions (#3918)
Ben Pankowb0b975ba5254
diff --git a/.changeset/remote-task-input-forwarding.md b/.changeset/remote-task-input-forwarding.mdnew file mode 100644index 000000000..1e420673b--- /dev/null+++ b/.changeset/remote-task-input-forwarding.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Remote subagents inherit the parent's human-input capability and forward questions and authorization requests through the parent channel, including concurrent workflow questions. Trusted remote receivers can read the replay-stable invocation operation ID in `onMessage`.diff --git a/e2e/fixtures/agent-subagents/agent/agent.ts b/e2e/fixtures/agent-subagents/agent/agent.tsindex eba694b65..c56f9b7c8 100644--- a/e2e/fixtures/agent-subagents/agent/agent.ts+++ b/e2e/fixtures/agent-subagents/agent/agent.ts@@ -3,6 +3,12 @@ import { defineAgent, defineDynamic } from "eve";import { mockModel } from "eve/evals";import { WORKSPACE_FORWARDING_MARKER, WORKSPACE_LOOKUP_MESSAGE } from "../constants";+import {+ REMOTE_QUESTION_DIRECTIVE,+ respondToRemoteQuestion,+} from "./lib/remote-question-script.js";+import { isNestedDirective, respondToNestedRequest } from "./lib/remote-nested-script.js";+import { isDirectHitlDirective, respondToDirectHitl } from "./lib/remote-direct-hitl-script.js";import {isNotebookDirective,isNotebookEntry,@@ -93,6 +99,15 @@ const workspaceDispatcher = mockModel({};},});+const remoteQuestionModel = mockModel({+ modelId: "remote-question",+ respond: respondToRemoteQuestion,+});+const remoteNestedModel = mockModel({ modelId: "remote-nested", respond: respondToNestedRequest });+const remoteDirectHitlModel = mockModel({+ modelId: "remote-direct-hitl",+ respond: respondToDirectHitl,+});const notebookParent = mockModel({ modelId: "notebook-parent", respond: respondAsNotebookParent });const surveyParent = mockModel({ modelId: "survey-parent", respond: respondAsSurveyParent });const surveyToolParent = mockModel({@@ -141,6 +156,15 @@ export default defineAgent({if (messages.some((message) => message.includes(WORKSPACE_FORWARDING_MARKER))) {return { model: workspaceDispatcher, modelContextWindowTokens: 1_000_000 };}+ if (messages.some((message) => message.includes(REMOTE_QUESTION_DIRECTIVE))) {+ return { model: remoteQuestionModel, modelContextWindowTokens: 1_000_000 };+ }+ if (messages.some(isNestedDirective)) {+ return { model: remoteNestedModel, modelContextWindowTokens: 1_000_000 };+ }+ if (messages.some(isDirectHitlDirective)) {+ return { model: remoteDirectHitlModel, modelContextWindowTokens: 1_000_000 };+ }if (messages.some(isNotebookEntry)) {return { model: notebookKeeper, modelContextWindowTokens: 1_000_000 };}diff --git a/e2e/fixtures/agent-subagents/agent/lib/remote-direct-hitl-script.ts b/e2e/fixtures/agent-subagents/agent/lib/remote-direct-hitl-script.tsnew file mode 100644index 000000000..2481829b8--- /dev/null+++ b/e2e/fixtures/agent-subagents/agent/lib/remote-direct-hitl-script.ts@@ -0,0 +1,44 @@+import { latestTaskResult, playScript } from "@eve-e2e/config/mock-script";+import type { MockModelRequest, MockModelResponse } from "eve/evals";++export const DIRECT_APPROVAL = "REMOTE-DIRECT-APPROVAL-9Q3P";+export const DIRECT_AUTHORIZATION = "REMOTE-DIRECT-AUTHORIZATION-9Q3P";++export function isDirectHitlDirective(message: string): boolean {+ return message.includes(DIRECT_APPROVAL) || message.includes(DIRECT_AUTHORIZATION);+}++export function respondToDirectHitl(request: MockModelRequest): MockModelResponse | string {+ const authorization = request.userMessages.some((message) =>+ message.includes(DIRECT_AUTHORIZATION),+ );+ const marker = authorization ? DIRECT_AUTHORIZATION : DIRECT_APPROVAL;+ if (request.userMessages.some((message) => message.includes(`CHILD-${marker}`))) {+ return playScript(+ request,+ [+ {+ id: "direct-gate",+ name: authorization ? "direct_authorization_gate" : "direct_approval_gate",+ },+ ],+ () => (authorization ? "DIRECT-AUTHORIZATION-COMPLETE" : "DIRECT-APPROVAL-COMPLETE"),+ );+ }+ return playScript(+ request,+ [+ {+ id: "direct-remote",+ name: "remote-loopback",+ input: () => ({ message: `CHILD-${marker}` }),+ },+ ],+ () => {+ const result = latestTaskResult(request, "remote-loopback");+ return result === undefined+ ? "Alice's release checklist is underway."+ : `PARENT-DIRECT-COMPLETE: ${result}`;+ },+ );+}diff --git a/e2e/fixtures/agent-subagents/agent/lib/remote-nested-script.ts b/e2e/fixtures/agent-subagents/agent/lib/remote-nested-script.tsnew file mode 100644index 000000000..f03daebac--- /dev/null+++ b/e2e/fixtures/agent-subagents/agent/lib/remote-nested-script.ts@@ -0,0 +1,68 @@+import { latestTaskResult, playScript } from "@eve-e2e/config/mock-script";+import type { MockModelRequest, MockModelResponse } from "eve/evals";++export const NESTED_APPROVALS = "REMOTE-NESTED-APPROVALS-8H4N";+export const NESTED_AUTHORIZATION = "REMOTE-NESTED-AUTHORIZATION-8H4N";++export function isNestedDirective(message: string): boolean {+ return message.includes(NESTED_APPROVALS) || message.includes(NESTED_AUTHORIZATION);+}++export function respondToNestedRequest(request: MockModelRequest): MockModelResponse | string {+ const authorization = request.userMessages.some((message) =>+ message.includes(NESTED_AUTHORIZATION),+ );+ const marker = authorization ? NESTED_AUTHORIZATION : NESTED_APPROVALS;+ const nested = request.userMessages.some((message) => message.includes(`CHILD-${marker}`));+ if (!nested) {+ return playScript(+ request,+ [+ {+ id: "nested-remote",+ name: "remote-loopback",+ input: () => ({ message: `CHILD-${marker}` }),+ },+ ],+ () => {+ const result = latestTaskResult(request, "remote-loopback");+ return result === undefined+ ? "The remote release checklist is underway."+ : `PARENT-NESTED-COMPLETE: ${result}`;+ },+ );+ }++ const workers = authorization ? ["Alice"] : ["Alice", "Bob"];+ const calls = workers.map((name) => ({+ id: `nested-${name}`,+ name: "nested-approval-worker",+ input: () => ({+ message: authorization+ ? "Authorize Alice's release checklist."+ : `Approve ${name}'s release checklist twice.`,+ }),+ }));+ return playScript(request, calls, () => {+ const results = request.messages+ .filter((message) => message.role === "user")+ .flatMap((message) =>+ [+ ...message.text.matchAll(+ /<task_result id="([^"]+)" tool="nested-approval-worker"[^>]*>([\s\S]*?)<\/task_result>/g,+ ),+ ].map((match) => ({ taskId: match[1], output: match[2] })),+ );+ const expected = authorization ? "NESTED-AUTHORIZED" : "NESTED-APPROVED";+ if (+ results.length === workers.length &&+ new Set(results.map((result) => result.taskId)).size === workers.length &&+ results.every((result) => result.output?.includes(expected))+ ) {+ return authorization+ ? "CHILD-NESTED-AUTHORIZATION-COMPLETE"+ : "CHILD-NESTED-APPROVALS-COMPLETE";+ }+ return "The nested release checklist is underway.";+ });+}diff --git a/e2e/fixtures/agent-subagents/agent/lib/remote-question-script.ts b/e2e/fixtures/agent-subagents/agent/lib/remote-question-script.tsnew file mode 100644index 000000000..ce55c36f6--- /dev/null+++ b/e2e/fixtures/agent-subagents/agent/lib/remote-question-script.ts@@ -0,0 +1,27 @@+import { latestTaskResult } from "@eve-e2e/config/mock-script";+import type { MockModelRequest, MockModelResponse } from "eve/evals";++export const REMOTE_QUESTION_DIRECTIVE = "REMOTE-WORKFLOW-QUESTION-7K2M";++export function respondToRemoteQuestion(request: MockModelRequest): MockModelResponse | string {+ if (+ request.userMessages.some((message) => message.includes(`CHILD-${REMOTE_QUESTION_DIRECTIVE}`))+ ) {+ const result = request.toolResults.find((entry) => entry.name === "remote_question");+ if (result === undefined) return { toolCalls: [{ name: "remote_question", input: {} }] };+ if (!String(result.output).includes("REMOTE-QUESTION-ANSWER=alice-ok")) {+ throw new Error("Remote workflow question did not receive Alice's answer.");+ }+ return "REMOTE-QUESTION-COMPLETE";+ }+ const answer = latestTaskResult(request, "remote-loopback");+ if (answer !== undefined) return `PARENT-QUESTION-COMPLETE: ${answer}`;+ if (request.toolResults.some((entry) => entry.name === "remote-loopback")) {+ return { toolCalls: [{ name: "task_wait", input: {} }] };+ }+ return {+ toolCalls: [+ { name: "remote-loopback", input: { message: `CHILD-${REMOTE_QUESTION_DIRECTIVE}` } },+ ],+ };+}diff --git a/e2e/fixtures/agent-subagents/agent/subagents/nested-approval-worker/agent.ts b/e2e/fixtures/agent-subagents/agent/subagents/nested-approval-worker/agent.tsnew file mode 100644index 000000000..105ecd8ac--- /dev/null+++ b/e2e/fixtures/agent-subagents/agent/subagents/nested-approval-worker/agent.ts@@ -0,0 +1,35 @@+import { defineAgent, defineDynamic } from "eve";+import { mockModel } from "eve/evals";+import { playScript } from "@eve-e2e/config/mock-script";++const workerModel = mockModel({+ modelId: "nested-approval-worker",+ respond(request) {+ const authorization = request.userMessages.some((message) =>+ message.includes("Authorize Alice's release checklist."),+ );+ return authorization+ ? playScript(+ request,+ [{ id: "authorize", name: "authorization_gate", input: () => ({}) }],+ () => "NESTED-AUTHORIZED",+ )+ : playScript(+ request,+ [+ { id: "first", name: "first_gate" },+ { id: "second", name: "second_gate" },+ ],+ () => "NESTED-APPROVED",+ );+ },+});++export default defineAgent({+ description: "Collects Alice's or Bob's release checklist approvals or authorization.",+ model: defineDynamic({+ events: {+ "step.started": () => ({ model: workerModel, modelContextWindowTokens: 1_000_000 }),+ },+ }),+});diff --git a/e2e/fixtures/agent-subagents/agent/subagents/nested-approval-worker/tools/authorization_gate.ts b/e2e/fixtures/agent-subagents/agent/subagents/nested-approval-worker/tools/authorization_gate.tsnew file mode 100644index 000000000..34e658def--- /dev/null+++ b/e2e/fixtures/agent-subagents/agent/subagents/nested-approval-worker/tools/authorization_gate.ts@@ -0,0 +1,40 @@+import {+ ConnectionAuthorizationRequiredError,+ defineInteractiveAuthorization,+} from "eve/connections";+import { defineTool } from "eve/tools";+import { z } from "zod";++const AUTHORIZATION_NAME = "nested-release-authorization";+const AUTHORIZATION_CODE = "nested-release-code";++const authorization = defineInteractiveAuthorization<{ marker: "release" }>({+ async getToken() {+ throw new ConnectionAuthorizationRequiredError(AUTHORIZATION_NAME);+ },+ async startAuthorization() {+ return {+ challenge: { displayName: "Release checklist sign-in", userCode: AUTHORIZATION_CODE },+ resume: { marker: "release" as const },+ };+ },+ async completeAuthorization({ callback, resume }) {+ if (callback.params.code !== AUTHORIZATION_CODE || resume?.marker !== "release") {+ throw new Error("Release checklist authorization failed.");+ }+ return { token: "nested-release-token" };+ },+});++export default defineTool({+ description: "Authorize Alice's release checklist.",+ inputSchema: z.object({}),+ async execute(_input, ctx) {+ const result = await ctx.getToken(authorization, {+ authKey: AUTHORIZATION_NAME,+ displayName: "Release checklist sign-in",+ });+ if (result.token !== "nested-release-token") throw new Error("Unexpected authorization token.");+ return "authorized";+ },+});diff --git a/e2e/fixtures/agent-subagents/agent/subagents/nested-approval-worker/tools/first_gate.ts b/e2e/fixtures/agent-subagents/agent/subagents/nested-approval-worker/tools/first_gate.tsnew file mode 100644index 000000000..5389bfc59--- /dev/null+++ b/e2e/fixtures/agent-subagents/agent/subagents/nested-approval-worker/tools/first_gate.ts@@ -0,0 +1,10 @@+import { defineTool } from "eve/tools";+import { once } from "eve/tools/approval";+import { z } from "zod";++export default defineTool({+ description: "Ask Alice to approve the first release checklist gate.",+ inputSchema: z.object({}),+ approval: once(),+ execute: async () => "first gate approved",+});diff --git a/e2e/fixtures/agent-subagents/agent/subagents/nested-approval-worker/tools/second_gate.ts b/e2e/fixtures/agent-subagents/agent/subagents/nested-approval-worker/tools/second_gate.tsnew file mode 100644index 000000000..138c889e2--- /dev/null+++ b/e2e/fixtures/agent-subagents/agent/subagents/nested-approval-worker/tools/second_gate.ts@@ -0,0 +1,10 @@+import { defineTool } from "eve/tools";+import { once } from "eve/tools/approval";+import { z } from "zod";++export default defineTool({+ description: "Ask Alice to approve the second release checklist gate.",+ inputSchema: z.object({}),+ approval: once(),+ execute: async () => "second gate approved",+});diff --git a/e2e/fixtures/agent-subagents/agent/tools/direct_approval_gate.ts b/e2e/fixtures/agent-subagents/agent/tools/direct_approval_gate.tsnew file mode 100644index 000000000..ae698df6b--- /dev/null+++ b/e2e/fixtures/agent-subagents/agent/tools/direct_approval_gate.ts@@ -0,0 +1,10 @@+import { defineTool } from "eve/tools";+import { once } from "eve/tools/approval";+import { z } from "zod";++export default defineTool({+ description: "Ask Alice to approve her release checklist in the remote agent.",+ inputSchema: z.object({}),+ approval: once(),+ execute: async () => "Alice approved the release checklist.",+});diff --git a/e2e/fixtures/agent-subagents/agent/tools/direct_authorization_gate.ts b/e2e/fixtures/agent-subagents/agent/tools/direct_authorization_gate.tsnew file mode 100644index 000000000..ee7e37ff1--- /dev/null+++ b/e2e/fixtures/agent-subagents/agent/tools/direct_authorization_gate.ts@@ -0,0 +1,39 @@+import {+ ConnectionAuthorizationRequiredError,+ defineInteractiveAuthorization,+} from "eve/connections";+import { defineTool } from "eve/tools";+import { z } from "zod";++const CODE = "direct-release-code";+const NAME = "direct-release-authorization";+const authorization = defineInteractiveAuthorization<{ marker: "direct" }>({+ async getToken() {+ throw new ConnectionAuthorizationRequiredError(NAME);+ },+ async startAuthorization() {+ return {+ challenge: { displayName: "Direct release checklist sign-in", userCode: CODE },+ resume: { marker: "direct" as const },+ };+ },+ async completeAuthorization({ callback, resume }) {+ if (callback.params.code !== CODE || resume?.marker !== "direct") {+ throw new Error("Direct release checklist authorization failed.");+ }+ return { token: "direct-release-token" };+ },+});++export default defineTool({+ description: "Authorize Alice's release checklist in the remote agent.",+ inputSchema: z.object({}),+ async execute(_input, ctx) {+ const result = await ctx.getToken(authorization, {+ authKey: NAME,+ displayName: "Direct release checklist sign-in",+ });+ if (result.token !== "direct-release-token") throw new Error("Unexpected authorization token.");+ return "Alice authorized the release checklist.";+ },+});diff --git a/e2e/fixtures/agent-subagents/agent/tools/remote_question.ts b/e2e/fixtures/agent-subagents/agent/tools/remote_question.tsnew file mode 100644index 000000000..a0476fc45--- /dev/null+++ b/e2e/fixtures/agent-subagents/agent/tools/remote_question.ts@@ -0,0 +1,20 @@+import {+ defineWorkflowTool,+ type WorkflowToolContext,+ type WorkflowToolDefinition,+} from "eve/tools";+import { z } from "zod";++async function execute(_input: Record<string, never>, ctx: WorkflowToolContext): Promise<string> {+ "use workflow";+ const answer = await ctx.ask({ prompt: "What is Alice's approval word?", allowFreeform: true });+ if (answer.status !== "answered") throw new Error("Remote question was not answered.");+ return `REMOTE-QUESTION-ANSWER=${answer.text}`;+}++const tool: WorkflowToolDefinition<Record<string, never>, string> = defineWorkflowTool({+ description: "Ask Alice for an approval word during a remote workflow call.",+ inputSchema: z.object({}),+ execute,+});+export default tool;diff --git a/e2e/fixtures/agent-subagents/evals/remote-direct-approval.eval.ts b/e2e/fixtures/agent-subagents/evals/remote-direct-approval.eval.tsnew file mode 100644index 000000000..4dbea98ca--- /dev/null+++ b/e2e/fixtures/agent-subagents/evals/remote-direct-approval.eval.ts@@ -0,0 +1,56 @@+import { defineEval, type EveEvalContext, type EveEvalSession } from "eve/evals";+import { DIRECT_APPROVAL } from "../agent/lib/remote-direct-hitl-script.js";++export default defineEval({+ description: "Alice approves a tool called directly in her remote agent.",+ timeoutMs: 90_000,+ async test(t) {+ const started = await t.send(+ `${DIRECT_APPROVAL}: Alice asks her remote agent to review the release checklist.`,+ );+ started.expectOk();+ const pending = await waitForDirectApproval(t, started.session);+ const request = pending.requireInputRequest({ toolName: "direct_approval_gate" });+ if (request.kind !== "tool-approval")+ throw new Error("The direct remote gate was not an approval.");+ const answered = await pending.respond([{ requestId: request.requestId, optionId: "approve" }]);+ answered.expectOk();+ let session: EveEvalSession = answered.session;+ if (answered.message?.includes("PARENT-DIRECT-COMPLETE: DIRECT-APPROVAL-COMPLETE")) {+ t.calledSubagent("remote-loopback", { status: "completed", count: 1 });+ t.noFailedActions();+ return;+ }+ for (let attempt = 0; attempt < 8; attempt++) {+ const live = t.target.watchTurn(session.sessionId, { startIndex: session.state.streamIndex });+ const turn = await live.result();+ turn.noFailedActions();+ if (turn.message?.includes("PARENT-DIRECT-COMPLETE: DIRECT-APPROVAL-COMPLETE")) {+ t.calledSubagent("remote-loopback", { status: "completed", count: 1 });+ t.noFailedActions();+ return;+ }+ session = live.session;+ }+ throw new Error("Direct remote approval did not return to Alice's parent session.");+ },+});++async function waitForDirectApproval(+ t: EveEvalContext,+ initial: EveEvalSession,+): Promise<EveEvalSession> {+ let session = initial;+ for (let attempt = 0; attempt < 8; attempt++) {+ if (+ session.pendingInputRequests.some(+ (request) => request.action.toolName === "direct_approval_gate",+ )+ )+ return session;+ const live = t.target.watchTurn(session.sessionId, { startIndex: session.state.streamIndex });+ (await live.result()).noFailedActions();+ session = live.session;+ }+ throw new Error("Direct remote approval did not reach Alice's parent session.");+}diff --git a/e2e/fixtures/agent-subagents/evals/remote-direct-authorization.eval.ts b/e2e/fixtures/agent-subagents/evals/remote-direct-authorization.eval.tsnew file mode 100644index 000000000..7a815cb79--- /dev/null+++ b/e2e/fixtures/agent-subagents/evals/remote-direct-authorization.eval.ts@@ -0,0 +1,34 @@+import { defineEval } from "eve/evals";+import { DIRECT_AUTHORIZATION } from "../agent/lib/remote-direct-hitl-script.js";++export default defineEval({+ description: "Alice authorizes a tool called directly in her remote agent.",+ timeoutMs: 90_000,+ async test(t) {+ const session = await t.session();+ const live = await session.start(+ `${DIRECT_AUTHORIZATION}: Alice asks her remote agent to authorize the release checklist.`,+ );+ const required = await live.waitForEvent("authorization.required");+ if (required.data.webhookUrl === undefined)+ throw new Error("Direct remote authorization has no callback URL.");+ const callback = new URL(required.data.webhookUrl);+ callback.searchParams.set("code", "direct-release-code");+ const response = await fetch(callback);+ if (!response.ok) throw new Error(`Direct authorization callback returned ${response.status}.`);+ const turn = await live.result();+ turn.expectOk();+ turn.event("authorization.required", {+ data: {+ name: "direct-release-authorization",+ authorization: { userCode: "direct-release-code" },+ },+ });+ turn.event("authorization.completed", {+ data: { name: "direct-release-authorization", outcome: "authorized" },+ });+ turn.messageIncludes("PARENT-DIRECT-COMPLETE: DIRECT-AUTHORIZATION-COMPLETE");+ t.calledSubagent("remote-loopback", { status: "completed", count: 1 });+ t.noFailedActions();+ },+});diff --git a/e2e/fixtures/agent-subagents/evals/remote-nested-approvals.eval.ts b/e2e/fixtures/agent-subagents/evals/remote-nested-approvals.eval.tsnew file mode 100644index 000000000..794f20746--- /dev/null+++ b/e2e/fixtures/agent-subagents/evals/remote-nested-approvals.eval.ts@@ -0,0 +1,59 @@+import { defineEval } from "eve/evals";+import { NESTED_APPROVALS } from "../agent/lib/remote-nested-script.js";++export default defineEval({+ description: "Alice approves two nested workers of a remote agent, each at two successive gates.",+ timeoutMs: 120_000,+ async test(t) {+ const started = await t.send(+ `${NESTED_APPROVALS}: Alice asks the remote agent to collect both release checklist approvals.`,+ );+ started.expectOk();+ let session = started.session;+ const seen = new Map<string, Set<string>>([+ ["first_gate", new Set()],+ ["second_gate", new Set()],+ ]);+ for (let attempt = 0; attempt < 16; attempt++) {+ const pending = session.pendingInputRequests.filter(+ (request) => !seen.get(request.action.toolName)?.has(request.requestId),+ );+ if (pending.length > 0) {+ for (const request of pending) {+ const ids = seen.get(request.action.toolName);+ if (ids === undefined || ids.size >= 2 || request.kind !== "tool-approval") {+ throw new Error(`Unexpected nested approval for ${request.action.toolName}.`);+ }+ ids.add(request.requestId);+ }+ const answered = await session.respond(+ pending.map((request) => ({ requestId: request.requestId, optionId: "approve" })),+ );+ answered.expectOk();+ if (answered.message?.includes("PARENT-NESTED-COMPLETE: CHILD-NESTED-APPROVALS-COMPLETE")) {+ if ([...seen.values()].some((ids) => ids.size !== 2))+ throw new Error("Both workers did not pass both gates.");+ t.noFailedActions();+ return;+ }+ session = answered.session;+ continue;+ }+ const live = t.target.watchTurn(session.sessionId!, {+ startIndex: session.state!.streamIndex,+ });+ const turn = await live.result();+ turn.noFailedActions();+ if (turn.message?.includes("PARENT-NESTED-COMPLETE: CHILD-NESTED-APPROVALS-COMPLETE")) {+ if ([...seen.values()].some((ids) => ids.size !== 2))+ throw new Error("Both workers did not pass both gates.");+ t.noFailedActions();+ return;+ }+ session = live.session;+ }+ throw new Error(+ `Nested approvals did not settle: ${[...seen].map(([gate, ids]) => `${gate}=${ids.size}`).join(", ")}.`,+ );+ },+});diff --git a/e2e/fixtures/agent-subagents/evals/remote-nested-authorization.eval.ts b/e2e/fixtures/agent-subagents/evals/remote-nested-authorization.eval.tsnew file mode 100644index 000000000..7b35dec69--- /dev/null+++ b/e2e/fixtures/agent-subagents/evals/remote-nested-authorization.eval.ts@@ -0,0 +1,38 @@+import { defineEval } from "eve/evals";+import { NESTED_AUTHORIZATION } from "../agent/lib/remote-nested-script.js";++const AUTHORIZATION_CODE = "nested-release-code";+const AUTHORIZATION_NAME = "nested-release-authorization";++export default defineEval({+ description:+ "Alice completes a nested worker's authorization callback through the remote parent.",+ timeoutMs: 120_000,+ async test(t) {+ const session = await t.session();+ const live = await session.start(+ `${NESTED_AUTHORIZATION}: Alice asks the remote agent to authorize her release checklist.`,+ );+ const required = await live.waitForEvent("authorization.required");+ if (required.data.webhookUrl === undefined) {+ throw new Error("Nested authorization challenge has no callback URL.");+ }+ const callback = new URL(required.data.webhookUrl);+ callback.searchParams.set("code", AUTHORIZATION_CODE);+ const response = await fetch(callback);+ if (!response.ok) throw new Error(`Nested authorization callback returned ${response.status}.`);++ const turn = await live.result();+ turn.expectOk();+ turn.event("authorization.required", {+ data: { name: AUTHORIZATION_NAME, authorization: { userCode: AUTHORIZATION_CODE } },+ });+ turn.event("authorization.completed", {+ data: { name: AUTHORIZATION_NAME, outcome: "authorized" },+ });+ if (!turn.message?.includes("PARENT-NESTED-COMPLETE: CHILD-NESTED-AUTHORIZATION-COMPLETE")) {+ throw new Error("Nested authorization result did not reach the parent.");+ }+ t.noFailedActions();+ },+});diff --git a/e2e/fixtures/agent-subagents/evals/remote-workflow-question.eval.ts b/e2e/fixtures/agent-subagents/evals/remote-workflow-question.eval.tsnew file mode 100644index 000000000..58daa39c8--- /dev/null+++ b/e2e/fixtures/agent-subagents/evals/remote-workflow-question.eval.ts@@ -0,0 +1,42 @@+import { defineEval, type EveEvalContext, type EveEvalSession } from "eve/evals";+import { REMOTE_QUESTION_DIRECTIVE } from "../agent/lib/remote-question-script.js";++export default defineEval({+ description: "Alice answers a remote workflow question through the parent session.",+ timeoutMs: 90_000,+ async test(t) {+ const started = await t.send(`${REMOTE_QUESTION_DIRECTIVE}: ask Alice for her approval word.`);+ started.expectOk();+ const pending = await waitForInput(t, started.session);+ const request = pending.requireInputRequest({ toolName: "remote_question" });+ if (request.kind !== "question" || request.prompt !== "What is Alice's approval word?") {+ throw new Error("Remote workflow question did not reach the parent.");+ }+ const answered = await pending.respond([{ requestId: request.requestId, text: "alice-ok" }]);+ answered.expectOk();+ const completion = answered.message?.includes("PARENT-QUESTION-COMPLETE")+ ? answered+ : await t.target+ .watchTurn(pending.sessionId, { startIndex: pending.state.streamIndex })+ .result();+ completion.messageIncludes("PARENT-QUESTION-COMPLETE: REMOTE-QUESTION-COMPLETE");+ t.calledSubagent("remote-loopback", { count: 1, status: "completed" });+ t.noFailedActions();+ },+});++async function waitForInput(t: EveEvalContext, initial: EveEvalSession): Promise<EveEvalSession> {+ let session = initial;+ for (let attempt = 0; attempt < 5; attempt += 1) {+ if (+ session.pendingInputRequests.some((request) => request.action.toolName === "remote_question")+ )+ return session;+ const turn = await t.target+ .watchTurn(session.sessionId, { startIndex: session.state.streamIndex })+ .result();+ turn.noFailedActions();+ session = turn.session;+ }+ throw new Error("Remote workflow tool did not ask Alice.");+}diff --git a/packages/eve/src/channel/adapter.ts b/packages/eve/src/channel/adapter.tsindex 6a7cc2316..bdaa9af4a 100644--- a/packages/eve/src/channel/adapter.ts+++ b/packages/eve/src/channel/adapter.ts@@ -49,6 +49,9 @@ export interface ChannelAdapterContext<TState = Record<string, unknown>> {* Live handle to the current session.*/readonly session: SessionHandle;++ /** @internal Independent source of a relayed child input batch. */+ readonly inputSource?: string;}/**diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.tsindex f080570ea..c73c98734 100644--- a/packages/eve/src/channel/types.ts+++ b/packages/eve/src/channel/types.ts@@ -305,6 +305,11 @@ export interface SubagentInputRequestEvent {* `input.requested` handler and the parent's runtime loop.*/export interface SubagentInputRequestHookPayload {+ readonly remote?: import("#eve-channel/support.js").RemoteAgentBinding & {+ readonly sessionId: string;+ };+ /** Independent source when several requests share an answer destination. */+ readonly inputSource?: string;readonly callId: string;readonly childContinuationToken: string;readonly childSessionId: string;diff --git a/packages/eve/src/eve-channel/index.ts b/packages/eve/src/eve-channel/index.tsindex dc49b32ea..6c348515f 100644--- a/packages/eve/src/eve-channel/index.ts+++ b/packages/eve/src/eve-channel/index.ts@@ -301,6 +301,10 @@ export function eveChannel(input: EveChannelInput): EveChannel {: await resolveOnMessage({auth: forwarded.auth,config: input,+ invocation:+ parent === undefined || body.operationId === undefined+ ? undefined+ : { operationId: body.operationId },message: body.message,request: req,});diff --git a/packages/eve/src/eve-channel/support.ts b/packages/eve/src/eve-channel/support.tsindex 4f189aa43..ec4a3f559 100644--- a/packages/eve/src/eve-channel/support.ts+++ b/packages/eve/src/eve-channel/support.ts@@ -27,6 +27,7 @@ export function healthResponse(): Response {/** Where a remote child the parent session recorded runs, and its credential key. */export interface RemoteAgentBinding {+ readonly forwardPrincipal?: boolean;readonly name: string;readonly resolverId?: string;readonly url: string;@@ -148,6 +149,7 @@ interface OnMessageOutcome {export async function resolveOnMessage(input: {readonly auth: SessionAuthContext | null;readonly config: EveChannelInput;+ readonly invocation?: EveHandle["invocation"];readonly message: string | UserContent;readonly request: Request;readonly sessionId?: string;@@ -156,10 +158,13 @@ export async function resolveOnMessage(input: {let result: EveMessageResult;try {+ const base = { caller: input.auth, request: input.request };const eve: EveHandle =input.sessionId === undefined- ? { caller: input.auth, request: input.request }- : { caller: input.auth, request: input.request, sessionId: input.sessionId };+ ? input.invocation === undefined+ ? base+ : { ...base, invocation: input.invocation }+ : { ...base, sessionId: input.sessionId };const ctx: EveMessageContext = { eve };result = await handler(ctx, input.message);if (result === null || result === undefined) {diff --git a/packages/eve/src/eve-channel/types.ts b/packages/eve/src/eve-channel/types.tsindex 50a4c20fd..1ee8ff5fb 100644--- a/packages/eve/src/eve-channel/types.ts+++ b/packages/eve/src/eve-channel/types.ts@@ -55,6 +55,8 @@ export type EveChannelCors = boolean | EveChannelCorsOptions;export interface EveHandle {/** Route-auth result for the request; `onMessage` chooses session auth by returning `{ auth }`. */readonly caller: SessionAuthContext | null;+ /** Replay-stable identity of a trusted remote-subagent create operation. */+ readonly invocation?: { readonly operationId: string };readonly request: Request;/** Existing runtime session id for follow-up requests. */readonly sessionId?: string;diff --git a/packages/eve/src/execution/agent-sessions/remote.test.ts b/packages/eve/src/execution/agent-sessions/remote.test.tsindex 43ac0e2a4..6f7f76e13 100644--- a/packages/eve/src/execution/agent-sessions/remote.test.ts+++ b/packages/eve/src/execution/agent-sessions/remote.test.ts@@ -8,6 +8,7 @@ import {resetRemoteAgentSession,resolveRemoteAgentForAction,resolveRemoteAgentStreamHeaders,+ respondToRemoteAgentSession,startRemoteAgentSession,} from "#execution/agent-sessions/remote.js";import type { RuntimeRemoteAgentDispatchRequest } from "#shared/action-types.js";@@ -427,6 +428,32 @@ describe("startRemoteAgentSession", () => {expect(body.capabilities).toEqual({});});+ it("passes an input-capable parent's capability to a remote child", async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ ok: true,+ protocolVersion: 2,+ sessionId: "remote-session",+ status: "accepted",+ }),+ { status: 202 },+ ),+ );+ vi.stubGlobal("fetch", fetchMock);++ await startRemoteAgentSession({+ action: createAction(),+ callbackBaseUrl: "https://caller.example.com",+ capabilities: { requestInput: true },+ remote: createRemoteAgent(),+ session: { continuationToken: "eve:parent-token" },+ });++ const body = JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string);+ expect(body.capabilities).toEqual({ requestInput: true });+ });+it("targets an active turn inbox when a callback token is supplied", async () => {const fetchMock = vi.fn().mockResolvedValue(new Response(@@ -773,6 +800,60 @@ describe("startRemoteAgentSession — forwarded principal", () => {});});+describe("respondToRemoteAgentSession", () => {+ afterEach(() => vi.unstubAllGlobals());++ it("sends an answer to the child's authenticated session route, not a parent-local hook", async () => {+ const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 202 }));+ vi.stubGlobal("fetch", fetchMock);+ await respondToRemoteAgentSession({+ auth: null,+ headers: { authorization: "Bearer remote-token" },+ remote: {+ name: "research",+ sessionId: "remote-session",+ url: "https://remote.example.com/prefix",+ },+ responses: [{ requestId: "ask-1", text: "approved" }],+ });+ expect(fetchMock).toHaveBeenCalledWith(+ "https://remote.example.com/prefix/eve/v1/session/remote-session",+ expect.objectContaining({+ body: JSON.stringify({ inputResponses: [{ requestId: "ask-1", text: "approved" }] }),+ headers: { authorization: "Bearer remote-token", "content-type": "application/json" },+ method: "POST",+ }),+ );+ });++ it("forwards the human responder only when the remote opts into principal forwarding", async () => {+ const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 202 }));+ vi.stubGlobal("fetch", fetchMock);+ const responder: SessionAuthContext = {+ attributes: {},+ authenticator: "fixture",+ principalId: "alice",+ principalType: "user",+ };+ const input = {+ auth: responder,+ headers: { authorization: "Bearer remote-token" },+ remote: { name: "research", sessionId: "remote-session", url: "https://remote.example.com" },+ responses: [{ requestId: "approval-1", optionId: "approve" }],+ };+ await respondToRemoteAgentSession({+ ...input,+ remote: { ...input.remote, forwardPrincipal: true },+ });+ await respondToRemoteAgentSession({ ...input, remote: input.remote });+ const bodies = fetchMock.mock.calls.map(([, options]) => JSON.parse(options.body as string));+ expect(bodies).toEqual([+ { inputResponses: input.responses, forwardedPrincipal: { current: responder } },+ { inputResponses: input.responses },+ ]);+ });+});+describe("continueRemoteAgentSession", () => {afterEach(() => {vi.unstubAllGlobals();diff --git a/packages/eve/src/execution/agent-sessions/remote.ts b/packages/eve/src/execution/agent-sessions/remote.tsindex 537cf910e..ee4aeac80 100644--- a/packages/eve/src/execution/agent-sessions/remote.ts+++ b/packages/eve/src/execution/agent-sessions/remote.ts@@ -18,6 +18,7 @@ import type {ActivityObserverConfig,CancelTurnResult,SessionAuthContext,+ SessionCapabilities,SessionTraceContext,} from "#channel/types.js";import type { ChannelAudience } from "#shared/channel-audience.js";@@ -32,6 +33,8 @@ import type { RuntimeRemoteAgentDispatchRequest } from "#shared/action-types.js"import type { RuntimeSubagentRegistry } from "#runtime/subagents/registry.js";import type { DynamicRemoteAgentConfig } from "#runtime/subagents/dynamic-remote-agent-config.js";import type { CompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";+import type { RemoteAgentBinding } from "#eve-channel/support.js";+import type { InputResponse } from "#shared/input.js";import type { ResolvedRuntimeRemoteAgentNode } from "#runtime/types.js";import { expectFunction, expectObjectRecord } from "#internal/authored-module.js";import type { JsonObject } from "#shared/json.js";@@ -58,6 +61,7 @@ export async function startRemoteAgentSession(input: {/** The dispatching turn's session principal, forwarded when `remote.forwardPrincipal` is set. */readonly auth?: SessionAuthContext | null;readonly callbackBaseUrl: string | undefined;+ readonly capabilities?: SessionCapabilities;readonly originAudience?: ChannelAudience;readonly activityObserver?: ActivityObserverConfig;/** The root initiator's principal, forwarded alongside {@link auth}. */@@ -84,7 +88,7 @@ export async function startRemoteAgentSession(input: {const forwardedPrincipal = buildForwardedPrincipalField(input);const requestBody: {- capabilities: {};+ capabilities: SessionCapabilities;callback: {callId: string;subagentName: string;@@ -98,7 +102,7 @@ export async function startRemoteAgentSession(input: {outputSchema?: object;protocolVersion: number;} = {- capabilities: {},+ capabilities: input.capabilities ?? {},callback: {callId: input.action.callId,subagentName: input.action.remoteAgentName,@@ -224,6 +228,33 @@ function buildForwardedTraceAssertion(input: {};}+export async function respondToRemoteAgentSession(input: {+ readonly remote: RemoteAgentBinding & { readonly sessionId: string };+ readonly headers: Record<string, string>;+ readonly auth: SessionAuthContext | null | undefined;+ readonly responses: readonly InputResponse[];+}): Promise<void> {+ const response = await fetch(+ createRemoteAgentRouteUrl(input.remote.url, createEveSessionRoutePath(input.remote.sessionId)),+ {+ body: JSON.stringify({+ inputResponses: input.responses,+ ...(input.remote.forwardPrincipal === true &&+ input.auth != null && {+ forwardedPrincipal: { current: input.auth },+ }),+ }),+ headers: { "content-type": "application/json", ...input.headers },+ method: "POST",+ redirect: "error",+ },+ );+ if (!response.ok)+ throw new Error(+ `Remote agent "${input.remote.name}" input answer failed with HTTP ${response.status}.`,+ );+}+/** Continues one remote-agent session by its immutable session ID. */export async function continueRemoteAgentSession(input: {readonly activityObserver?: ActivityObserverConfig;diff --git a/packages/eve/src/execution/agent-sessions/requests.ts b/packages/eve/src/execution/agent-sessions/requests.tsindex e9f1a9d8a..0409b15e8 100644--- a/packages/eve/src/execution/agent-sessions/requests.ts+++ b/packages/eve/src/execution/agent-sessions/requests.ts@@ -2,12 +2,9 @@ import type {SubagentAuthorizationEventHookPayload,SubagentInputRequestHookPayload,} from "#channel/types.js";-import {- sessionCommandHookToken,- sessionInboxHookToken,-} from "#execution/session-inbox/address.js";import type { WorkflowToolRunRef } from "#execution/tools/workflow/messages.js";import type { WorkflowToolRunInbox } from "#execution/tools/workflow/owner.js";+import type { RemoteAgentBinding } from "#eve-channel/support.js";/** A child's question or sign-in, which only a person at the root can answer. */export type AgentSessionRequest =@@ -24,6 +21,7 @@ export async function forwardAgentSessionRequest(input: {readonly owner: WorkflowToolRunInbox;readonly replyTo: string;readonly request: AgentSessionRequest;+ readonly remote?: RemoteAgentBinding & { readonly sessionId: string };}): Promise<void> {const { from, request } = input;if (request.kind === "subagent-authorization-event") {@@ -37,8 +35,14 @@ export async function forwardAgentSessionRequest(input: {}await input.owner.send({from,+ inputSource: request.inputSource,+ remote: input.remote,kind: "request",- replyTo: childAnswerToken(request),+ replyTo: request.childContinuationToken,+ childSessionInbox:+ request.childSessionInbox?.sessionId === request.childSessionId+ ? request.childSessionInbox+ : undefined,request: { kind: "input-batch", requests: request.event.requests },requestCoordinates: {sequence: request.event.sequence,@@ -47,15 +51,3 @@ export async function forwardAgentSessionRequest(input: {},});}--/**- * Current session inboxes take answers on their physical token. A remote- * child's create-once operation hook is already a narrowed reply capability.- */-function childAnswerToken(request: SubagentInputRequestHookPayload): string {- const inbox = request.childSessionInbox;- if (inbox?.sessionId === request.childSessionId) {- return sessionInboxHookToken(sessionCommandHookToken(inbox.sessionId));- }- return request.childContinuationToken;-}diff --git a/packages/eve/src/execution/agent-sessions/session.ts b/packages/eve/src/execution/agent-sessions/session.tsindex 29a8b24a6..8a88557a9 100644--- a/packages/eve/src/execution/agent-sessions/session.ts+++ b/packages/eve/src/execution/agent-sessions/session.ts@@ -155,6 +155,20 @@ class RunAgentSession implements AgentSession {owner: this.#run.owner,replyTo: hook.token,request: reply,+ remote:+ this.#opened === undefined+ ? undefined+ : await this.#opened.then(({ address }) =>+ address.kind === "remote"+ ? {+ forwardPrincipal: address.forwardPrincipal,+ name: address.name,+ resolverId: address.resolverId,+ url: address.url,+ sessionId: address.sessionId,+ }+ : undefined,+ ),});continue;}diff --git a/packages/eve/src/execution/agent-sessions/steps.ts b/packages/eve/src/execution/agent-sessions/steps.tsindex 04212060f..9a2506fa7 100644--- a/packages/eve/src/execution/agent-sessions/steps.ts+++ b/packages/eve/src/execution/agent-sessions/steps.ts@@ -52,6 +52,7 @@ export type AgentSessionAddress =| {readonly callbackBaseUrl: string;readonly kind: "remote";+ readonly forwardPrincipal?: boolean;readonly name: string;readonly nodeId: string;/** Keys the authored credential functions, as on `agent.started`. */@@ -286,6 +287,7 @@ async function startRemoteSession(}),auth: auth.current,callbackBaseUrl,+ capabilities: context.capabilities,initiatorAuth: auth.initiator,operationId: `agent-session:${input.key}`,originAudience: context.trace.originAudience,@@ -296,6 +298,7 @@ async function startRemoteSession(return {callbackBaseUrl,kind: "remote",+ forwardPrincipal: remote.forwardPrincipal,name: action.remoteAgentName,nodeId: action.nodeId,resolverId: target.dynamicRemoteAgent?.credentialsStepId ?? action.nodeId,diff --git a/packages/eve/src/execution/forward-session-input.ts b/packages/eve/src/execution/forward-session-input.tsnew file mode 100644index 000000000..8b626372a--- /dev/null+++ b/packages/eve/src/execution/forward-session-input.ts@@ -0,0 +1,52 @@+import type { ContextContainer } from "#context/container.js";+import {+ ContinuationTokenKey,+ SessionCallbackKey,+ SessionIdKey,+ SessionInboxKey,+} from "#context/keys.js";+import { postSessionCallbackRequest } from "#execution/session-callback-request.js";+import { sessionCommandHookToken } from "#execution/session-inbox/address.js";+import type { UnstampedMessageStreamEvent } from "#protocol/message.js";++/** A remote session sends input to its caller instead of presenting it on its own channel. */+export async function forwardSessionInput(+ ctx: ContextContainer,+ event: UnstampedMessageStreamEvent,+ inputSource?: string,+): Promise<boolean> {+ const callback = ctx.get(SessionCallbackKey);+ if (callback === undefined) return false;+ if (+ event.type !== "input.requested" &&+ event.type !== "authorization.required" &&+ event.type !== "authorization.completed" &&+ event.type !== "approval.candidate" &&+ event.type !== "approval.settled"+ )+ return false;++ const body =+ event.type === "input.requested"+ ? {+ callId: callback.callId,+ childContinuationToken:+ ctx.get(ContinuationTokenKey) ?? sessionCommandHookToken(ctx.require(SessionIdKey)),+ childSessionId: ctx.require(SessionIdKey),+ childSessionInbox: ctx.get(SessionInboxKey),+ event: event.data,+ inputSource: inputSource ?? "session",+ kind: "subagent-input-request",+ subagentName: callback.subagentName,+ }+ : {+ callId: callback.callId,+ childSessionId: ctx.require(SessionIdKey),+ event,+ kind: "subagent-authorization-event",+ subagentName: callback.subagentName,+ };+ const response = await postSessionCallbackRequest({ body, url: callback.url });+ if (!response.ok) throw new Error(`Remote input callback failed with HTTP ${response.status}.`);+ return true;+}diff --git a/packages/eve/src/execution/proxied-deliver-step.ts b/packages/eve/src/execution/proxied-deliver-step.tsindex 9b04177de..16ec7c784 100644--- a/packages/eve/src/execution/proxied-deliver-step.ts+++ b/packages/eve/src/execution/proxied-deliver-step.ts@@ -8,6 +8,12 @@ import {replaceDurableSessionSnapshot,} from "#execution/durable-session-store.js";import { relaySessionEvents, type SessionStepState } from "#execution/publish-session-events.js";+import { deserializeContext } from "#context/serialize.js";+import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";+import {+ resolveRemoteAgentStreamHeaders,+ respondToRemoteAgentSession,+} from "#execution/agent-sessions/remote.js";import { routeDeliverPayload } from "#subagents/hitl-proxy.js";import { resumeSessionInbox } from "#execution/session-inbox/resume.js";import {@@ -38,6 +44,9 @@ export type RoutedDeliverResult =interface ChildBucket {readonly workflowAsk?: WorkflowAskRoute;+ readonly remote?: NonNullable<+ import("#harness/proxy-input-requests.js").ProxyInputRequest["remote"]+ >;readonly childContinuationToken: string;readonly childSessionInbox?: SessionInboxAddress;readonly event: PendingInputBatchEvent;@@ -83,12 +92,18 @@ export async function routeProxiedDeliverStep(if (forChild.workflowAsk !== undefined) {for (const { requestId } of forChild.resolved.resolutions) resolvedQuestions.add(requestId);}- const key = [+ const key = JSON.stringify([forChild.childContinuationToken,forChild.childSessionInbox?.sessionId ?? "",- ].join("\0");+ forChild.remote?.sessionId ?? "",+ forChild.resolved.event.sequence,+ forChild.resolved.event.stepIndex,+ forChild.resolved.event.turnId,+ forChild.inputSource ?? null,+ ]);const child: ChildBucket = children.get(key) ?? {workflowAsk: forChild.workflowAsk,+ remote: forChild.remote,childContinuationToken: forChild.childContinuationToken,childSessionInbox: forChild.childSessionInbox,event: forChild.resolved.event,@@ -130,10 +145,27 @@ export async function routeProxiedDeliverStep(deliveryMetadata: child.metadata.length === 0 ? undefined : child.metadata,payloads: child.payloads,};- await resumeSessionInbox(- child.childSessionInbox ?? child.childContinuationToken,- childDelivery,- );+ const remote = child.remote;+ if (remote !== undefined) {+ const ctx = await deserializeContext(input.serializedContext);+ const headers = await resolveRemoteAgentStreamHeaders({+ bundle: ctx.require(BundleKey),+ name: remote.name,+ resolverId: remote.resolverId,+ url: remote.url,+ });+ await respondToRemoteAgentSession({+ remote,+ headers,+ auth: sourceDelivery.auth,+ responses: coalesceDeliverPayloads(child.payloads).inputResponses ?? [],+ });+ } else {+ await resumeSessionInbox(+ child.childSessionInbox ?? child.childContinuationToken,+ childDelivery,+ );+ }}if (child.resolutions.size > 0) {resolvedEvents.push(diff --git a/packages/eve/src/execution/publish-session-events.ts b/packages/eve/src/execution/publish-session-events.tsindex ef92722a6..e73613909 100644--- a/packages/eve/src/execution/publish-session-events.ts+++ b/packages/eve/src/execution/publish-session-events.ts@@ -7,6 +7,7 @@ import { withContextScope } from "#context/run-step.js";import { deserializeContext, serializeContext } from "#context/serialize.js";import * as activityCohort from "#execution/activity-cohort.js";import { setChannelContext } from "#execution/channel-context.js";+import { forwardSessionInput } from "#execution/forward-session-input.js";import {createDurableSessionState,readDurableSession,@@ -119,6 +120,7 @@ export async function withSessionEventEmitter<T>(readonly durableSession: DurableSession;readonly origin: SessionEventOrigin;readonly sessionWritable: WritableStream<Uint8Array>;+ readonly inputSource?: string;},emitEvents: (emit: HandleEventFn,@@ -148,6 +150,7 @@ export async function withSessionEventEmitter<T>(origin: input.origin,sessionId: session.sessionId,sessionWritable: input.sessionWritable,+ inputSource: input.inputSource,});try {return await withContextScope(ctx, session, async (enrichedSession) => {@@ -206,6 +209,7 @@ function openSessionEventStream(input: {readonly origin: SessionEventOrigin;readonly sessionId: string;readonly sessionWritable: WritableStream<Uint8Array>;+ readonly inputSource?: string;}): SessionEventSink {const { ctx, origin } = input;const adapter = ctx.require(ChannelKey);@@ -222,7 +226,16 @@ function openSessionEventStream(input: {adapterCtx,async emit(event) {if (origin === "own") activityCohort.updateActivityState(ctx, event);- const routed = await callAdapterEventHandler(adapter, event, adapterCtx);+ const forwarded = await forwardSessionInput(ctx, event, input.inputSource);+ const routed = forwarded+ ? event+ : await callAdapterEventHandler(+ adapter,+ event,+ input.inputSource === undefined+ ? adapterCtx+ : { ...adapterCtx, inputSource: input.inputSource },+ );setChannelContext(ctx, { ...adapter, state: { ...adapterCtx.state } });const stamped = stampMessageStreamEvent(routed,diff --git a/packages/eve/src/execution/remote-agent-input.scenario.test.ts b/packages/eve/src/execution/remote-agent-input.scenario.test.tsnew file mode 100644index 000000000..9fe81470c--- /dev/null+++ b/packages/eve/src/execution/remote-agent-input.scenario.test.ts@@ -0,0 +1,353 @@+import { spawn } from "node:child_process";+import { join } from "node:path";+import { expect, it } from "vitest";+import { Client } from "#client/client.js";+import type { ClientSession } from "#client/session.js";+import { filterEventsByType } from "#internal/testing/events.js";+import { type ScenarioAppDescriptor, useScenarioApp } from "#internal/testing/scenario-app.js";+import type { HandleMessageStreamEvent } from "#protocol/message.js";++const scenarioApp = useScenarioApp();+const TOKEN = "remote-input-scenario-token";+const ANSWER = "approved-by-parent";+const CHILD_RESULT = `CHILD_APPROVED=${ANSWER}`;+const PARENT_RESULT = `REMOTE_HITL_RESULT=${ANSWER}`;+const TIMEOUT = 120_000;++const channel = `import { none } from "eve/channels/auth"; import { eveChannel } from "eve/channels/eve"; export default eveChannel({ auth: none() });`;+const remoteChannel = `import { eveChannel } from "eve/channels/eve"; export default eveChannel({ trustedForwarders: (f) => f.principalId === "remote-parent", auth(request) { if (request.headers.get("authorization") !== "Bearer ${TOKEN}") return null; return { attributes: {}, authenticator: "scenario", principalId: "remote-parent", principalType: "service" }; } });`;++const childTool = `import { defineWorkflowTool } from "eve/tools";+export default defineWorkflowTool({ description: "Ask the parent.", inputSchema: {}, async execute(_input, ctx) { "use workflow"; const answer = await ctx.ask({ prompt: "What is the approval word?", allowFreeform: true }); return answer.text ?? answer.optionId ?? "NO_ANSWER"; } });`;+const childAgent = `import { defineAgent } from "eve"; import { mockModel } from "eve/evals";+const model = mockModel((request) => { const result = request.toolResults.find((entry) => entry.id === "ask-parent"); if (result) return "${CHILD_RESULT}".replace("${ANSWER}", String(result.output)); return { toolCalls: [{ id: "ask-parent", name: "ask-parent", input: {} }] }; });+export default defineAgent({ model, modelContextWindowTokens: 32000 });`;+const concurrentChildAgent = `import { defineAgent } from "eve"; import { mockModel } from "eve/evals";+const model = mockModel((request) => {+ const results = request.toolResults;+ if (results.some((entry) => entry.id === "ask-alice" && entry.output === "alice-lantern") &&+ results.some((entry) => entry.id === "ask-bob" && entry.output === "bob-comet")) return "CHILD_APPROVED=alice-lantern,bob-comet";+ if (results.some((entry) => entry.id === "ask-alice" || entry.id === "ask-bob")) return "Waiting for both approvals.";+ return { toolCalls: [{ id: "ask-alice", name: "ask-alice", input: {} }, { id: "ask-bob", name: "ask-bob", input: {} }] };+});+export default defineAgent({ model, modelContextWindowTokens: 32000 });`;+const askTool = (person: string) => `import { defineWorkflowTool } from "eve/tools";+export default defineWorkflowTool({ description: "Ask for ${person}'s approval word.", inputSchema: {}, async execute(_input, ctx) { "use workflow"; const answer = await ctx.ask({ prompt: "Word for ${person}?", allowFreeform: true }); return answer.text ?? "NO_ANSWER"; } });`;++const childDescriptor: ScenarioAppDescriptor = {+ name: "remote-input-child",+ installDependencies: true,+ files: {+ "agent/agent.ts": childAgent,+ "agent/channels/eve.ts": remoteChannel,+ "agent/instructions.md": "Ask the parent for approval.",+ "agent/tools/ask-parent.ts": childTool,+ },+};++const memoryChildDescriptor: ScenarioAppDescriptor = {+ name: "remote-memory-child",+ installDependencies: true,+ files: {+ "agent/agent.ts": `import { defineAgent } from "eve"; import { mockModel } from "eve/evals";+const model = mockModel((request) => {+ if (request.userMessageCount === 1) return request.lastUserMessage?.includes("LANTERN-COMET-7319") ? "STORED" : "MISSING_CODEWORD";+ if (request.userMessageCount === 2) return request.userMessages[0]?.includes("LANTERN-COMET-7319") ? "LANTERN-COMET-7319" : "CONTEXT_LOST";+ return "UNEXPECTED_TURN";+});+export default defineAgent({ model, modelContextWindowTokens: 32000 });`,+ "agent/channels/eve.ts": remoteChannel,+ "agent/instructions.md": "Remember the first message for the follow-up.",+ },+};++const concurrentChildDescriptor: ScenarioAppDescriptor = {+ name: "remote-input-concurrent-child",+ installDependencies: true,+ files: {+ "agent/agent.ts": concurrentChildAgent,+ "agent/channels/eve.ts": remoteChannel,+ "agent/instructions.md": "Ask Alice and Bob for their words.",+ "agent/tools/ask-alice.ts": askTool("Alice"),+ "agent/tools/ask-bob.ts": askTool("Bob"),+ },+};++function parentDescriptor(url: string, concurrent = false): ScenarioAppDescriptor {+ const expectedChildResult = concurrent ? "CHILD_APPROVED=alice-lantern,bob-comet" : CHILD_RESULT;+ const expectedParentResult = concurrent+ ? "REMOTE_HITL_RESULT=alice-lantern,bob-comet"+ : PARENT_RESULT;+ const parentAgent = `import { defineAgent } from "eve"; import { mockModel } from "eve/evals";+const model = mockModel((request) => { const text = request.messages.map((m) => m.text).join("\\n"); if (text.includes("<task_result") && text.includes("${expectedChildResult}")) return "${expectedParentResult}"; if (request.toolResults.some((r) => r.id === "delegate")) return { toolCalls: [{ id: "wait", name: "task_wait", input: {} }] }; return { toolCalls: [{ id: "delegate", name: "delegate-approval", input: {} }] }; });+export default defineAgent({ model, modelContextWindowTokens: 32000 });`;+ const tool = `import { defineWorkflowTool } from "eve/tools";+export default defineWorkflowTool({ description: "Delegate approval.", inputSchema: {}, async task(_input, ctx) { "use workflow"; const result = await ctx.agent("remote-hitl-child").send("Ask the parent for approval."); return (await result.result()).message; } });`;+ const remote = `import { defineRemoteAgent } from "eve"; import { bearer } from "eve/agents/auth"; export default defineRemoteAgent({ auth: bearer(${JSON.stringify(TOKEN)}), description: "Ask parent", url: ${JSON.stringify(url)} });`;+ return {+ name: "remote-input-parent",+ installDependencies: true,+ files: {+ "agent/agent.ts": parentAgent,+ "agent/channels/eve.ts": channel,+ "agent/instructions.md": "Delegate the approval question.",+ "agent/tools/delegate-approval.ts": tool,+ "agent/subagents/remote-hitl-child.ts": remote,+ },+ };+}++function memoryParentDescriptor(url: string): ScenarioAppDescriptor {+ const parentAgent = `import { defineAgent } from "eve"; import { mockModel } from "eve/evals";+const model = mockModel((request) => {+ const text = request.messages.map((message) => message.text).join("\\n");+ if (text.includes("MEMORY_RECALLED=LANTERN-COMET-7319")) return "PARENT_RECALLED=LANTERN-COMET-7319";+ if (text.includes("MEMORY_RECALLED=CONTEXT_LOST")) return "PARENT_RECALLED=CONTEXT_LOST";+ if (request.toolResults.some((result) => result.id === "remember")) return { toolCalls: [{ id: "wait-memory", name: "task_wait", input: {} }] };+ return { toolCalls: [{ id: "remember", name: "remember", input: {} }] };+});+export default defineAgent({ model, modelContextWindowTokens: 32000 });`;+ const tool = `import { defineWorkflowTool } from "eve/tools";+export default defineWorkflowTool({ description: "Remember and recall a codeword in one remote session.", inputSchema: {}, async task(_input, ctx) { "use workflow";+ const agent = ctx.agent("remote-memory-child");+ const first = await (await agent.send("Remember the codeword LANTERN-COMET-7319.")).result();+ if (first.message !== "STORED") return "MEMORY_FIRST_FAILED=" + first.message;+ const second = await (await agent.send("What codeword did I ask you to remember?")).result();+ return "MEMORY_RECALLED=" + second.message;+} });`;+ const remote = `import { defineRemoteAgent } from "eve"; import { bearer } from "eve/agents/auth"; export default defineRemoteAgent({ auth: bearer(${JSON.stringify(TOKEN)}), description: "Remember a codeword", url: ${JSON.stringify(url)} });`;+ return {+ name: "remote-memory-parent",+ installDependencies: true,+ files: {+ "agent/agent.ts": parentAgent,+ "agent/channels/eve.ts": channel,+ "agent/instructions.md": "Ask the remote child to remember and recall a codeword.",+ "agent/tools/remember.ts": tool,+ "agent/subagents/remote-memory-child.ts": remote,+ },+ };+}++interface RunningServer {+ readonly url: string;+ readonly stdout: () => string;+ readonly stderr: () => string;+ stop(): Promise<void>;+}++it(+ "forwards one remote child HITL question to the root parent",+ async () => {+ const child = await scenarioApp(childDescriptor);+ const childServer = await startScriptedEveDev(child.appRoot);+ let parentServer: RunningServer | undefined;+ try {+ const parent = await scenarioApp(parentDescriptor(childServer.url));+ parentServer = await startScriptedEveDev(parent.appRoot);+ const client = new Client({ host: parentServer.url });+ const { session, response } = await client.sessions.create({+ message: "Delegate the approval question.",+ });+ const waiting = await response.result();+ expect(waiting.status).toBe("waiting");+ const events = await waitFor(+ session,+ (es) =>+ filterEventsByType(es, "input.requested").length === 1 ||+ filterEventsByType(es, "session.failed").length > 0,+ );+ expect(filterEventsByType(events, "session.failed")).toHaveLength(0);+ const request = filterEventsByType(events, "input.requested")[0]!.data.requests[0]!;+ expect(request.prompt).toBe("What is the approval word?");+ await session.respond([{ requestId: request.requestId, text: ANSWER }]);+ const final = await waitFor(+ session,+ (es) =>+ filterEventsByType(es, "message.completed").some(+ (e) => e.data.message === PARENT_RESULT,+ ) || filterEventsByType(es, "session.failed").length > 0,+ );+ expect(filterEventsByType(final, "session.failed")).toHaveLength(0);+ expect(filterEventsByType(final, "message.completed").map((e) => e.data.message)).toContain(+ PARENT_RESULT,+ );+ } catch (error) {+ throw new Error(+ `parent stdout:\n${parentServer?.stdout() ?? "not started"}\nparent stderr:\n${parentServer?.stderr() ?? "not started"}\nchild stdout:\n${childServer.stdout()}\nchild stderr:\n${childServer.stderr()}`,+ { cause: error },+ );+ } finally {+ await parentServer?.stop();+ await childServer.stop();+ }+ },+ TIMEOUT,+);++it(+ "answers two independent remote workflow questions without losing either request",+ async () => {+ const child = await scenarioApp(concurrentChildDescriptor);+ const childServer = await startScriptedEveDev(child.appRoot);+ let parentServer: RunningServer | undefined;+ try {+ const parent = await scenarioApp(parentDescriptor(childServer.url, true));+ parentServer = await startScriptedEveDev(parent.appRoot);+ const { session, response } = await new Client({ host: parentServer.url }).sessions.create({+ message: "Delegate the approval questions for Alice and Bob.",+ });+ expect((await response.result()).status).toBe("waiting");+ const pending = await waitFor(+ session,+ (events) =>+ filterEventsByType(events, "input.requested").flatMap((event) => event.data.requests)+ .length >= 2,+ );+ const requests = filterEventsByType(pending, "input.requested").flatMap(+ (event) => event.data.requests,+ );+ expect(requests.map((request) => request.prompt).sort()).toEqual([+ "Word for Alice?",+ "Word for Bob?",+ ]);+ const alice = requests.find((request) => request.prompt.includes("Alice"))!;+ const bob = requests.find((request) => request.prompt.includes("Bob"))!;+ const first = await session.respond([{ requestId: alice.requestId, text: "alice-lantern" }]);+ expect((await first.result()).status).toBe("waiting");+ const afterFirst = await session.snapshot();+ expect(+ filterEventsByType(afterFirst.events, "input.resolved")+ .flatMap((event) => event.data.resolutions)+ .some((resolution) => resolution.requestId === bob.requestId),+ ).toBe(false);+ await session.respond([{ requestId: bob.requestId, text: "bob-comet" }]);+ const final = await waitFor(session, (events) =>+ filterEventsByType(events, "message.completed").some(+ (event) => event.data.message === "REMOTE_HITL_RESULT=alice-lantern,bob-comet",+ ),+ );+ expect(filterEventsByType(final, "session.failed")).toHaveLength(0);+ } catch (error) {+ throw new Error(+ `parent stdout:\n${parentServer?.stdout() ?? "not started"}\nparent stderr:\n${parentServer?.stderr() ?? "not started"}\nchild stdout:\n${childServer.stdout()}\nchild stderr:\n${childServer.stderr()}`,+ { cause: error },+ );+ } finally {+ await parentServer?.stop();+ await childServer.stop();+ }+ },+ TIMEOUT,+);++it(+ "continues a parked remote child with its earlier conversation",+ async () => {+ const child = await scenarioApp(memoryChildDescriptor);+ const childServer = await startScriptedEveDev(child.appRoot);+ let parentServer: RunningServer | undefined;+ try {+ const parent = await scenarioApp(memoryParentDescriptor(childServer.url));+ parentServer = await startScriptedEveDev(parent.appRoot);+ const { session, response } = await new Client({ host: parentServer.url }).sessions.create({+ message: "Ask the remote child to remember and recall the codeword.",+ });+ expect((await response.result()).status).toBe("waiting");+ const final = await waitFor(session, (events) =>+ filterEventsByType(events, "message.completed").some(+ (event) => event.data.message === "PARENT_RECALLED=LANTERN-COMET-7319",+ ),+ );+ expect(filterEventsByType(final, "session.failed")).toHaveLength(0);+ const starts = filterEventsByType(final, "agent.started");+ expect(starts).toHaveLength(1);+ const remoteClient = new Client({ host: childServer.url, auth: { bearer: TOKEN } });+ const childSnapshot = await remoteClient.sessions+ .attach(starts[0]!.data.sessionId)+ .snapshot();+ expect(filterEventsByType(childSnapshot.events, "turn.started")).toHaveLength(2);+ expect(filterEventsByType(childSnapshot.events, "session.failed")).toHaveLength(0);+ } catch (error) {+ throw new Error(+ `parent stdout:\n${parentServer?.stdout() ?? "not started"}\nparent stderr:\n${parentServer?.stderr() ?? "not started"}\nchild stdout:\n${childServer.stdout()}\nchild stderr:\n${childServer.stderr()}`,+ { cause: error },+ );+ } finally {+ await parentServer?.stop();+ await childServer.stop();+ }+ },+ TIMEOUT,+);++async function waitFor(+ session: ClientSession,+ ready: (events: readonly HandleMessageStreamEvent[]) => boolean,+) {+ const deadline = Date.now() + 30_000;+ let events: readonly HandleMessageStreamEvent[] = [];+ while (Date.now() < deadline) {+ ({ events } = await session.snapshot());+ if (ready(events)) return events;+ await new Promise((r) => setTimeout(r, 100));+ }+ throw new Error(`Timed out waiting for events: ${JSON.stringify(events)}`);+}++async function startScriptedEveDev(root: string): Promise<RunningServer> {+ const child = spawn(+ process.execPath,+ [+ join(root, "node_modules/eve/bin/eve.js"),+ "dev",+ "--no-ui",+ "--host",+ "127.0.0.1",+ "--port",+ "0",+ ],+ {+ cwd: root,+ env: { ...process.env, EVE_MOCK_AUTHORED_MODELS: "", NODE_ENV: "production" },+ stdio: ["ignore", "pipe", "pipe"],+ },+ );+ let stdout = "",+ stderr = "";+ child.stdout.setEncoding("utf8");+ child.stderr.setEncoding("utf8");+ child.stdout.on("data", (x: string) => {+ stdout += x;+ });+ child.stderr.on("data", (x: string) => {+ stderr += x;+ });+ const url = await new Promise<string>((resolve, reject) => {+ const timer = setTimeout(+ () => reject(new Error(`startup timeout\n${stdout}\n${stderr}`)),+ 30_000,+ );+ const inspect = () => {+ const match = /\[DEV\] server listening at (http:\/\/[^\s]+)/u.exec(stdout);+ if (match?.[1]) {+ clearTimeout(timer);+ resolve(match[1]);+ }+ };+ child.stdout.on("data", inspect);+ child.once("exit", (code) => reject(new Error(`server exited ${code}\n${stdout}\n${stderr}`)));+ });+ return {+ url,+ stdout: () => stdout,+ stderr: () => stderr,+ async stop() {+ if (child.exitCode !== null) return;+ await new Promise<void>((resolve) => {+ child.once("exit", () => resolve());+ child.kill("SIGTERM");+ });+ },+ };+}diff --git a/packages/eve/src/execution/tools/workflow/messages.ts b/packages/eve/src/execution/tools/workflow/messages.tsindex e391bec1f..dd470c55a 100644--- a/packages/eve/src/execution/tools/workflow/messages.ts+++ b/packages/eve/src/execution/tools/workflow/messages.ts@@ -1,4 +1,6 @@import type { SubagentAuthorizationEventHookPayload } from "#channel/types.js";+import type { SessionInboxAddress } from "#execution/session-inbox/address.js";+import type { RemoteAgentBinding } from "#eve-channel/support.js";import type { SessionAuth } from "#context/session-context.js";import type { AgentSessionContext } from "#execution/agent-sessions/context.js";import type { AgentSessionAddress } from "#execution/agent-sessions/steps.js";@@ -72,7 +74,10 @@ export interface WorkflowToolRunReport {}export interface WorkflowToolRunRequestMessage {+ readonly childSessionInbox?: SessionInboxAddress;+ readonly remote?: RemoteAgentBinding & { readonly sessionId: string };readonly from: WorkflowToolRunRef;+ readonly inputSource?: string;readonly replyTo: string;readonly request: WorkflowToolRequest;readonly requestCoordinates?: {diff --git a/packages/eve/src/execution/tools/workflow/owner-inbox.test.ts b/packages/eve/src/execution/tools/workflow/owner-inbox.test.tsindex d7e0a7e9b..60be78d41 100644--- a/packages/eve/src/execution/tools/workflow/owner-inbox.test.ts+++ b/packages/eve/src/execution/tools/workflow/owner-inbox.test.ts@@ -46,6 +46,23 @@ describe("workflow-tool task input", () => {});});+ it("keeps the producer identity when forwarding a child request", () => {+ const request = {+ action: { callId: "child-call", input: {}, kind: "tool-call" as const, toolName: "ask" },+ kind: "question" as const,+ prompt: "What is Alice's answer?",+ requestId: "alice-ask",+ };+ expect(+ workflowToolRunRequestToInputRequestPayload({+ from,+ inputSource: "child:alice",+ replyTo: "child-inbox",+ request,+ }),+ ).toMatchObject({ inputSource: "child:alice", event: { requests: [request] } });+ });+it("uses child event coordinates for repeated forwarded requests", () => {const request = {action: {diff --git a/packages/eve/src/execution/tools/workflow/owner-inbox.ts b/packages/eve/src/execution/tools/workflow/owner-inbox.tsindex 2759252fa..dafe4a303 100644--- a/packages/eve/src/execution/tools/workflow/owner-inbox.ts+++ b/packages/eve/src/execution/tools/workflow/owner-inbox.ts@@ -72,6 +72,9 @@ export function workflowToolRunRequestToInputRequestPayload(callId: from.callId,childContinuationToken: replyTo,childSessionId: from.runId,+ childSessionInbox: message.childSessionInbox,+ remote: message.remote,+ inputSource: message.inputSource,event: {requests: workflowToolRunInputRequests(message),sequence: requestCoordinates?.sequence ?? from.sequence,diff --git a/packages/eve/src/harness/proxy-input-requests.test.ts b/packages/eve/src/harness/proxy-input-requests.test.tsindex 782785a32..d9a54c13b 100644--- a/packages/eve/src/harness/proxy-input-requests.test.ts+++ b/packages/eve/src/harness/proxy-input-requests.test.ts@@ -82,6 +82,72 @@ describe("upsertProxyInputRequests", () => {});});+ it("keeps independent questions at the same answer destination", () => {+ let session = upsertProxyInputRequests({+ entries: [+ [+ "alice",+ {+ childContinuationToken: "shared-inbox",+ inputSource: "workflow-alice",+ event: REQUEST_EVENT,+ kind: "question",+ },+ ],+ ],+ forChildContinuationToken: "shared-inbox",+ inputSource: "workflow-alice",+ session: createSession(),+ });+ session = upsertProxyInputRequests({+ entries: [+ [+ "bob",+ {+ childContinuationToken: "shared-inbox",+ inputSource: "workflow-bob",+ event: REQUEST_EVENT,+ kind: "question",+ },+ ],+ ],+ forChildContinuationToken: "shared-inbox",+ inputSource: "workflow-bob",+ session,+ });++ expect([...getProxyInputRequests(session.state).keys()]).toEqual(["alice", "bob"]);+ });++ it("preserves remote response coordinates through a durable proxy snapshot", () => {+ const remote = {+ name: "research",+ resolverId: "subagents/research.ts",+ sessionId: "remote-child-session",+ url: "https://remote.example.com",+ };+ const payload: SubagentInputRequestHookPayload = {+ callId: "call-1",+ childContinuationToken: "remote-reply",+ childSessionId: "remote-child-session",+ event: { requests: [createRequest("req-remote", "question")], ...REQUEST_EVENT },+ kind: "subagent-input-request",+ remote,+ subagentName: "research",+ };+ const session = upsertProxyInputRequests({+ entries: toProxyInputRequestEntries(payload),+ forChildContinuationToken: payload.childContinuationToken,+ session: createSession(),+ });+ expect(+ getProxyInputRequests(JSON.parse(JSON.stringify(session.state))).get("req-remote"),+ ).toMatchObject({+ remote,+ childContinuationToken: "remote-reply",+ });+ });+it("drops a prior child's batch when its request ID is claimed by another child", () => {let session = upsertProxyInputRequests({entries: [diff --git a/packages/eve/src/harness/proxy-input-requests.ts b/packages/eve/src/harness/proxy-input-requests.tsindex 253e91b9f..91aad3255 100644--- a/packages/eve/src/harness/proxy-input-requests.ts+++ b/packages/eve/src/harness/proxy-input-requests.ts@@ -6,6 +6,7 @@ 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";@@ -35,6 +36,8 @@ export interface ProxyInputQuestion {/** Routing and control metadata for one descendant-owned input request. */export interface ProxyInputRequest {+ readonly remote?: RemoteAgentBinding & { readonly sessionId: string };+ readonly inputSource?: string;readonly workflowAsk?: WorkflowAskRoute;/** Batch semantics are optional so sessions written before this field remain routable. */readonly batch?: ProxyInputRequestBatch;@@ -80,12 +83,13 @@ export function hasProxyInputRequests(state: SessionStateMap | undefined): boole}/**- * Replaces prior entries for `forChildContinuationToken` with the provided+ * 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 children's routes stay+ * parent never keeps stale request metadata. Other sources' routes stay* independently answerable.*/export function upsertProxyInputRequests(input: {+ readonly inputSource?: string;readonly entries: readonly (readonly [requestId: string, route: ProxyInputRequest])[];readonly forChildContinuationToken: string;readonly session: HarnessSession;@@ -95,6 +99,7 @@ export function upsertProxyInputRequests(input: {state: upsertProxyInputRequestState({entries: input.entries,forChildContinuationToken: input.forChildContinuationToken,+ inputSource: input.inputSource,state: input.session.state,}),};@@ -102,6 +107,7 @@ export function upsertProxyInputRequests(input: {/** 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;@@ -109,7 +115,10 @@ export function upsertProxyInputRequestState(input: {const next: Record<string, ProxyInputRequest> = {};for (const [requestId, route] of Object.entries(readMap(input.state))) {- if (route.childContinuationToken !== input.forChildContinuationToken) {+ if (+ route.childContinuationToken !== input.forChildContinuationToken ||+ route.inputSource !== input.inputSource+ ) {next[requestId] = route;}}@@ -198,6 +207,8 @@ export function toProxyInputRequestEntries(return payload.event.requests.map((request) => {const route: {readonly childContinuationToken: string;+ readonly inputSource?: string;+ readonly remote?: RemoteAgentBinding & { readonly sessionId: string };childSessionInbox?: SessionInboxAddress;readonly event: PendingInputBatchEvent;readonly kind: InputRequestKind;@@ -205,6 +216,8 @@ export function toProxyInputRequestEntries(} & { readonly batch: ProxyInputRequestBatch } = {batch,childContinuationToken: payload.childContinuationToken,+ ...(payload.inputSource !== undefined && { inputSource: payload.inputSource }),+ ...(payload.remote !== undefined && { remote: payload.remote }),event,kind: request.kind,};@@ -267,6 +280,11 @@ function parseProxyInputRequest(value: unknown, requestId: string): ProxyInputReif (typeof value.childContinuationToken !== "string" || !isInputRequestKind(value.kind)) {return undefined;}+ const remote = "remote" in value ? parseRemoteAgentBinding(value.remote) : undefined;+ if ("remote" in value && remote === undefined) return undefined;+ const inputSource = "inputSource" in value ? value.inputSource : undefined;+ if (inputSource !== undefined && (typeof inputSource !== "string" || inputSource.length === 0))+ return undefined;const event = "event" in value ? parseInputRequestEvent(value.event) : undefined;if (event === undefined) return undefined;const batch = "batch" in value ? parseProxyInputRequestBatch(value.batch) : undefined;@@ -281,6 +299,8 @@ function parseProxyInputRequest(value: unknown, requestId: string): ProxyInputReworkflowAsk?: WorkflowAskRoute;batch?: ProxyInputRequestBatch;readonly childContinuationToken: string;+ inputSource?: string;+ remote?: RemoteAgentBinding & { readonly sessionId: string };childSessionInbox?: SessionInboxAddress;readonly event: PendingInputBatchEvent;readonly kind: InputRequestKind;@@ -290,6 +310,8 @@ function parseProxyInputRequest(value: unknown, requestId: string): ProxyInputReevent,kind: value.kind,};+ if (typeof inputSource === "string") request.inputSource = inputSource;+ if (remote !== undefined) request.remote = remote;if (workflowAsk !== undefined) request.workflowAsk = workflowAsk;if (childSessionInbox !== undefined) request.childSessionInbox = childSessionInbox;if (batch !== undefined && batch.requestIds.includes(requestId)) request.batch = batch;@@ -318,6 +340,35 @@ function parseWorkflowAskRoute(value: unknown): WorkflowAskRoute | undefined {return { control, question, runId };}+function parseRemoteAgentBinding(+ value: unknown,+): (RemoteAgentBinding & { readonly sessionId: string }) | undefined {+ if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined;+ const name = Reflect.get(value, "name");+ const url = Reflect.get(value, "url");+ const resolverId = Reflect.get(value, "resolverId");+ const forwardPrincipal = Reflect.get(value, "forwardPrincipal");+ const sessionId = Reflect.get(value, "sessionId");+ if (+ typeof name !== "string" ||+ !name ||+ typeof url !== "string" ||+ !url ||+ typeof sessionId !== "string" ||+ !sessionId+ )+ return undefined;+ if (resolverId !== undefined && (typeof resolverId !== "string" || !resolverId)) return undefined;+ if (forwardPrincipal !== undefined && typeof forwardPrincipal !== "boolean") return undefined;+ return {+ name,+ url,+ sessionId,+ ...(resolverId !== undefined && { resolverId }),+ ...(forwardPrincipal !== undefined && { forwardPrincipal }),+ };+}+function parseProxyInputQuestion(value: unknown): ProxyInputQuestion | undefined {if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined;const question: {diff --git a/packages/eve/src/public/channels/eve.test.ts b/packages/eve/src/public/channels/eve.test.tsindex 5fcc1cfda..a65354c06 100644--- a/packages/eve/src/public/channels/eve.test.ts+++ b/packages/eve/src/public/channels/eve.test.ts@@ -28,6 +28,7 @@ import {type Session as RuntimeSession,} from "#context/keys.js";import { createMessageCompletedEvent } from "#protocol/message.js";+import { writeForwardedParentSessionBaggage } from "#protocol/baggage.js";import { captureLogRecords } from "#internal/testing/log-records.js";/**@@ -958,6 +959,59 @@ describe("eveChannel — create session idempotency", () => {expect(handler.resolveSession).toHaveBeenCalledWith(token);});+ it("exposes a trusted remote invocation identity only for delegated creates", async () => {+ const invocations: unknown[] = [];+ const handler = createEveCreateHandler({+ auth: () => ACCEPTED_AUTH,+ trustedForwarders: () => true,+ onMessage(ctx) {+ invocations.push(ctx.eve.invocation);+ return { auth: ctx.eve.caller };+ },+ });+ const request = createJsonMessageRequest({+ callback: {+ callId: "call-1",+ subagentName: "research",+ token: "tok123",+ url: "https://caller.example.com/eve/v1/callback/tok123",+ },+ message: "hi",+ operationId: "remote-operation-1",+ protocolVersion: REMOTE_AGENT_PROTOCOL_VERSION,+ });+ request.headers.set(+ "baggage",+ writeForwardedParentSessionBaggage(undefined, {+ callId: "call-1",+ rootSessionId: "root-session",+ sessionId: "parent-session",+ turn: { id: "parent-turn", sequence: 1 },+ })!,+ );+ expect((await handler.fetch(request)).status).toBe(202);+ expect((await handler.fetch(createJsonMessageRequest({ message: "hi" }))).status).toBe(202);+ expect(invocations).toEqual([{ operationId: "remote-operation-1" }, undefined]);++ const noLineage = createEveCreateHandler({+ auth: () => ACCEPTED_AUTH,+ onMessage(ctx) {+ expect(ctx.eve.invocation).toBeUndefined();+ return { auth: ctx.eve.caller };+ },+ });+ expect(+ (+ await noLineage.fetch(+ createJsonMessageRequest({+ message: "hi",+ operationId: "ordinary-operation",+ }),+ )+ ).status,+ ).toBe(202);+ });+it("returns the existing child for a replayed operation without dispatching again", async () => {const handler = createEveCreateHandler({ auth: () => ACCEPTED_AUTH },@@ -2398,6 +2452,33 @@ describe("eveChannel — forwarded principal", () => {expect(handler.send).not.toHaveBeenCalled();});+ it("attributes a trusted remote input response to the forwarded human", async () => {+ const handler = createEveContinueHandler({+ auth: () => ROUTER_CALLER,+ trustedForwarders: (forwarder) => forwarder.principalId === ROUTER_CALLER.principalId,+ });+ const response = await handler.fetch(+ new Request("https://example.com/eve/v1/session/test-session-id", {+ body: JSON.stringify({+ forwardedPrincipal: { current: FORWARDED_CURRENT },+ inputResponses: [{ requestId: "approval-1", optionId: "approve" }],+ }),+ headers: { "content-type": "application/json" },+ method: "POST",+ }),+ );+ expect(response.status).toBe(202);+ expect(handler.respond).toHaveBeenCalledWith(+ [{ requestId: "approval-1", optionId: "approve" }],+ expect.objectContaining({+ auth: expect.objectContaining({+ principalId: FORWARDED_CURRENT.principalId,+ attributes: expect.objectContaining({ "eve:forwarded-by": ROUTER_CALLER.principalId }),+ }),+ }),+ );+ });+it("rejects a forwarded continuation when the channel has no trustedForwarders", async () => {const handler = createEveContinueHandler({ auth: () => ROUTER_CALLER });diff --git a/packages/eve/src/subagents/adapter.ts b/packages/eve/src/subagents/adapter.tsindex e325b2aef..97a36f48e 100644--- a/packages/eve/src/subagents/adapter.ts+++ b/packages/eve/src/subagents/adapter.ts@@ -45,6 +45,7 @@ export const SUBAGENT_ADAPTER: ChannelAdapter = {childContinuationToken: ctx.ctx.require(ContinuationTokenKey),childSessionId: ctx.ctx.require(SessionIdKey),childSessionInbox: ctx.ctx.get(SessionInboxKey),+ inputSource: ctx.inputSource,event: {requests: data.requests,sequence: data.sequence,diff --git a/packages/eve/src/subagents/callback-route.test.ts b/packages/eve/src/subagents/callback-route.test.tsindex 3b802a7c4..006fb5814 100644--- a/packages/eve/src/subagents/callback-route.test.ts+++ b/packages/eve/src/subagents/callback-route.test.ts@@ -54,6 +54,136 @@ describe("session callback route", () => {});});+ it("relays a remote child's question to the waiting parent", async () => {+ resumeHookMock.mockResolvedValue(undefined);+ const input = {+ callId: "call-2",+ childContinuationToken: "child-inbox",+ childSessionId: "remote-session",+ event: {+ requests: [+ {+ action: { callId: "ask-1", input: {}, kind: "tool-call", toolName: "ask_question" },+ kind: "question",+ prompt: "What should Alice do?",+ requestId: "alice-1",+ },+ ],+ sequence: 0,+ stepIndex: 1,+ turnId: "child-turn",+ },+ inputSource: "alice-run",+ kind: "subagent-input-request",+ subagentName: "research",+ };+ const response = await handleSessionCallbackRequest(+ new Request("https://app.example.com/eve/v1/callback/tok123", {+ body: JSON.stringify(input),+ method: "POST",+ }),+ createRouteContext({ token: "tok123" }),+ );+ expect(response.status).toBe(202);+ expect(resumeHookMock).toHaveBeenCalledWith("tok123", input);+ });++ it("relays remote authorization lifecycle without settling the turn", async () => {+ resumeHookMock.mockResolvedValue(undefined);+ const event = {+ type: "authorization.required",+ data: {+ attemptId: "auth-1",+ description: "Sign in to Linear",+ name: "linear",+ sequence: 0,+ stepIndex: 1,+ turnId: "child-turn",+ webhookUrl: "https://remote.example/connections/linear/callback/child",+ },+ };+ const payload = {+ callId: "call-2",+ childSessionId: "remote-session",+ event,+ kind: "subagent-authorization-event",+ subagentName: "research",+ };+ const response = await handleSessionCallbackRequest(+ new Request("https://app.example.com/eve/v1/callback/tok123", {+ body: JSON.stringify(payload),+ method: "POST",+ }),+ createRouteContext({ token: "tok123" }),+ );+ expect(response.status).toBe(202);+ expect(resumeHookMock).toHaveBeenCalledWith("tok123", payload);+ });++ it.each(["approval.candidate", "approval.settled"])(+ "rejects a malformed %s callback before it reaches the parent channel",+ async (type) => {+ const response = await handleSessionCallbackRequest(+ new Request("https://app.example.com/eve/v1/callback/tok123", {+ body: JSON.stringify({+ callId: "call-2",+ childSessionId: "remote-session",+ event: { type, data: {} },+ kind: "subagent-authorization-event",+ subagentName: "research",+ }),+ method: "POST",+ }),+ createRouteContext({ token: "tok123" }),+ );+ expect(response.status).toBe(400);+ expect(resumeHookMock).not.toHaveBeenCalled();+ },+ );++ it("relays a well-formed approval settlement", async () => {+ resumeHookMock.mockResolvedValue(undefined);+ const event = {+ type: "approval.settled",+ data: {+ outcome: "approved",+ requestId: "approval-1",+ responderPrincipalId: "alice",+ sequence: 0,+ stepIndex: 1,+ turnId: "child-turn",+ },+ };+ const payload = {+ callId: "call-2",+ childSessionId: "remote-session",+ event,+ kind: "subagent-authorization-event",+ subagentName: "research",+ };+ const response = await handleSessionCallbackRequest(+ new Request("https://app.example.com/eve/v1/callback/tok123", {+ body: JSON.stringify(payload),+ method: "POST",+ }),+ createRouteContext({ token: "tok123" }),+ );+ expect(response.status).toBe(202);+ expect(resumeHookMock).toHaveBeenCalledWith("tok123", payload);+ });++ it("rejects malformed remote input without resuming the parent", async () => {+ const response = await handleSessionCallbackRequest(+ new Request("https://app.example.com/eve/v1/callback/tok123", {+ body: JSON.stringify({ kind: "subagent-input-request", childContinuationToken: "child" }),+ method: "POST",+ }),+ createRouteContext({ token: "tok123" }),+ );+ expect(response.status).toBe(400);+ expect(resumeHookMock).not.toHaveBeenCalled();+ });+it("rejects a turn callback without an outcome envelope", async () => {const response = await handleSessionCallbackRequest(new Request("https://app.example.com/eve/v1/callback/tok123", {diff --git a/packages/eve/src/subagents/callback-route.ts b/packages/eve/src/subagents/callback-route.tsindex 9e3412c0d..d099756bc 100644--- a/packages/eve/src/subagents/callback-route.ts+++ b/packages/eve/src/subagents/callback-route.ts@@ -2,21 +2,109 @@ import { resumeHook } from "#internal/workflow/runtime.js";import { z } from "#compiled/zod/index.js";import type { RouteContext } from "#public/definitions/channel.js";import type { RuntimeSubagentChildResult } from "#shared/action-types.js";+import { inputRequestSchema } from "#shared/input.js";import { agentTurnOutcomeWithCostSchema } from "#shared/agent-turn-outcome.js";import { jsonValueSchema } from "#shared/json-schemas.js";-// Wire schemas of the child→parent callback route. Possession of the-// callback token is the authorization to settle; results bind to the-// pending call by callId. `sessionId` is informational (tracing and-// diagnostics) and never verified — new senders emit it, older eve-// deployments may omit it.+// The callback token grants access to the pending turn. Validate remote input+// before handing it to the parent; the child session ID is not authority.+const sessionInputCallbackSchema = z.object({+ callId: z.string().min(1),+ childContinuationToken: z.string().min(1),+ childSessionId: z.string().min(1),+ childSessionInbox: z+ .object({ sessionId: z.string().min(1) })+ .strict()+ .optional(),+ inputSource: z.string().min(1).optional(),+ remote: z+ .object({+ name: z.string().min(1),+ url: z.string().url(),+ forwardPrincipal: z.boolean().optional(),+ sessionId: z.string().min(1),+ resolverId: z.string().min(1).optional(),+ })+ .strict()+ .optional(),+ kind: z.literal("subagent-input-request"),+ subagentName: z.string().min(1),+ event: z.object({+ requests: z.array(inputRequestSchema).min(1),+ sequence: z.number(),+ stepIndex: z.number(),+ taskId: z.string().optional(),+ turnId: z.string(),+ }),+});++const sessionAuthorizationCallbackSchema = z.object({+ callId: z.string().min(1),+ childSessionId: z.string().min(1),+ kind: z.literal("subagent-authorization-event"),+ subagentName: z.string().min(1),+ event: z.discriminatedUnion("type", [+ z.object({+ type: z.literal("approval.candidate"),+ data: z+ .object({+ candidateId: z.string(),+ outcome: z.enum(["pending", "rejected", "failed", "timed-out", "stale"]),+ requestId: z.string(),+ responderPrincipalId: z.string(),+ reason: z.string().optional(),+ sequence: z.number(),+ stepIndex: z.number(),+ turnId: z.string(),+ })+ .passthrough(),+ }),+ z.object({+ type: z.literal("approval.settled"),+ data: z+ .object({+ outcome: z.enum(["approved", "cancelled"]),+ requestId: z.string(),+ responderPrincipalId: z.string(),+ sequence: z.number(),+ stepIndex: z.number(),+ turnId: z.string(),+ })+ .passthrough(),+ }),+ z.object({+ type: z.literal("authorization.required"),+ data: z+ .object({+ description: z.string(),+ name: z.string(),+ sequence: z.number(),+ stepIndex: z.number(),+ turnId: z.string(),+ webhookUrl: z.string().optional(),+ attemptId: z.string().optional(),+ taskId: z.string().optional(),+ })+ .passthrough(),+ }),+ z.object({+ type: z.literal("authorization.completed"),+ data: z+ .object({+ name: z.string(),+ outcome: z.enum(["authorized", "declined", "failed", "timed-out"]),+ sequence: z.number(),+ stepIndex: z.number(),+ turnId: z.string(),+ attemptId: z.string().optional(),+ taskId: z.string().optional(),+ })+ .passthrough(),+ }),+ ]),+});-/**- * Turn callbacks must carry the explicit `AgentTurnOutcome` envelope:- * the receiving parent settles the child's handle from `outcome.kind`, so- * a turn callback that cannot state its lifecycle is rejected rather than- * guessed at (pre-1.0: no wire compatibility shims).- */+/** A settled remote turn must state its outcome; callers do not infer its lifecycle. */const sessionResultCallbackSchema = z.discriminatedUnion("kind", [z.object({callId: z.string().min(1),@@ -50,16 +138,24 @@ export async function handleSessionCallbackRequest(return Response.json({ error: "Invalid JSON body.", ok: false }, { status: 400 });}- const result = projectSessionCallbackResult(body);- if (result instanceof Response) {- return result;+ const kind = callbackKind(body);+ const forwarded =+ kind === "subagent-input-request"+ ? sessionInputCallbackSchema.safeParse(body)+ : kind === "subagent-authorization-event"+ ? sessionAuthorizationCallbackSchema.safeParse(body)+ : undefined;+ if (forwarded !== undefined && !forwarded.success) {+ return Response.json({ error: "Invalid session input callback.", ok: false }, { status: 400 });}+ const result = forwarded === undefined ? projectSessionCallbackResult(body) : undefined;+ if (result instanceof Response) return result;try {- await resumeHook(token, {- kind: "runtime-action-result",- results: [result],- });+ await resumeHook(+ token,+ forwarded?.success ? forwarded.data : { kind: "runtime-action-result", results: [result] },+ );} catch {return Response.json({ error: "Session callback not pending.", ok: false }, { status: 404 });}diff --git a/packages/eve/src/subagents/event-proxy-step.integration.test.ts b/packages/eve/src/subagents/event-proxy-step.integration.test.tsindex 1f7772241..b01e88658 100644--- a/packages/eve/src/subagents/event-proxy-step.integration.test.ts+++ b/packages/eve/src/subagents/event-proxy-step.integration.test.ts@@ -3,9 +3,17 @@ import { describe, expect, it, vi } from "vitest";import type { ChannelAdapter } from "#channel/adapter.js";import type { SubagentInputRequestHookPayload } from "#channel/types.js";import { ContextContainer } from "#context/container.js";-import { AuthKey, ContinuationTokenKey, SessionIdKey } from "#context/keys.js";+import {+ AuthKey,+ ContinuationTokenKey,+ SessionCallbackKey,+ SessionIdKey,+ SessionInboxKey,+} from "#context/keys.js";import type { DurableSession } from "#execution/durable-session-store.js";+import { createSessionEventSink } from "#execution/publish-session-events.js";import { createSessionLimitContinuationRequest } from "#harness/session-limit-continuation.js";+import { getProxyInputRequests } from "#harness/proxy-input-requests.js";import type { MessageStreamEvent } from "#protocol/message.js";import type { HookContext } from "#public/definitions/hook.js";import { createRuntimeHookRegistry } from "#runtime/hooks/registry.js";@@ -164,6 +172,271 @@ describe("proxied stream hooks", () => {]);});+ it("forwards a remote session's own input without asking on its channel", async () => {+ const f = fixture();+ f.ctx.set(SessionCallbackKey, {+ callId: "remote-call",+ subagentName: "remote-child",+ token: "parent-reply",+ url: "https://parent.example/eve/v1/callback/parent-reply",+ });+ const fetchMock = vi.fn(async (_url: string, _init: RequestInit) =>+ Response.json({ ok: true }, { status: 202 }),+ );+ vi.stubGlobal("fetch", fetchMock);+ const sink = createSessionEventSink({+ ctx: f.ctx,+ sessionId: "parent-session",+ sessionWritable: f.sessionWritable,+ });+ try {+ await sink.emit({ type: "input.requested", data: f.hookPayload.event });+ expect(fetchMock).toHaveBeenCalledOnce();+ const forwarded = JSON.parse(fetchMock.mock.calls[0]![1]!.body as string);+ expect(forwarded).toMatchObject({+ callId: "remote-call",+ childSessionId: "parent-session",+ event: { requests: [f.request] },+ kind: "subagent-input-request",+ });+ expect(f.order).not.toContain("channel:input.requested");+ expect(f.events.map((event) => event.type)).toEqual(["input.requested"]);+ } finally {+ sink.release();+ vi.unstubAllGlobals();+ }+ });++ it("forwards callback input without an operation ID through the session inbox", async () => {+ const f = fixture();+ f.ctx.delete(ContinuationTokenKey);+ f.ctx.set(SessionInboxKey, { sessionId: "parent-session" });+ f.ctx.set(SessionCallbackKey, {+ callId: "remote-call",+ subagentName: "remote-child",+ token: "parent-reply",+ url: "https://parent.example/eve/v1/callback/parent-reply",+ });+ const fetchMock = vi.fn(async (_url: string, _init: RequestInit) =>+ Response.json({ ok: true }, { status: 202 }),+ );+ vi.stubGlobal("fetch", fetchMock);+ const sink = createSessionEventSink({+ ctx: f.ctx,+ sessionId: "parent-session",+ sessionWritable: f.sessionWritable,+ });+ try {+ await sink.emit({ type: "input.requested", data: f.hookPayload.event });+ const forwarded = JSON.parse(fetchMock.mock.calls[0]![1]!.body as string);+ expect(forwarded).toMatchObject({+ childContinuationToken: "eve:session:parent-session:inbox",+ childSessionInbox: { sessionId: "parent-session" },+ kind: "subagent-input-request",+ });+ expect(f.order).not.toContain("channel:input.requested");+ } finally {+ sink.release();+ vi.unstubAllGlobals();+ }+ });++ it("forwards nested questions to the remote caller instead of its own channel", async () => {+ const f = fixture();+ f.ctx.set(SessionCallbackKey, {+ callId: "remote-call",+ subagentName: "remote-child",+ token: "parent-reply",+ url: "https://parent.example/eve/v1/callback/parent-reply",+ });+ const hookPayload = { ...f.hookPayload, inputSource: "nested-alice" };+ const fetchMock = vi.fn(async (_url: string, _init: RequestInit) =>+ Response.json({ ok: true }, { status: 202 }),+ );+ vi.stubGlobal("fetch", fetchMock);+ try {+ const result = await emitProxiedSubagentEvent({ ...f, hookPayload });+ expect(fetchMock).toHaveBeenCalledOnce();+ const forwarded = JSON.parse(fetchMock.mock.calls[0]![1]!.body as string);+ expect(forwarded).toMatchObject({+ childSessionId: "parent-session",+ event: { requests: [f.request] },+ kind: "subagent-input-request",+ });+ expect(forwarded.inputSource).toBe(JSON.stringify(["child-token", "nested-alice"]));+ expect(f.order).not.toContain("channel:input.requested");+ expect(f.events.map((event) => event.type)).toEqual(["input.requested", "turn.waiting"]);+ expect(result.sessionState.hasProxyInputRequests).toBe(true);++ const answer = { inputResponses: [{ requestId: f.request.requestId, optionId: "continue" }] };+ expect(+ routeDeliverPayload({ payload: answer, state: result.sessionState.snapshot.session.state }),+ ).toMatchObject({+ forSelf: undefined,+ forChildren: [+ {+ childContinuationToken: "child-token",+ payload: answer,+ },+ ],+ });+ } finally {+ vi.unstubAllGlobals();+ }+ });++ it("forwards a nested authorization interrupt through the remote callback", async () => {+ const f = fixture();+ f.ctx.set(SessionCallbackKey, {+ callId: "remote-call",+ subagentName: "remote-child",+ token: "parent-reply",+ url: "https://parent.example/eve/v1/callback/parent-reply",+ });+ const event = {+ type: "authorization.required" as const,+ data: {+ description: "Sign in to Linear",+ name: "linear",+ sequence: 7,+ stepIndex: 2,+ turnId: "nested-turn",+ webhookUrl: "https://child.example/connections/linear/callback/child-auth",+ },+ };+ const fetchMock = vi.fn(async (_url: string, _init: RequestInit) =>+ Response.json({ ok: true }, { status: 202 }),+ );+ vi.stubGlobal("fetch", fetchMock);+ try {+ await emitProxiedSubagentEvent({+ ...f,+ hookPayload: {+ callId: "nested-call",+ childSessionId: "nested-session",+ event,+ kind: "subagent-authorization-event",+ subagentName: "nested-child",+ },+ });+ expect(fetchMock).toHaveBeenCalledOnce();+ expect(JSON.parse(fetchMock.mock.calls[0]![1]!.body as string)).toMatchObject({+ childSessionId: "parent-session",+ event,+ kind: "subagent-authorization-event",+ });+ expect(f.events.map((published) => published.type)).toContain("authorization.required");+ } finally {+ vi.unstubAllGlobals();+ }+ });++ it("keeps two nested approval requests routable through the remote callback", async () => {+ const f = fixture();+ f.ctx.set(SessionCallbackKey, {+ callId: "remote-call",+ subagentName: "remote-child",+ token: "parent-reply",+ url: "https://parent.example/eve/v1/callback/parent-reply",+ });+ const fetchMock = vi.fn(async (_url: string, _init: RequestInit) =>+ Response.json({ ok: true }, { status: 202 }),+ );+ vi.stubGlobal("fetch", fetchMock);+ try {+ let session = f.durableSession;+ for (const name of ["Alice", "Bob"]) {+ const request = {+ action: {+ callId: `tool-${name}`,+ input: {},+ kind: "tool-call" as const,+ toolName: "create_issue",+ },+ kind: "tool-approval" as const,+ options: [{ id: "approve", label: "Approve" }],+ prompt: `Approve ${name}'s issue?`,+ requestId: `approval-${name}`,+ };+ const result = await emitProxiedSubagentEvent({+ ...f,+ durableSession: session,+ hookPayload: {+ ...f.hookPayload,+ childContinuationToken: `child-${name}`,+ childSessionId: `session-${name}`,+ event: { ...f.hookPayload.event, requests: [request] },+ },+ });+ session = result.sessionState.snapshot.session;+ }+ expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(+ fetchMock.mock.calls.map(([, init]) => {+ const payload = JSON.parse(init.body as string);+ return {+ requestId: payload.event.requests[0].requestId,+ inputSource: payload.inputSource,+ };+ }),+ ).toEqual(+ ["Alice", "Bob"].map((name) => ({+ requestId: `approval-${name}`,+ inputSource: JSON.stringify([`child-${name}`, null]),+ })),+ );+ expect([...getProxyInputRequests(session.state).keys()]).toEqual([+ "approval-Alice",+ "approval-Bob",+ ]);+ const routed = routeDeliverPayload({+ payload: {+ inputResponses: ["Alice", "Bob"].map((name) => ({+ requestId: `approval-${name}`,+ optionId: "approve",+ })),+ },+ state: session.state,+ });+ expect(+ routed.forChildren.map(({ childContinuationToken, payload }) => ({+ childContinuationToken,+ payload,+ })),+ ).toEqual(+ ["Alice", "Bob"].map((name) => ({+ childContinuationToken: `child-${name}`,+ payload: { inputResponses: [{ requestId: `approval-${name}`, optionId: "approve" }] },+ })),+ );+ } finally {+ vi.unstubAllGlobals();+ }+ });++ it("does not publish or retain a nested request when its remote callback fails", async () => {+ const f = fixture();+ f.ctx.set(SessionCallbackKey, {+ callId: "remote-call",+ subagentName: "remote-child",+ token: "parent-reply",+ url: "https://parent.example/eve/v1/callback/parent-reply",+ });+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => Response.json({ ok: false }, { status: 503 })),+ );+ try {+ await expect(emitProxiedSubagentEvent(f)).rejects.toThrow("HTTP 503");+ 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);+ } finally {+ vi.unstubAllGlobals();+ }+ });+it("isolates hook failures after publication and releases the writer", async () => {const f = fixture();f.typed.mockRejectedValueOnce(new Error("audit unavailable"));diff --git a/packages/eve/src/subagents/event-proxy-step.ts b/packages/eve/src/subagents/event-proxy-step.tsindex 7b640f2ac..0e95d958d 100644--- a/packages/eve/src/subagents/event-proxy-step.ts+++ b/packages/eve/src/subagents/event-proxy-step.ts@@ -59,6 +59,10 @@ export async function emitProxiedSubagentEvent(input: {durableSession: input.durableSession,origin: "relayed",sessionWritable: input.sessionWritable,+ inputSource:+ hookPayload.kind === "subagent-input-request"+ ? JSON.stringify([hookPayload.childContinuationToken, hookPayload.inputSource ?? null])+ : undefined,},async (emit, session) => {if (hookPayload.kind === "subagent-authorization-event") {@@ -80,6 +84,7 @@ export async function emitProxiedSubagentEvent(input: {? relayed.result: relayed.result.map(([requestId, route]) => [requestId, { ...route, workflowAsk }]),forChildContinuationToken: hookPayload.childContinuationToken,+ inputSource: hookPayload.inputSource,session: scopedSession,});}diff --git a/packages/eve/src/subagents/hitl-proxy.test.ts b/packages/eve/src/subagents/hitl-proxy.test.tsindex 4b855c621..c63deb6f0 100644--- a/packages/eve/src/subagents/hitl-proxy.test.ts+++ b/packages/eve/src/subagents/hitl-proxy.test.ts@@ -192,6 +192,69 @@ describe("routeDeliverPayload", () => {});});+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({+ entries: [+ [+ `ask-${name}`,+ {+ childContinuationToken: "remote-inbox",+ remote: {+ name: "remote-child",+ url: "https://remote.example",+ sessionId: "remote-session",+ },+ inputSource: `workflow-${name}`,+ event: { sequence: index, stepIndex: index + 1, turnId: `turn-${name}` },+ kind: "question",+ },+ ],+ ],+ forChildContinuationToken: "remote-inbox",+ inputSource: `workflow-${name}`,+ session,+ });+ }+ const routed = routeDeliverPayload({+ payload: {+ inputResponses: [+ { requestId: "ask-alice", text: "lantern" },+ { requestId: "ask-bob", text: "comet" },+ ],+ },+ state: session.state,+ });+ expect(routed.forChildren).toHaveLength(2);+ expect(routed.forChildren.map(({ resolved }) => resolved)).toEqual([+ {+ event: { sequence: 0, stepIndex: 1, turnId: "turn-alice" },+ resolutions: [+ {+ kind: "question",+ outcome: "answered",+ requestId: "ask-alice",+ response: { requestId: "ask-alice", text: "lantern" },+ },+ ],+ },+ {+ event: { sequence: 1, stepIndex: 2, turnId: "turn-bob" },+ resolutions: [+ {+ kind: "question",+ outcome: "answered",+ requestId: "ask-bob",+ response: { requestId: "ask-bob", text: "comet" },+ },+ ],+ },+ ]);+ });+});+describe("routeDeliverPayload message resolution", () => {function askSession(questions: ReadonlyArray<readonly [requestId: string, question: { allowFreeform?: boolean }]>,diff --git a/packages/eve/src/subagents/hitl-proxy.ts b/packages/eve/src/subagents/hitl-proxy.tsindex c79af8fb9..09ec260cc 100644--- a/packages/eve/src/subagents/hitl-proxy.ts+++ b/packages/eve/src/subagents/hitl-proxy.ts@@ -79,6 +79,8 @@ async function emitTurnWaiting(emit: HarnessEmitFn, session: HarnessSession): Pr/** One proxied-child bucket of a routed deliver payload. */export interface RoutedChildDelivery {readonly workflowAsk?: WorkflowAskRoute;+ readonly remote?: ProxyInputRequest["remote"];+ readonly inputSource?: string;readonly childContinuationToken: string;readonly childSessionInbox?: SessionInboxAddress;readonly payload: { readonly inputResponses: readonly InputResponse[] };@@ -111,6 +113,7 @@ export interface RoutedDeliverPayload {/** In-progress accumulation for one `forChildren` bucket. */interface ChildResponseBucket {readonly workflowAsk?: WorkflowAskRoute;+ readonly remote?: ProxyInputRequest["remote"];readonly childContinuationToken: string;readonly childSessionInbox?: SessionInboxAddress;/** A child's routes all come from its latest batch, so they share coordinates. */@@ -151,13 +154,20 @@ export function routeDeliverPayload(input: {let parentAction: RoutedDeliverPayload["parentAction"];const bucketFor = (route: ProxyInputRequest): ChildResponseBucket => {- const bucketKey = [route.childContinuationToken, route.childSessionInbox?.sessionId ?? ""].join(- "\0",- );+ const bucketKey = JSON.stringify([+ route.childContinuationToken,+ route.childSessionInbox?.sessionId ?? "",+ route.remote?.sessionId ?? "",+ route.event.sequence,+ route.event.stepIndex,+ route.event.turnId,+ route.inputSource ?? null,+ ]);const existing = responsesByChild.get(bucketKey);if (existing !== undefined) return existing;const bucket: ChildResponseBucket = {childContinuationToken: route.childContinuationToken,+ remote: route.remote,event: route.event,parentRequestIds: [],responses: [],@@ -196,6 +206,7 @@ export function routeDeliverPayload(input: {const forChildren = [...responsesByChild.values()].map(({workflowAsk,+ remote,childContinuationToken,childSessionInbox,event,@@ -227,6 +238,8 @@ export function routeDeliverPayload(input: {},...(childSessionInbox !== undefined && { childSessionInbox }),...(workflowAsk !== undefined && { workflowAsk }),+ ...(remote !== undefined && { remote }),+ ...(routes[0]?.inputSource !== undefined && { inputSource: routes[0].inputSource }),};},);