Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

[1/2] fix(eve): answer subagent approvals and limit prompts by text (#4387)

Ben Pankow04d47bc3c7ab
diff --git a/.changeset/proxied-text-replies.md b/.changeset/proxied-text-replies.md
new file mode 100644
index 000000000..ec42413a5
--- /dev/null
+++ b/.changeset/proxied-text-replies.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+A typed reply now answers a tool approval or session-limit prompt proxied from a subagent, the same way it answers a subagent's `ctx.ask()` question. On text-only channels such as Linq, Twilio, and Linear, replying `approve` or `continue` resumes the subagent instead of reaching the parent model while the subagent stays parked. When a subagent raises several prompts at once, each reply answers the first open one.
diff --git a/docs/concepts/sessions-runs-and-streaming.md b/docs/concepts/sessions-runs-and-streaming.md
index 9fd53fce9..d5803200b 100644
--- a/docs/concepts/sessions-runs-and-streaming.md
+++ b/docs/concepts/sessions-runs-and-streaming.md
@@ -219,7 +219,7 @@ Message sends default to `"steer"`. Before assistant output begins, eve interrup
If the session is waiting on a human-in-the-loop approval, respond with the channel’s Approve or Cancel controls. Text that doesn't match an option doesn't approve the call. From the person the turn serves, it steers the turn and cancels the approval, even when sent with `turnPolicy: "queue"`, since the turn can't end until that person acts; from anyone else, it waits until the turn ends. If they had already approved some calls in the batch, those calls still run. Cancelling the turn withdraws the approval, and a later answer to it approves nothing.
-A pending `ctx.ask()` question from a tool, such as `ask_question`, can be answered with plain text. When it is the only pending question, a message that matches an option answers it, and so does any message when the question allows free text. The stream records that message as `message.received`, carrying its delivery id, just before the `input.resolved` it produces. Otherwise eve does not guess which question the text addresses: the message follows the normal `turnPolicy`. A steering message withdraws the questions of the `execute` workflow tool calls the turn waits on, which resolve as `cancelled`; a task's questions stay open. Questions from subagents always need a structured response. Use structured responses to target requests unambiguously.
+A pending prompt, whether a `ctx.ask()` question from a tool such as `ask_question`, a tool approval, or a session-limit prompt, can be answered with plain text, including prompts proxied from a subagent. A message answers the first open prompt, as described in [Several requests at once](/docs/human-in-the-loop#several-requests-at-once): a reply that matches one of its options, such as `approve` or `continue`, answers it as if the sender had pressed that option, and so does any message when the prompt allows free text. Send one message per prompt to answer several. The stream records a message that answers a question as `message.received`, carrying its delivery id, just before the `input.resolved` it produces. A message that doesn't answer the first open prompt follows the normal `turnPolicy`. A steering message withdraws the questions of the `execute` workflow tool calls the turn waits on, which resolve as `cancelled`; a task's questions stay open. Use structured responses to target requests unambiguously.
A structured response matches any currently pending request by ID, not only the newest batch. It becomes stale only after that request was answered, cleared, or cancelled. eve delivers a stale response to the model as a new user message, and the model decides whether the old selection still matters. A stale approval never authorizes the earlier tool call; the model must request the action and approval again if they are still needed.
diff --git a/docs/subagents/index.mdx b/docs/subagents/index.mdx
index 8a90d3be6..02fe91ca5 100644
--- a/docs/subagents/index.mdx
+++ b/docs/subagents/index.mdx
@@ -229,7 +229,7 @@ By default, a subagent named `researcher` collides with an authored tool named `
Do not rely on subagent delegation by itself as an approval boundary. Put sensitive tools behind `approval`, connection approval, route/session authorization, or other controls wherever those tools can be called.
-Each delegated subagent spins up its own child session and stream. The parent stream carries the call's `task.started` and `task.settled` events, `agent.started` when the child session opens, plus interactive `input.requested`, `authorization.required`, and `authorization.completed` events proxied from descendants so the root channel can prompt the user. The parent emits `input.resolved` when it routes an answer back down to the descendant that asked. `task.settled` carries the child's reply as `output` when the call completes, or `error.message` when it fails, along with the same tool `name` and `kind: "agent"` as the call's `task.started`. To follow the child's other progress, pass the `agent.started` event to [`session.agent()`](./guides/client/streaming#follow-a-subagent) on a client session attached to the parent and follow the child with `stream()`. It reads `agent.started.data.streamPath`: the child's own session stream for a local child, or a parent-origin proxy for a remote child, which the parent authenticates to the remote deployment.
+Each delegated subagent spins up its own child session and stream. The parent stream carries the call's `task.started` and `task.settled` events, `agent.started` when the child session opens, plus interactive `input.requested`, `authorization.required`, and `authorization.completed` events proxied from descendants so the root channel can prompt the user. The parent emits `input.resolved` when it routes an answer back down to the descendant that asked. On text-only channels, a typed reply that matches an option of the first open prompt, such as `approve` for a tool approval or `continue` for a session limit, answers it as the person who typed it, so a person answers several proxied prompts one message at a time. `task.settled` carries the child's reply as `output` when the call completes, or `error.message` when it fails, along with the same tool `name` and `kind: "agent"` as the call's `task.started`. To follow the child's other progress, pass the `agent.started` event to [`session.agent()`](./guides/client/streaming#follow-a-subagent) on a client session attached to the parent and follow the child with `stream()`. It reads `agent.started.data.streamPath`: the child's own session stream for a local child, or a parent-origin proxy for a remote child, which the parent authenticates to the remote deployment.
`agent.started` carries the `callId` and `turnId` of the call that opened the session, the call's `taskId`, the agent `name`, and the child's `sessionId`. Later calls with the same `taskId` reach the same session and do not announce it again, so match a child to its calls by `taskId`. A session an authored workflow tool opens with `ctx.agent` is announced the same way, with its `taskId` only when the workflow tool call runs as a task.
diff --git a/docs/tools/human-in-the-loop.md b/docs/tools/human-in-the-loop.md
index 61304c217..84b095dbd 100644
--- a/docs/tools/human-in-the-loop.md
+++ b/docs/tools/human-in-the-loop.md
@@ -219,7 +219,7 @@ Approvals and questions share one protocol:
3. The run parks durably, for as long as it takes. The turn stays open: the stream emits `turn.waiting`, and after the answer the turn resumes under the same `turnId`. That `turn.waiting` carries `on: "input"`, since a person must act.
4. The client answers with `inputResponses` (structured, keyed by `requestId`) or a normal follow-up `message`. A follow-up whose text matches an option ID, option label, or numeric option index resolves automatically, including approval options such as `approve` and `cancel`.
-For `ctx.ask()` questions from tools, a follow-up message answers the first open request, as described in [Several requests at once](#several-requests-at-once). The message must match an option, or the question must allow free text. Otherwise the message follows the session's `turnPolicy`. A steering message, the default, aborts the `ctx.abortSignal` of each `execute` workflow tool call the turn waits on, so a question such a call asked, such as `ask_question`'s, is withdrawn and resolves as `cancelled`. The model reads the message once those calls settle. Questions from subagents need a structured response.
+For `ctx.ask()` questions from tools and prompts proxied from subagents, a follow-up message answers the first open request, as described in [Several requests at once](#several-requests-at-once). The message must match an option, or the question must allow free text. Otherwise the message follows the session's `turnPolicy`. A steering message, the default, aborts the `ctx.abortSignal` of each `execute` workflow tool call the turn waits on, so a question such a call asked, such as `ask_question`'s, is withdrawn and resolves as `cancelled`. The model reads the message once those calls settle.
Each request includes a `kind` discriminator: `tool-approval`, `question`, or
`session-limit`. Clients should use `kind` to choose behavior and presentation.
diff --git a/e2e/fixtures/agent-subagents-hitl/evals/proxied-approval-text-response.eval.ts b/e2e/fixtures/agent-subagents-hitl/evals/proxied-approval-text-response.eval.ts
new file mode 100644
index 000000000..c02b6d1c4
--- /dev/null
+++ b/e2e/fixtures/agent-subagents-hitl/evals/proxied-approval-text-response.eval.ts
@@ -0,0 +1,71 @@
+import { defineEval } from "eve/evals";
+import type { EveEvalContext, EveEvalSession, EveEvalTurn } from "eve/evals";
+
+const GOOG_PRICE = "178.92";
+
+/**
+ * A text-only channel can't press Approve, so a typed reply at the parent must
+ * settle the subagent's proxied tool approval rather than reach the parent model.
+ */
+export default defineEval({
+ tags: ["session-inbox"],
+ description: "Plain-text approve at the parent runs a delegated child's gated tool.",
+ timeoutMs: 90_000,
+
+ async test(t) {
+ const started = await t.send(
+ `Call the stock-price subagent exactly once with message 'Call the get_stock_price tool exactly once with ticker "GOOG". After it returns, do not call any tool again; return the result.'. After that single subagent call finishes, do not call any subagent or tool again; include the exact stock price in your final reply.`,
+ );
+ const blocked = await waitForInput(t, started.session, "get_stock_price");
+ const resumed = await blocked.send("approve");
+ resumed.noFailedActions();
+ const completed = resumed.message?.includes(GOOG_PRICE)
+ ? resumed
+ : await waitForMessage(t, blocked, GOOG_PRICE);
+ completed.messageIncludes(GOOG_PRICE);
+
+ t.calledSubagent("stock-price", { status: "completed", count: 1 });
+ t.noFailedActions();
+ },
+});
+
+async function waitForInput(
+ t: EveEvalContext,
+ initialSession: EveEvalSession,
+ toolName: string,
+): Promise<EveEvalSession> {
+ let session = initialSession;
+ for (let attempt = 0; attempt < 5; attempt += 1) {
+ if (session.pendingInputRequests.some((request) => request.action.toolName === toolName)) {
+ return session;
+ }
+ const live = watchNextTurn(t, session, "subagent input wait");
+ const turn = await live.result();
+ turn.noFailedActions();
+ session = live.session;
+ }
+ throw new Error(`Subagent did not surface input for tool "${toolName}" after five turns.`);
+}
+
+async function waitForMessage(
+ t: EveEvalContext,
+ initialSession: EveEvalSession,
+ marker: string,
+): Promise<EveEvalTurn> {
+ let session = initialSession;
+ for (let attempt = 0; attempt < 5; attempt += 1) {
+ const live = watchNextTurn(t, session, "subagent completion wait");
+ const turn = await live.result();
+ turn.noFailedActions();
+ if (turn.message?.includes(marker) === true) return turn;
+ session = live.session;
+ }
+ throw new Error(`Subagent result did not reach the parent after five turns.`);
+}
+
+function watchNextTurn(t: EveEvalContext, session: EveEvalSession, operation: string) {
+ if (session.sessionId === undefined || session.state === undefined) {
+ throw new Error(`${operation} has no parent session cursor.`);
+ }
+ return t.target.watchTurn(session.sessionId, { startIndex: session.state.streamIndex });
+}
diff --git a/packages/eve/src/execution/proxied-deliver-step.ts b/packages/eve/src/execution/proxied-deliver-step.ts
index abd8dfcdb..23798f9e9 100644
--- a/packages/eve/src/execution/proxied-deliver-step.ts
+++ b/packages/eve/src/execution/proxied-deliver-step.ts
@@ -92,13 +92,13 @@ async function routeProxiedDeliver(
const parentPayloads = new Map<number, DeliverPayload>();
const children = new Map<string, ChildBucket>();
let parentAction: { readonly kind: "cancel-turn" } | undefined;
- // Only a person's own message may answer or skip a pending question.
+ // Only a person's own message may answer a pending prompt by text.
const resolveMessage =
!hasDelegatedSessionContext(serializedContext) && sourceDelivery.caller === undefined;
- // Every payload routes against the same state, so a `ctx.ask()` question
- // resolved by an earlier payload is hidden from later ones; its run takes
- // one answer, and later messages must reach the parent instead.
- const resolvedQuestions = new Set<string>();
+ // Every payload routes against the same state, so a request a `ctx.ask()`
+ // answer or typed reply resolved in an earlier payload is hidden from later
+ // ones; it takes one answer, and later messages must reach the parent instead.
+ const resolvedRequests = new Set<string>();
// A message that answers a question is still the person's turn in the
// conversation, so the stream records it with its delivery ids.
const answerMessages: UnstampedMessageStreamEvent[] = [];
@@ -106,7 +106,7 @@ async function routeProxiedDeliver(
for (const [sourcePayloadIndex, payload] of sourceDelivery.payloads.entries()) {
const routed = routeDeliverPayload({
- allowRoute: (requestId) => !resolvedQuestions.has(requestId),
+ allowRoute: (requestId) => !resolvedRequests.has(requestId),
payload,
resolveMessage,
state: durableSession.state,
@@ -115,8 +115,8 @@ async function routeProxiedDeliver(
if (routed.forSelf !== undefined) parentPayloads.set(sourcePayloadIndex, routed.forSelf);
for (const [childIndex, forChild] of routed.forChildren.entries()) {
- if (forChild.workflowAsk !== undefined) {
- for (const { requestId } of forChild.resolved.resolutions) resolvedQuestions.add(requestId);
+ if (forChild.workflowAsk !== undefined || forChild.message !== undefined) {
+ for (const { requestId } of forChild.resolved.resolutions) resolvedRequests.add(requestId);
}
if (forChild.message !== undefined) {
const { sequence, turnId } = forChild.resolved.event;
diff --git a/packages/eve/src/execution/publish-session-events.integration.test.ts b/packages/eve/src/execution/publish-session-events.integration.test.ts
index 36d83d972..abe05ce66 100644
--- a/packages/eve/src/execution/publish-session-events.integration.test.ts
+++ b/packages/eve/src/execution/publish-session-events.integration.test.ts
@@ -89,7 +89,8 @@ it("relays a withdrawn workflow question's input.resolved to the stream and its
[
"ask-1",
{
- workflowAsk: { control: "control", question: {} },
+ workflowAsk: { control: "control" },
+ reply: {},
runId: "run-1",
childContinuationToken: "ask-1",
event: { sequence: 1, stepIndex: 0, turnId: "turn-1" },
diff --git a/packages/eve/src/execution/session-workflow-tool-run.ts b/packages/eve/src/execution/session-workflow-tool-run.ts
index 811758bfd..bfd471273 100644
--- a/packages/eve/src/execution/session-workflow-tool-run.ts
+++ b/packages/eve/src/execution/session-workflow-tool-run.ts
@@ -150,12 +150,5 @@ async function handleWorkflowToolRunWithdraw(
}
function createWorkflowAskRoute(ask: WorkflowToolAskRequest): WorkflowAskRoute {
- const { allowFreeform, options } = ask.request;
- return {
- control: ask.control,
- question: {
- ...(allowFreeform !== undefined && { allowFreeform }),
- ...(options !== undefined && { options: [...options] }),
- },
- };
+ return { control: ask.control };
}
diff --git a/packages/eve/src/execution/session/turn-step.test.ts b/packages/eve/src/execution/session/turn-step.test.ts
index f7eb41909..ae16b8eb9 100644
--- a/packages/eve/src/execution/session/turn-step.test.ts
+++ b/packages/eve/src/execution/session/turn-step.test.ts
@@ -419,7 +419,8 @@ describe("routeProxiedDeliverStep", () => {
[
"ask-1",
{
- workflowAsk: { control: "control", question: { allowFreeform: true } },
+ workflowAsk: { control: "control" },
+ reply: { allowFreeform: true },
runId: "run-1",
childContinuationToken: "ask-1",
event: REQUEST_EVENT,
@@ -454,6 +455,54 @@ describe("routeProxiedDeliverStep", () => {
});
});
+ it("forwards a typed approve to a subagent's approval as its sender, once", async () => {
+ const auth = {
+ attributes: {},
+ authenticator: "test",
+ principalId: "alice",
+ principalType: "user",
+ };
+ const session = upsertProxyInputRequests({
+ entries: [
+ [
+ "approval-1",
+ {
+ childContinuationToken: "child-token",
+ event: REQUEST_EVENT,
+ kind: "tool-approval",
+ reply: { options: [{ id: "approve", label: "Approve" }] },
+ },
+ ],
+ ],
+ forChildContinuationToken: "child-token",
+ session: createStubSession(),
+ });
+ installSessionStoreMocks([session]);
+
+ const result = await routeProxiedDeliverStep({
+ serializedContext: createSerializedContext(),
+ delivery: {
+ kind: "deliver",
+ auth,
+ payloads: [{ message: "approve" }, { message: "approve" }],
+ },
+ sessionWritable: createTestWritable(),
+ sessionState: createStubSessionState({ hasProxyInputRequests: true }),
+ });
+
+ expect(resumeHookMock).toHaveBeenCalledTimes(1);
+ expect(resumeHookMock).toHaveBeenCalledWith("eve:inbox:v1:child-token", {
+ auth,
+ deliveryMetadata: undefined,
+ kind: "deliver",
+ payloads: [{ inputResponses: [{ optionId: "approve", requestId: "approval-1" }] }],
+ });
+ expect(result).toMatchObject({
+ kind: "continue",
+ remainder: { payloads: [{ message: "approve" }] },
+ });
+ });
+
it.each([
["local", { "eve.channel": { kind: "subagent" } }],
[
@@ -473,12 +522,10 @@ describe("routeProxiedDeliverStep", () => {
[
"ask-1",
{
- workflowAsk: {
- control: "control",
- question: {
- allowFreeform: false,
- options: [{ id: "approve", label: "Approve" }],
- },
+ workflowAsk: { control: "control" },
+ reply: {
+ allowFreeform: false,
+ options: [{ id: "approve", label: "Approve" }],
},
runId: "run-1",
childContinuationToken: "ask-1",
diff --git a/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts b/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts
index 713659c4b..90cefab73 100644
--- a/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts
+++ b/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts
@@ -113,7 +113,7 @@ describe("settleCancelledTurnStep", () => {
relay(base.snapshot.session.state, "deploy-run-ask-1", {
kind: "question",
runId: "deploy-run",
- workflowAsk: { control: "deploy-run-control", question: {} },
+ workflowAsk: { control: "deploy-run-control" },
}),
"reviewer-approval-1",
{ kind: "tool-approval" },
diff --git a/packages/eve/src/execution/tasks/session.test.ts b/packages/eve/src/execution/tasks/session.test.ts
index 2fb57e5fb..82e05c83f 100644
--- a/packages/eve/src/execution/tasks/session.test.ts
+++ b/packages/eve/src/execution/tasks/session.test.ts
@@ -224,7 +224,8 @@ function withQuestion(session: DurableSession, runId: string): DurableSession {
event: REQUEST_EVENT,
kind: "question",
runId,
- workflowAsk: { control: `${runId}-control`, question: {} },
+ workflowAsk: { control: `${runId}-control` },
+ reply: {},
},
],
],
diff --git a/packages/eve/src/harness/coordination.test.ts b/packages/eve/src/harness/coordination.test.ts
index ca92e88a4..ea198f7b3 100644
--- a/packages/eve/src/harness/coordination.test.ts
+++ b/packages/eve/src/harness/coordination.test.ts
@@ -357,7 +357,8 @@ describe("runtime results", () => {
answerToken,
{
runId: "run-1",
- workflowAsk: { control: "control", question: {} },
+ workflowAsk: { control: "control" },
+ reply: {},
childContinuationToken: answerToken,
event: REQUEST_EVENT,
kind: "question",
diff --git a/packages/eve/src/harness/proxy-input-requests.test.ts b/packages/eve/src/harness/proxy-input-requests.test.ts
index d9a54c13b..6b0dde252 100644
--- a/packages/eve/src/harness/proxy-input-requests.test.ts
+++ b/packages/eve/src/harness/proxy-input-requests.test.ts
@@ -238,7 +238,7 @@ describe("toProxyInputRequestEntries", () => {
);
});
- it("records shared batch and approval metadata on every route", () => {
+ it("records batch, approval, and reply metadata on every route", () => {
const requests = [
createRequest("question-1", "question"),
createRequest("approval-1", "tool-approval"),
@@ -263,7 +263,7 @@ describe("toProxyInputRequestEntries", () => {
childContinuationToken: "child-a",
event: { sequence: 3, stepIndex: 2, turnId: "turn-1" },
kind: "question",
- question: {},
+ reply: {},
},
],
[
@@ -276,6 +276,7 @@ describe("toProxyInputRequestEntries", () => {
childContinuationToken: "child-a",
event: { sequence: 3, stepIndex: 2, turnId: "turn-1" },
kind: "tool-approval",
+ reply: {},
},
],
]);
diff --git a/packages/eve/src/harness/proxy-input-requests.ts b/packages/eve/src/harness/proxy-input-requests.ts
index 3efb26d72..c18dbaf49 100644
--- a/packages/eve/src/harness/proxy-input-requests.ts
+++ b/packages/eve/src/harness/proxy-input-requests.ts
@@ -23,12 +23,10 @@ const PROXY_INPUT_REQUEST_KINDS = {
*/
export interface WorkflowAskRoute {
readonly control: string;
- /** What a plain-text message may answer. */
- readonly question: ProxyInputQuestion;
}
-/** The parts of a `ctx.ask()` request a plain-text message is resolved against. */
-export interface ProxyInputQuestion {
+/** The parts of a request a plain-text reply is resolved against. */
+export interface ProxyInputReply {
readonly allowFreeform?: boolean;
readonly options?: readonly InputOption[];
}
@@ -54,8 +52,8 @@ export interface ProxyInputRequest {
*/
readonly event: PendingInputBatchEvent;
readonly kind: InputRequestKind;
- /** Question metadata lets the human-facing parent resolve plain text before proxying by ID. */
- readonly question?: ProxyInputQuestion;
+ /** Lets the human-facing parent resolve a plain-text reply before proxying it by ID. */
+ readonly reply?: ProxyInputReply;
}
export interface ProxyInputRequestBatch {
@@ -197,7 +195,7 @@ export function toProxyInputRequestEntries(
childSessionInbox?: SessionInboxAddress;
readonly event: PendingInputBatchEvent;
readonly kind: InputRequestKind;
- question?: ProxyInputQuestion;
+ readonly reply: ProxyInputReply;
} & { readonly batch: ProxyInputRequestBatch } = {
batch,
childContinuationToken: payload.childContinuationToken,
@@ -205,13 +203,11 @@ export function toProxyInputRequestEntries(
...(payload.remote !== undefined && { remote: payload.remote }),
event,
kind: request.kind,
- };
- if (request.kind === "question") {
- route.question = {
+ reply: {
...(request.allowFreeform !== undefined && { allowFreeform: request.allowFreeform }),
...(request.options !== undefined && { options: [...request.options] }),
- };
- }
+ },
+ };
if (payload.childSessionInbox?.sessionId === payload.childSessionId) {
route.childSessionInbox = payload.childSessionInbox;
}
@@ -277,8 +273,8 @@ function parseProxyInputRequest(value: unknown, requestId: string): ProxyInputRe
if ("workflowAsk" in value && workflowAsk === undefined) return undefined;
const runId = "runId" in value ? value.runId : undefined;
if (runId !== undefined && (typeof runId !== "string" || runId.length === 0)) return undefined;
- const question = "question" in value ? parseProxyInputQuestion(value.question) : undefined;
- if ("question" in value && question === undefined) return undefined;
+ const reply = "reply" in value ? parseProxyInputReply(value.reply) : undefined;
+ if ("reply" in value && reply === undefined) return undefined;
const childSessionInbox = "childSessionInbox" in value ? value.childSessionInbox : undefined;
if (childSessionInbox !== undefined && !isSessionInboxAddress(childSessionInbox))
return undefined;
@@ -292,7 +288,7 @@ function parseProxyInputRequest(value: unknown, requestId: string): ProxyInputRe
childSessionInbox?: SessionInboxAddress;
readonly event: PendingInputBatchEvent;
readonly kind: InputRequestKind;
- question?: ProxyInputQuestion;
+ reply?: ProxyInputReply;
} = {
childContinuationToken: value.childContinuationToken,
event,
@@ -304,7 +300,7 @@ function parseProxyInputRequest(value: unknown, requestId: string): ProxyInputRe
if (typeof runId === "string") request.runId = runId;
if (childSessionInbox !== undefined) request.childSessionInbox = childSessionInbox;
if (batch !== undefined && batch.requestIds.includes(requestId)) request.batch = batch;
- if (question !== undefined) request.question = question;
+ if (reply !== undefined) request.reply = reply;
return request;
}
@@ -322,9 +318,7 @@ function parseWorkflowAskRoute(value: unknown): WorkflowAskRoute | undefined {
if (value === null || typeof value !== "object") return undefined;
const control = Reflect.get(value, "control");
if (typeof control !== "string" || control.length === 0) return undefined;
- const question = parseProxyInputQuestion(Reflect.get(value, "question"));
- if (question === undefined) return undefined;
- return { control, question };
+ return { control };
}
function parseRemoteAgentBinding(
@@ -356,24 +350,24 @@ function parseRemoteAgentBinding(
};
}
-function parseProxyInputQuestion(value: unknown): ProxyInputQuestion | undefined {
+function parseProxyInputReply(value: unknown): ProxyInputReply | undefined {
if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined;
- const question: {
+ const reply: {
allowFreeform?: boolean;
options?: readonly InputOption[];
} = {};
const allowFreeform = Reflect.get(value, "allowFreeform");
if (allowFreeform !== undefined) {
if (typeof allowFreeform !== "boolean") return undefined;
- question.allowFreeform = allowFreeform;
+ reply.allowFreeform = allowFreeform;
}
const options = Reflect.get(value, "options");
if (options !== undefined) {
const parsed = inputOptionSchema.array().safeParse(options);
if (!parsed.success) return undefined;
- question.options = parsed.data;
+ reply.options = parsed.data;
}
- return question;
+ return reply;
}
function parseProxyInputRequestBatch(value: unknown): ProxyInputRequestBatch | undefined {
diff --git a/packages/eve/src/subagents/hitl-proxy.integration.test.ts b/packages/eve/src/subagents/hitl-proxy.integration.test.ts
index 7fa5fbd3b..09836e21f 100644
--- a/packages/eve/src/subagents/hitl-proxy.integration.test.ts
+++ b/packages/eve/src/subagents/hitl-proxy.integration.test.ts
@@ -273,6 +273,7 @@ describe("subagent HITL proxy → Slack-style text-approve regression (Finding #
childContinuationToken: "subagent:parent:call-1",
event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
kind: "tool-approval",
+ reply: { options: approvalRequest.options },
},
],
]);
diff --git a/packages/eve/src/subagents/hitl-proxy.test.ts b/packages/eve/src/subagents/hitl-proxy.test.ts
index e55e5ef4f..424f7a831 100644
--- a/packages/eve/src/subagents/hitl-proxy.test.ts
+++ b/packages/eve/src/subagents/hitl-proxy.test.ts
@@ -1,8 +1,13 @@
import { describe, expect, it } from "vitest";
-import { upsertProxyInputRequests } from "#harness/proxy-input-requests.js";
+import {
+ retireProxyInputRequests,
+ toProxyInputRequestEntries,
+ upsertProxyInputRequests,
+} from "#harness/proxy-input-requests.js";
import type { HarnessSession } from "#harness/types.js";
import { withParkedStep } from "#internal/testing/session-machine.js";
+import type { InputRequest } from "#shared/input.js";
import { routeDeliverPayload } from "#subagents/hitl-proxy.js";
const REQUEST_EVENT = { sequence: 0, stepIndex: 0, turnId: "turn_0" };
@@ -267,15 +272,13 @@ describe("routeDeliverPayload message resolution", () => {
[
requestId,
{
- workflowAsk: {
- question: {
- ...question,
- options: [
- { id: "1", label: "Staging" },
- { id: "2", label: "Production" },
- ],
- },
- control: `control-${requestId}`,
+ workflowAsk: { control: `control-${requestId}` },
+ reply: {
+ ...question,
+ options: [
+ { id: "1", label: "Staging" },
+ { id: "2", label: "Production" },
+ ],
},
runId: `run-${requestId}`,
childContinuationToken: `hook-${requestId}`,
@@ -394,13 +397,14 @@ describe("routeDeliverPayload message resolution", () => {
expect(routed.forChildren).toEqual([]);
});
- it("does not answer a question while a subagent question comes first", () => {
+ it("does not answer a later question while a request it can't match comes first", () => {
const session = upsertProxyInputRequests({
entries: [
[
"ask-1",
{
- workflowAsk: { control: "control-ask-1", question: { allowFreeform: true } },
+ workflowAsk: { control: "control-ask-1" },
+ reply: { allowFreeform: true },
childContinuationToken: "hook-ask-1",
event: REQUEST_EVENT,
kind: "question",
@@ -429,6 +433,119 @@ describe("routeDeliverPayload message resolution", () => {
expect(routed.forChildren).toEqual([]);
});
+ function childPromptSession(requests: readonly InputRequest[]): HarnessSession {
+ return upsertProxyInputRequests({
+ entries: toProxyInputRequestEntries({
+ callId: "call-1",
+ childContinuationToken: "child-token",
+ childSessionId: "child-session",
+ event: { requests, ...REQUEST_EVENT },
+ kind: "subagent-input-request",
+ subagentName: "reviewer",
+ }),
+ forChildContinuationToken: "child-token",
+ session: createSession(),
+ });
+ }
+
+ function childPrompt(requestId: string, kind: InputRequest["kind"]): InputRequest {
+ const options =
+ kind === "session-limit"
+ ? [
+ { id: "continue", label: "Approve" },
+ { id: "stop", label: "Stop" },
+ ]
+ : [
+ { id: "approve", label: "Approve" },
+ { id: "cancel", label: "Cancel" },
+ ];
+ return {
+ action: { callId: requestId, input: {}, kind: "tool-call", toolName: "deploy" },
+ kind,
+ options,
+ prompt: "Continue?",
+ requestId,
+ };
+ }
+
+ it("answers a subagent's approvals one typed reply at a time", () => {
+ const session = childPromptSession([
+ childPrompt("approve-1", "tool-approval"),
+ childPrompt("approve-2", "tool-approval"),
+ ]);
+ const first = routeDeliverPayload({
+ payload: { message: "approve" },
+ resolveMessage: true,
+ state: session.state,
+ });
+
+ expect(first.forSelf).toBeUndefined();
+ expect(first.forChildren).toMatchObject([
+ {
+ childContinuationToken: "child-token",
+ message: "approve",
+ payload: { inputResponses: [{ optionId: "approve", requestId: "approve-1" }] },
+ resolved: { resolutions: [{ outcome: "approved", requestId: "approve-1" }] },
+ },
+ ]);
+
+ const second = routeDeliverPayload({
+ payload: { message: "cancel" },
+ resolveMessage: true,
+ state: retireProxyInputRequests(session, ["approve-1"]).state,
+ });
+ expect(second.forChildren).toMatchObject([
+ {
+ payload: { inputResponses: [{ optionId: "cancel", requestId: "approve-2" }] },
+ resolved: { resolutions: [{ outcome: "denied", requestId: "approve-2" }] },
+ },
+ ]);
+ });
+
+ it.each([
+ ["continue", undefined],
+ ["stop", { kind: "cancel-turn" }],
+ ] as const)("routes a typed %s to a subagent's session-limit prompt", (reply, parentAction) => {
+ const routed = routeDeliverPayload({
+ payload: { message: reply },
+ resolveMessage: true,
+ state: childPromptSession([childPrompt("limit-1", "session-limit")]).state,
+ });
+
+ expect(routed.parentAction).toEqual(parentAction);
+ expect(routed.forChildren[0]?.payload.inputResponses).toEqual([
+ { optionId: reply, requestId: "limit-1" },
+ ]);
+ });
+
+ it("answers the first of two children's prompts with a typed reply", () => {
+ const session = upsertProxyInputRequests({
+ entries: toProxyInputRequestEntries({
+ callId: "call-2",
+ childContinuationToken: "other-child-token",
+ childSessionId: "other-child-session",
+ event: { requests: [childPrompt("approve-other", "tool-approval")], ...REQUEST_EVENT },
+ kind: "subagent-input-request",
+ subagentName: "deployer",
+ }),
+ forChildContinuationToken: "other-child-token",
+ session: childPromptSession([childPrompt("approve-1", "tool-approval")]),
+ });
+ const routed = routeDeliverPayload({
+ payload: { message: "approve" },
+ resolveMessage: true,
+ state: session.state,
+ });
+
+ expect(routed.forSelf).toBeUndefined();
+ expect(routed.forChildren).toMatchObject([
+ {
+ childContinuationToken: "child-token",
+ payload: { inputResponses: [{ optionId: "approve", requestId: "approve-1" }] },
+ },
+ ]);
+ });
+
it("leaves questions alone unless a person's message may resolve them", () => {
const routed = routeDeliverPayload({
payload: { message: "production" },
diff --git a/packages/eve/src/subagents/hitl-proxy.ts b/packages/eve/src/subagents/hitl-proxy.ts
index 83e5c33ae..0ca9a4a33 100644
--- a/packages/eve/src/subagents/hitl-proxy.ts
+++ b/packages/eve/src/subagents/hitl-proxy.ts
@@ -73,9 +73,10 @@ const CONSUMED_MESSAGE_KEYS: ReadonlySet<string> = new Set(["context", "message"
/**
* Splits a deliver payload into parent-local and proxied-child buckets.
*
- * With `resolveMessage`, a plain-text message is also resolved against pending
- * `ctx.ask()` questions: when exactly one question is pending, a matching option or
- * permitted free text answers it and consumes the message along with its
+ * With `resolveMessage`, a plain-text message is also resolved against the
+ * first open request when a child asked it, whether a `ctx.ask()` question, a
+ * tool approval, or a session-limit prompt: a matching option or permitted free
+ * text answers that one request, and the message is consumed along with its
* `context`. Otherwise the message stays with the parent.
*/
export function routeDeliverPayload(input: {
@@ -87,7 +88,7 @@ export function routeDeliverPayload(input: {
const entries = getProxyInputRequests(input.state);
const routable = (requestId: string, route: ProxyInputRequest | undefined) =>
route !== undefined && input.allowRoute?.(requestId, route) !== false;
- const message = resolveMessageAgainstQuestions({
+ const message = resolveMessageAgainstFirstRequest({
enabled: input.resolveMessage === true,
entries,
payload: input.payload,
@@ -244,7 +245,7 @@ function toInputResolution(
return response === undefined ? resolution : { ...resolution, response };
}
-function resolveMessageAgainstQuestions(input: {
+function resolveMessageAgainstFirstRequest(input: {
readonly enabled: boolean;
readonly entries: ReadonlyMap<string, ProxyInputRequest>;
readonly payload: DeliverPayload;
@@ -269,13 +270,10 @@ function resolveMessageAgainstQuestions(input: {
const requestId =
firstOpenInput(storedProjection(input.state), answered)?.request.requestId ??
[...input.entries.keys()].find((id) => !answered(id));
- const route = requestId === undefined ? undefined : input.entries.get(requestId);
- if (requestId === undefined || route?.kind !== "question") return none;
- // Task and subagent questions carry no `ctx.ask()` metadata, so plain text
- // cannot resolve them.
- const question = route.workflowAsk?.question ?? route.question;
- const answer =
- question === undefined ? undefined : resolveTextToResponse(text, { requestId, ...question });
+ const reply = requestId === undefined ? undefined : input.entries.get(requestId)?.reply;
+ // A request recorded without reply metadata cannot be matched at all.
+ if (requestId === undefined || reply === undefined) return none;
+ const answer = resolveTextToResponse(text, { requestId, ...reply });
return answer === undefined ? none : { consumed: true, responses: [answer] };
}