Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): let the first answer to an approval decide it (#4817) (#4825)

roboeve[bot]5c53f1fc973f
diff --git a/.changeset/approval-answer-checks.md b/.changeset/approval-answer-checks.md
new file mode 100644
index 000000000..52d8a061c
--- /dev/null
+++ b/.changeset/approval-answer-checks.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+An approval answer that is neither Approve nor Cancel now gets feedback instead of being dropped, and a repeated answer to an approval that was already decided is discarded before the requester check, so it no longer warns whoever's delivery carried it.
diff --git a/.changeset/duplicate-approval-answer.md b/.changeset/duplicate-approval-answer.md
new file mode 100644
index 000000000..7e10c089e
--- /dev/null
+++ b/.changeset/duplicate-approval-answer.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+The first answer to a tool approval now decides it. A repeated answer, for example from a double click, no longer leaves the session waiting when the tool has an approval response policy, and no longer overrides an earlier answer when it doesn't: Cancel followed by Approve stays cancelled. The note sent with the deciding answer, such as why it was cancelled, still reaches the model. An unauthenticated answer to a call that has a requester is rejected with feedback instead of settling it, so it can't pre-empt the requester's own answer. When the call has no requester, an unauthenticated answer is recorded as the anonymous principal that `none()` gives unauthenticated callers.
diff --git a/packages/eve/src/channel/principal-identity.ts b/packages/eve/src/channel/principal-identity.ts
index 195d41a0b..cab8d8cf2 100644
--- a/packages/eve/src/channel/principal-identity.ts
+++ b/packages/eve/src/channel/principal-identity.ts
@@ -19,3 +19,11 @@ export function principalIdentity(auth: SessionAuthContext): readonly string[] {
export function isAnonymousPrincipal(auth: SessionAuthContext): boolean {
return auth.principalType === "anonymous";
}
+
+/** The principal `none()` gives every unauthenticated caller. */
+export const ANONYMOUS_SESSION_AUTH_CONTEXT: SessionAuthContext = {
+ attributes: {},
+ authenticator: "none",
+ principalId: "anonymous",
+ principalType: "anonymous",
+};
diff --git a/packages/eve/src/execution/session/approval-caller.integration.test.ts b/packages/eve/src/execution/session/approval-caller.integration.test.ts
index 6a33413ae..cfad8866b 100644
--- a/packages/eve/src/execution/session/approval-caller.integration.test.ts
+++ b/packages/eve/src/execution/session/approval-caller.integration.test.ts
@@ -380,9 +380,11 @@ describe("approval caller", () => {
const { secondRequesters, seen, stages } = await withChainRun(
"approval-caller-null-auth",
async (run) => {
- // Without a response policy, the approval stands; the call runs as the turn's caller.
- await run.approve(null, "deploy_change");
- // A response policy needs an authenticated responder, so this one stays pending.
+ // The call has a requester, so an unauthenticated answer settles nothing, with or
+ // without a response policy; the requester's own answer still decides it.
+ const refusedDirect = await run.approve(null, "deploy_change");
+ expect(filterEventsByType(refusedDirect, "input.resolved")).toEqual([]);
+ await run.approve(ALICE, "deploy_change");
const refused = await run.approve(null, "publish_change");
expect(filterEventsByType(refused, "input.resolved")).toEqual([]);
await run.approve(ALICE, "publish_change");
@@ -394,6 +396,7 @@ describe("approval caller", () => {
expect(secondRequesters).toEqual(["alice"]);
expect(stages.flatMap((stage) => filterEventsByType(stage, "approval.settled"))).toMatchObject([
{ data: { outcome: "approved", responderPrincipalId: "alice" } },
+ { data: { outcome: "approved", responderPrincipalId: "alice" } },
]);
}, 60_000);
diff --git a/packages/eve/src/harness/hitl/approvals.ts b/packages/eve/src/harness/hitl/approvals.ts
index 3fdb866c1..6c1529252 100644
--- a/packages/eve/src/harness/hitl/approvals.ts
+++ b/packages/eve/src/harness/hitl/approvals.ts
@@ -159,8 +159,7 @@ export interface ResponsePolicyPass {
| "continue"
| "continue-coordination"
| "authorization-required"
- | "responses-completed"
- | "park";
+ | "responses-completed";
readonly challenges: readonly AuthorizationChallenge[];
readonly feedback: readonly string[];
/** The delivery minus the answers the policies took, plus the settlements they reached. */
@@ -231,7 +230,6 @@ export function answer(
turn = withQueued(turn, queued);
};
- if (policy.kind === "park") return done({ next: "park" });
if (policy.kind === "continue-coordination") {
queue(policy.stepInput);
return done({ next: "repeat" });
diff --git a/packages/eve/src/harness/hitl/candidates.ts b/packages/eve/src/harness/hitl/candidates.ts
index 430a46c65..b8eb9a6c7 100644
--- a/packages/eve/src/harness/hitl/candidates.ts
+++ b/packages/eve/src/harness/hitl/candidates.ts
@@ -47,6 +47,8 @@ export interface ApprovalSettlementAuditRecord {
readonly requestId: string;
readonly settledAt: number;
readonly candidateId?: string;
+ /** What the settling responder wrote with their answer, such as why they cancelled. */
+ readonly text?: string;
}
export interface ActiveApprovalCandidate {
@@ -58,6 +60,8 @@ export interface ActiveApprovalCandidate {
readonly createdAt: number;
readonly expiresAt: number;
readonly authorizationChallenges?: readonly AuthorizationChallenge[];
+ /** What the responder wrote with their answer; the settlement keeps it once allowed. */
+ readonly text?: string;
}
export interface DurableApprovalState {
@@ -81,6 +85,7 @@ export function createApprovalCandidate(input: {
readonly requestId: string;
readonly responder: SessionAuthContext;
readonly state: SessionStateMap | undefined;
+ readonly text?: string;
}): ApprovalStateTransition {
const expiredState = expireApprovalCandidates({ now: input.createdAt, state: input.state });
const approvalState = readApprovalState(expiredState);
@@ -123,6 +128,7 @@ export function createApprovalCandidate(input: {
requestId: input.requestId,
responder,
status: "pending",
+ ...(input.text !== undefined && { text: input.text }),
};
const next: DurableApprovalState = {
...approvalState,
@@ -230,6 +236,7 @@ export function settleAllowedCandidate(input: {
responder: candidate.responder,
settledAt: input.settledAt,
state: expiredState,
+ text: candidate.text,
});
}
@@ -257,13 +264,14 @@ export function settleUnavailableCandidate(input: {
});
}
-/** Atomically settles a direct authenticated approval response. */
+/** Atomically settles a direct approval response. */
export function settleDirectApprovalResponse(input: {
readonly actor: SessionAuthContext;
readonly outcome: "allowed" | "cancelled";
readonly requestId: string;
readonly settledAt: number;
readonly state: SessionStateMap | undefined;
+ readonly text?: string;
}): ApprovalStateTransition {
const state = expireApprovalCandidates({ now: input.settledAt, state: input.state });
return settleRequest({
@@ -272,6 +280,7 @@ export function settleDirectApprovalResponse(input: {
responder: input.actor,
settledAt: input.settledAt,
state,
+ text: input.text,
});
}
@@ -306,6 +315,7 @@ function settleRequest(input: {
readonly responder: SessionAuthContext;
readonly settledAt: number;
readonly state: SessionStateMap | undefined;
+ readonly text?: string;
}): ApprovalStateTransition {
const approvalState = readApprovalState(input.state);
const existing = approvalState.settlements[input.requestId];
@@ -320,6 +330,7 @@ function settleRequest(input: {
outcome: input.outcome,
requestId: input.requestId,
settledAt: input.settledAt,
+ ...(input.text !== undefined && { text: input.text }),
};
const activeCandidates: Record<string, ActiveApprovalCandidate> = {};
const candidateHistory = [...approvalState.candidateHistory];
@@ -356,6 +367,7 @@ function toCandidateAuditRecord(input: {
const {
authorizationChallenges: _authorizationChallenges,
responder,
+ text: _text,
...candidate
} = input.candidate;
return {
diff --git a/packages/eve/src/harness/hitl/coordinator.test.ts b/packages/eve/src/harness/hitl/coordinator.test.ts
index a4ccec026..1a31e1b37 100644
--- a/packages/eve/src/harness/hitl/coordinator.test.ts
+++ b/packages/eve/src/harness/hitl/coordinator.test.ts
@@ -20,7 +20,7 @@ import { storedProjection } from "#harness/session-machine/view.js";
import { captureLogRecords } from "#internal/testing/log-records.js";
import { parkedSteps, withParkedStep, withPublished } from "#internal/testing/session-machine.js";
import { createApprovalSettledEvent } from "#protocol/message.js";
-import type { HarnessSession } from "#harness/types.js";
+import type { HarnessSession, StepInput } from "#harness/types.js";
import type { InputRequest } from "#shared/input.js";
const request: InputRequest = {
@@ -65,6 +65,7 @@ describe("coordinateApprovalDelivery", () => {
session: HarnessSession,
response: ApprovalResponsePolicy,
prepareTools?: () => Promise<Map<string, HarnessToolDefinition>>,
+ stepInput?: StepInput,
) {
const ctx = new ContextContainer();
ctx.set(SessionKey, {
@@ -84,6 +85,7 @@ describe("coordinateApprovalDelivery", () => {
now: 101,
prepareTools,
session,
+ stepInput,
tools: new Map([["gate", tool]]),
}),
);
@@ -286,11 +288,59 @@ describe("coordinateApprovalDelivery", () => {
);
});
- it("does not complete a duplicate while its candidate is active", async () => {
+ it("authorizes the active candidate once when its duplicate arrives", async () => {
const ingested = await ingest();
- const duplicate = await ingest(ingested.session);
- expect(duplicate.kind).toBe("continue");
- expect(getApprovalAuditState(duplicate.session.state).activeCandidates).toHaveLength(1);
+ const response = vi.fn<ApprovalResponsePolicy>(() => ({ status: "allowed" }));
+ const duplicate = await authorize(ingested.session, response, undefined, {
+ attributedInputResponses: [
+ { auth: responder, response: { requestId: request.requestId, optionId: "approve" } },
+ ],
+ });
+ expect(response).toHaveBeenCalledOnce();
+ expect(duplicate.kind).toBe("responses-completed");
+ expect(duplicate.stepInput?.inputResponses).toEqual([
+ { optionId: "approve", requestId: request.requestId },
+ ]);
+ });
+
+ it("authorizes the active candidate when a sibling's direct answer arrives", async () => {
+ const direct: InputRequest = {
+ ...request,
+ action: { ...request.action, callId: "call-2" },
+ requestId: "approval-2",
+ };
+ const parked = withParkedStep(
+ {
+ agent: { modelReference: { id: "test" }, system: "", tools: [] },
+ compaction: { recentWindowSize: 10, threshold: 0.8 },
+ continuationToken: "test",
+ history: [],
+ sessionId: "session-1",
+ },
+ {
+ requester: responder,
+ requests: [request, direct],
+ responseAuthRequiredRequestIds: [request.requestId],
+ },
+ );
+ const ingested = await ingest(parked);
+ expect(ingested.kind).toBe("continue-coordination");
+
+ const response = vi.fn<ApprovalResponsePolicy>(() => ({ status: "allowed" }));
+ const result = await authorize(ingested.session, response, undefined, {
+ attributedInputResponses: [
+ { auth: responder, response: { requestId: direct.requestId, optionId: "approve" } },
+ ],
+ });
+ expect(response).toHaveBeenCalledOnce();
+ expect(result.kind).toBe("responses-completed");
+ expect(getApprovalAuditState(result.session.state).activeCandidates).toEqual([]);
+ expect(result.stepInput?.inputResponses).toEqual(
+ expect.arrayContaining([
+ { optionId: "approve", requestId: request.requestId },
+ { optionId: "approve", requestId: direct.requestId },
+ ]),
+ );
});
it("keeps authorization-required candidates parked instead of completing", async () => {
@@ -426,6 +476,30 @@ describe("coordinateApprovalDelivery", () => {
]);
});
+ it("keeps the note an authorized Cancel was sent with", async () => {
+ const ingested = await coordinateApprovalDelivery({
+ now: 100,
+ session: parkedSession(),
+ stepInput: {
+ attributedInputResponses: [
+ {
+ auth: responder,
+ response: {
+ optionId: "cancel",
+ requestId: request.requestId,
+ text: "only the three-pack",
+ },
+ },
+ ],
+ },
+ tools: new Map(),
+ });
+ const settled = await authorize(ingested.session, () => ({ status: "allowed" }));
+ expect(settled.stepInput?.inputResponses).toEqual([
+ { optionId: "cancel", requestId: request.requestId, text: "only the three-pack" },
+ ]);
+ });
+
it("forwards an unrelated message while a response-authorized approval remains pending", async () => {
const messageAuth: SessionAuthContext = { ...responder, principalId: "user-2" };
const result = await coordinateApprovalDelivery({
@@ -488,11 +562,211 @@ describe("approval responses without a response policy", () => {
expect(parkedSteps(result.session)).toHaveLength(1);
});
+ it("keeps the first answer when a repeated answer disagrees", async () => {
+ const second: InputRequest = {
+ ...request,
+ action: { ...request.action, callId: "call-2" },
+ requestId: "approval-2",
+ };
+ const parked = withParkedStep(
+ { ...parkedSession(), state: undefined },
+ { requester: alice, requests: [request, second] },
+ );
+ const answer = (session: HarnessSession, ...responses: [string, string][]) =>
+ coordinateApprovalDelivery({
+ now: 100,
+ session,
+ stepInput: {
+ attributedInputResponses: responses.map(([requestId, optionId]) => ({
+ auth: alice,
+ response: { optionId, requestId },
+ })),
+ },
+ tools: new Map(),
+ });
+
+ const cancelled = await answer(parked, [request.requestId, "cancel"]);
+ const repeated = await answer(
+ cancelled.session,
+ [request.requestId, "approve"],
+ [second.requestId, "approve"],
+ );
+ expect(repeated.stepInput?.inputResponses).toEqual([
+ { optionId: "cancel", requestId: request.requestId },
+ { optionId: "approve", requestId: second.requestId },
+ ]);
+ });
+
+ it("keeps the first answer's note when a repeated answer disagrees", async () => {
+ const second: InputRequest = {
+ ...request,
+ action: { ...request.action, callId: "call-2" },
+ requestId: "approval-2",
+ };
+ const parked = withParkedStep(
+ { ...parkedSession(), state: undefined },
+ { requester: alice, requests: [request, second] },
+ );
+ const cancelled = await coordinateApprovalDelivery({
+ now: 100,
+ session: parked,
+ stepInput: {
+ attributedInputResponses: [
+ {
+ auth: alice,
+ response: {
+ optionId: "cancel",
+ requestId: request.requestId,
+ text: "only the three-pack",
+ },
+ },
+ ],
+ },
+ tools: new Map(),
+ });
+ const repeated = await coordinateApprovalDelivery({
+ now: 101,
+ session: cancelled.session,
+ stepInput: {
+ attributedInputResponses: [
+ {
+ auth: alice,
+ response: { optionId: "cancel", requestId: request.requestId, text: "never mind" },
+ },
+ { auth: alice, response: { optionId: "approve", requestId: second.requestId } },
+ ],
+ },
+ tools: new Map(),
+ });
+ expect(repeated.stepInput?.inputResponses).toEqual([
+ { optionId: "cancel", requestId: request.requestId, text: "only the three-pack" },
+ { optionId: "approve", requestId: second.requestId },
+ ]);
+ });
+
+ it("doesn't recheck a settled answer replayed with another responder's delivery", async () => {
+ const second: InputRequest = {
+ ...request,
+ action: { ...request.action, callId: "call-2" },
+ requestId: "approval-2",
+ };
+ const parked = withParkedStep(
+ { ...parkedSession(), state: undefined },
+ { requester: alice, requests: [request, second] },
+ );
+ const settled = await respond(parked, alice);
+ // `answer` queues the settled response while the batch waits; Bob's delivery brings it back.
+ const ctx = new ContextContainer();
+ ctx.set(SessionKey, {
+ auth: { current: bob, initiator: alice },
+ sessionId: parked.sessionId,
+ turn: { id: "turn-2", sequence: 2 },
+ });
+ const replayed = await contextStorage.run(ctx, () =>
+ coordinateApprovalDelivery({
+ now: 101,
+ session: settled.session,
+ stepInput: {
+ attributedInputResponses: [
+ { auth: bob, response: { optionId: "approve", requestId: second.requestId } },
+ ],
+ inputResponses: settled.stepInput?.inputResponses,
+ },
+ tools: new Map(),
+ }),
+ );
+ expect(replayed.feedback).toEqual([
+ "Only the person who requested this action can respond to this approval.",
+ ]);
+ expect(
+ getApprovalAuditState(replayed.session.state).settlements.map((entry) => entry.requestId),
+ ).toEqual([request.requestId]);
+ expect(replayed.stepInput?.inputResponses).toEqual([
+ { optionId: "approve", requestId: request.requestId },
+ ]);
+ });
+
+ it.each([
+ ["an unknown option", { optionId: "bogus" }],
+ ["text alone", { text: "hmm, not sure" }],
+ ])("rejects %s with feedback and settles nothing", async (_label, answer) => {
+ const result = await coordinateApprovalDelivery({
+ now: 100,
+ session: parkedFor(alice),
+ stepInput: {
+ attributedInputResponses: [
+ { auth: alice, response: { ...answer, requestId: request.requestId } },
+ ],
+ },
+ tools: new Map(),
+ });
+ expect(result.feedback).toEqual(["Respond to this approval with Approve or Cancel."]);
+ expect(getApprovalAuditState(result.session.state).settlements).toEqual([]);
+ expect(result.stepInput?.inputResponses ?? []).toEqual([]);
+ expect(parkedSteps(result.session)).toHaveLength(1);
+ });
+
it("lets anyone respond when the requester is unauthenticated", async () => {
const result = await respond(parkedFor(null), bob);
expect(result.feedback).toEqual([]);
expect(getApprovalAuditState(result.session.state).settlements).toHaveLength(1);
});
+
+ it("settles nothing for an unauthenticated answer to a requester's call", async () => {
+ const result = await coordinateApprovalDelivery({
+ now: 100,
+ session: parkedFor(alice),
+ stepInput: {
+ attributedInputResponses: [
+ { auth: null, response: { optionId: "approve", requestId: request.requestId } },
+ ],
+ },
+ tools: new Map(),
+ });
+ expect(result.feedback).toEqual(["Authentication is required to respond to this approval."]);
+ expect(getApprovalAuditState(result.session.state).settlements).toEqual([]);
+ expect(result.stepInput?.inputResponses ?? []).toEqual([]);
+ expect(parkedSteps(result.session)).toHaveLength(1);
+ });
+
+ it("keeps the requester's Cancel decisive after an unauthenticated answer", async () => {
+ const afterAnonymous = await coordinateApprovalDelivery({
+ now: 100,
+ session: parkedFor(alice),
+ stepInput: {
+ attributedInputResponses: [
+ { auth: null, response: { optionId: "approve", requestId: request.requestId } },
+ ],
+ },
+ tools: new Map(),
+ });
+ const result = await respond(afterAnonymous.session, alice, "cancel");
+ expect(getApprovalAuditState(result.session.state).settlements).toEqual([
+ expect.objectContaining({ outcome: "cancelled" }),
+ ]);
+ });
+
+ it("records an unauthenticated answer as the anonymous principal", async () => {
+ const result = await coordinateApprovalDelivery({
+ now: 100,
+ session: parkedFor(null),
+ stepInput: {
+ attributedInputResponses: [
+ { auth: null, response: { optionId: "approve", requestId: request.requestId } },
+ ],
+ },
+ tools: new Map(),
+ });
+ expect(getApprovalAuditState(result.session.state).settlements).toEqual([
+ expect.objectContaining({
+ actor: expect.objectContaining({ principalId: "anonymous", principalType: "anonymous" }),
+ outcome: "allowed",
+ }),
+ ]);
+ expect(result.stepInput?.inputResponses).toEqual([
+ { optionId: "approve", requestId: request.requestId },
+ ]);
+ });
});
describe("text approval replay preparation", () => {
diff --git a/packages/eve/src/harness/hitl/coordinator.ts b/packages/eve/src/harness/hitl/coordinator.ts
index 68dfb7469..e1e78881c 100644
--- a/packages/eve/src/harness/hitl/coordinator.ts
+++ b/packages/eve/src/harness/hitl/coordinator.ts
@@ -1,3 +1,4 @@
+import { ANONYMOUS_SESSION_AUTH_CONTEXT } from "#channel/principal-identity.js";
import { readHitlState } from "./requests.js";
import type { SessionAuthContext } from "#channel/types.js";
import { buildCallbackContext } from "#context/build-callback-context.js";
@@ -38,6 +39,7 @@ import { createLogger, logError } from "#internal/logging.js";
import type { InputRequest } from "#shared/input.js";
const UNAUTHENTICATED_APPROVAL_FEEDBACK = "Authentication is required to respond to this approval.";
+const INVALID_APPROVAL_FEEDBACK = "Respond to this approval with Approve or Cancel.";
const REQUESTER_ONLY_APPROVAL_FEEDBACK =
"Only the person who requested this action can respond to this approval.";
const UNAVAILABLE_TOOL_APPROVAL_REASON =
@@ -56,8 +58,7 @@ interface ApprovalDeliveryResult {
| "continue"
| "continue-coordination"
| "authorization-required"
- | "responses-completed"
- | "park";
+ | "responses-completed";
readonly session: HarnessSession;
readonly stepInput?: StepInput;
}
@@ -68,7 +69,7 @@ interface ApprovalDeliveryResult {
* | State | Input | Transition |
* | --- | --- | --- |
* | pending request | Approve or Cancel | create responder-bound candidate |
- * | pending candidate | coordinator pass | run current authorizer |
+ * | pending candidate | coordinator pass or repeated answer | run current authorizer |
* | pending candidate | allowed | settle with its decision; competitors go stale |
* | pending candidate | rejected/error/expiry | append terminal history |
* | pending candidate | authorization required | persist private challenge |
@@ -101,36 +102,16 @@ export async function coordinateApprovalDelivery(input: {
const view = sessionView(storedProjection(session.state), session.state);
session = saveTransition(session, matchSignIns(view, { attemptIds: [...expiredChallengeIds] }));
}
- const audit = getApprovalAuditState(session.state);
+ const settledRequestIds = new Set(
+ getApprovalAuditState(session.state).settlements.map((settlement) => settlement.requestId),
+ );
const batches = suspendedSteps(session.state).filter((step) => step.requests.length > 0);
const pendingRequestIds = new Set(
batches.flatMap((batch) => batch.requests.map((request) => request.requestId)),
);
- const pendingSettlements = audit.settlements.filter((settlement) =>
- pendingRequestIds.has(settlement.requestId),
- );
- const settledRequestIds = new Set(audit.settlements.map((settlement) => settlement.requestId));
- // A direct response settles its individual request before the whole batch
- // resolves. Keep that response while its request is still pending so a
- // later response can complete the batch; only discard responses for requests
- // that have left pending input entirely.
- const deduplicableSettledRequestIds = new Set(
- [...settledRequestIds].filter((requestId) => !pendingRequestIds.has(requestId)),
- );
- const discardedDuplicate = hasResponseForRequest(input.stepInput, deduplicableSettledRequestIds);
- const deduplicatedInput = discardedDuplicate
- ? removeConsumedResponses(input.stepInput, deduplicableSettledRequestIds)
- : input.stepInput;
- if (
- discardedDuplicate &&
- pendingSettlements.length === 0 &&
- !hasMeaningfulInput(deduplicatedInput)
- ) {
- return deliveryResult(session, deduplicatedInput, "park");
- }
- if (batches.length === 0) return deliveryResult(session, deduplicatedInput);
+ if (batches.length === 0) return deliveryResult(session, input.stepInput);
- const stepInput = deduplicatedInput;
+ const stepInput = input.stepInput;
const authorizationRequiredRequestIds = new Set(
batches.flatMap((batch) => batch.responseAuthRequiredRequestIds ?? []),
);
@@ -149,15 +130,23 @@ export async function coordinateApprovalDelivery(input: {
for (const { auth: attributedResponder, response } of deliveredResponses) {
const request = requests.get(response.requestId);
if (request === undefined || !isApprovalRequest(request)) continue;
+ // First answer wins: every answer to a pending approval is consumed here, and only the
+ // request's recorded settlement reaches `answer`. An answer to a request that settled before
+ // this delivery is discarded unchecked; the settlement already decided it.
+ consumed.add(response.requestId);
+ if (settledRequestIds.has(response.requestId)) continue;
+ const decision = toCandidateDecision(response.optionId);
+ if (decision === undefined) {
+ feedback.push(INVALID_APPROVAL_FEEDBACK);
+ continue;
+ }
- const requiresAuthorization = authorizationRequiredRequestIds.has(response.requestId);
- if (!requiresAuthorization) {
+ if (!authorizationRequiredRequestIds.has(response.requestId)) {
const context = contextStorage.getStore();
const responder =
attributedResponder !== undefined
? attributedResponder
: (context?.get(AuthKey) ?? context?.get(SessionKey)?.auth.current ?? null);
- const decision = toCandidateDecision(response.optionId);
// Without a response policy, only the requester may settle the call. An
// unauthenticated or anonymous requester has no identity to match, so
// any responder may settle it. A tool opts into other responders by
@@ -166,35 +155,31 @@ export async function coordinateApprovalDelivery(input: {
suspendedSteps(session.state).find((step) =>
step.requests.some((request) => request.requestId === response.requestId),
)?.requester ?? null;
- if (
- responder !== null &&
- decision !== undefined &&
- requester !== null &&
- !sameResponder(requester, responder)
- ) {
- consumed.add(response.requestId);
- feedback.push(REQUESTER_ONLY_APPROVAL_FEEDBACK);
+ if (requester !== null && responder === null) {
+ feedback.push(UNAUTHENTICATED_APPROVAL_FEEDBACK);
continue;
}
- if (responder !== null && decision !== undefined) {
- const settled = settleDirectApprovalResponse({
- actor: responder,
- outcome: decision === "approve" ? "allowed" : "cancelled",
- requestId: response.requestId,
- settledAt: now,
- state: session.state,
- });
- session = { ...session, state: settled.state };
- didCommit ||= settled.changed;
+ if (requester !== null && responder !== null && !sameResponder(requester, responder)) {
+ feedback.push(REQUESTER_ONLY_APPROVAL_FEEDBACK);
+ continue;
}
+ // A direct settlement needs no authorizer pass; the settlements below carry it. An
+ // unauthenticated responder, allowed only when the call has no requester, settles as the
+ // anonymous principal `none()` gives such callers.
+ const settled = settleDirectApprovalResponse({
+ actor: responder ?? ANONYMOUS_SESSION_AUTH_CONTEXT,
+ outcome: decision === "approve" ? "allowed" : "cancelled",
+ requestId: response.requestId,
+ settledAt: now,
+ state: session.state,
+ text: response.text,
+ });
+ session = { ...session, state: settled.state };
continue;
}
- consumed.add(response.requestId);
// A response policy decides Cancel as well as Approve, so a responder it
// rejects can neither approve nor cancel someone else's request.
- const decision = toCandidateDecision(response.optionId);
- if (decision === undefined) continue;
const responder =
attributedResponder !== undefined
? attributedResponder
@@ -212,23 +197,18 @@ export async function coordinateApprovalDelivery(input: {
requestId: request.requestId,
responder,
state: session.state,
+ text: response.text,
});
session = { ...session, state: created.state };
didCommit ||= created.changed;
}
const remainingStepInput = removeConsumedResponses(stepInput, consumed);
- if (consumed.size > 0) {
- return deliveryResult(
- session,
- remainingStepInput,
- didCommit ? "continue-coordination" : "continue",
- [],
- feedback,
- );
- }
+ // A new candidate commits before any authorizer runs, and the next pass authorizes it. Every
+ // other delivery, such as a repeated answer or a direct settlement, runs the pending candidates
+ // now: no later pass is scheduled for them.
if (didCommit) {
- return deliveryResult(session, remainingStepInput, "continue", [], feedback);
+ return deliveryResult(session, remainingStepInput, "continue-coordination", [], feedback);
}
// Candidates are persisted in an earlier pass. Run pending candidates and
@@ -269,12 +249,11 @@ export async function coordinateApprovalDelivery(input: {
session = processed.session;
didCommit ||= processed.didCommit;
challenges.push(...processed.challenges);
- const settlement = getApprovalAuditState(session.state).settlements.find(
- (entry) => entry.requestId === candidate.requestId,
- );
- if (settlement !== undefined) pendingSettlements.push(settlement);
}
+ const pendingSettlements = getApprovalAuditState(session.state).settlements.filter((settlement) =>
+ pendingRequestIds.has(settlement.requestId),
+ );
const resumedStepInput = appendSettledResponses(remainingStepInput, pendingSettlements);
// Only a terminal candidate pass completes response processing. Ingestion must
// still commit before policy work, and live candidates still own their park.
@@ -282,18 +261,19 @@ export async function coordinateApprovalDelivery(input: {
(didCommit || expiredCandidates.length > 0) &&
getApprovalAuditState(session.state).activeCandidates.length === 0
) {
- return deliveryResult(session, resumedStepInput, "responses-completed");
+ return deliveryResult(session, resumedStepInput, "responses-completed", [], feedback);
}
if (pendingSettlements.length > 0) {
- return deliveryResult(session, resumedStepInput, "continue");
+ return deliveryResult(session, resumedStepInput, "continue", [], feedback);
}
return didCommit
- ? deliveryResult(session, resumedStepInput, "continue-coordination")
+ ? deliveryResult(session, resumedStepInput, "continue-coordination", [], feedback)
: deliveryResult(
session,
resumedStepInput,
challenges.length > 0 ? "authorization-required" : "continue",
challenges,
+ feedback,
);
}
@@ -466,48 +446,20 @@ function failCandidate(input: {
};
}
-function hasResponseForRequest(
- stepInput: StepInput | undefined,
- requestIds: ReadonlySet<string>,
-): boolean {
- return (
- stepInput?.attributedInputResponses?.some(({ response }) =>
- requestIds.has(response.requestId),
- ) === true ||
- stepInput?.inputResponses?.some((response) => requestIds.has(response.requestId)) === true
- );
-}
-
-function hasMeaningfulInput(stepInput: StepInput | undefined): boolean {
- return (
- stepInput?.message !== undefined ||
- (stepInput?.attributedInputResponses?.length ?? 0) > 0 ||
- (stepInput?.inputResponses?.length ?? 0) > 0 ||
- (stepInput?.runtimeActionResults?.length ?? 0) > 0
- );
-}
-
function appendSettledResponses(
stepInput: StepInput | undefined,
settlements: readonly ApprovalSettlementAuditRecord[],
): StepInput | undefined {
if (settlements.length === 0) return stepInput;
- const existingRequestIds = new Set([
- ...(stepInput?.inputResponses ?? []).map((response) => response.requestId),
- ...(stepInput?.attributedInputResponses ?? []).map(({ response }) => response.requestId),
- ]);
- const missingSettlements = settlements.filter(
- (settlement) => !existingRequestIds.has(settlement.requestId),
- );
- if (missingSettlements.length === 0) return stepInput;
return {
...stepInput,
inputResponses: [
...(stepInput?.inputResponses ?? []),
// An unavailable request answers as cancel, so nothing runs; `answer` reports it unavailable.
- ...missingSettlements.map((settlement) => ({
+ ...settlements.map((settlement) => ({
optionId: settlement.outcome === "allowed" ? "approve" : "cancel",
requestId: settlement.requestId,
+ ...(settlement.text !== undefined && { text: settlement.text }),
})),
],
};
diff --git a/packages/eve/src/harness/tool-loop-generate-approval-resume.integration.test.ts b/packages/eve/src/harness/tool-loop-generate-approval-resume.integration.test.ts
index c146be3aa..fcd7c2ac5 100644
--- a/packages/eve/src/harness/tool-loop-generate-approval-resume.integration.test.ts
+++ b/packages/eve/src/harness/tool-loop-generate-approval-resume.integration.test.ts
@@ -169,6 +169,36 @@ function createTwoPendingApprovalSession(): HarnessSession {
});
}
+/** One parked step asking for both calls; `responseAuthRequiredRequestIds` have a response policy. */
+function createOneBatchTwoApprovalSession(
+ responseAuthRequiredRequestIds?: readonly string[],
+): HarnessSession {
+ return withParkedStep(createBaseSession(), {
+ event: { sequence: 1, stepIndex: 0, turnId: "turn-1" },
+ messages: [
+ {
+ content: [toolCall, approvalRequest, secondToolCall, secondApprovalRequest],
+ role: "assistant",
+ },
+ ],
+ requests: [
+ pendingApprovalInputRequest,
+ {
+ ...pendingApprovalInputRequest,
+ action: {
+ ...pendingApprovalInputRequest.action,
+ callId: secondToolCall.toolCallId,
+ input: secondToolCall.input,
+ },
+ requestId: secondApprovalRequest.approvalId,
+ },
+ ],
+ responseAuthRequiredRequestIds: responseAuthRequiredRequestIds && [
+ ...responseAuthRequiredRequestIds,
+ ],
+ });
+}
+
function createModel(): MockLanguageModelV4 {
return new MockLanguageModelV4({
doStream: textStreamResult("The command returned /workspace."),
@@ -525,6 +555,91 @@ describe("tool loop generate approval resume (real AI SDK)", () => {
expect(execute).not.toHaveBeenCalled();
});
+ // #4817: a second press of the same Approve reaches the pass that should authorize the first.
+ it("authorizes a pending approval when a duplicate answer joins its pass", async () => {
+ const execute = vi.fn(async () => "/workspace");
+ const response = vi.fn(() => ({ status: "allowed" as const }));
+ const runStep = createToolLoopHarness(
+ createConfig(createModel(), execute, { request: () => "user-approval", response }),
+ );
+ const approve = {
+ inputResponses: [{ optionId: "approve", requestId: approvalRequest.approvalId }],
+ };
+ const session = withOpenTurn(createPendingApprovalSession(undefined, true), {
+ sequence: 1,
+ stepIndex: 1,
+ turnId: "turn-1",
+ });
+
+ const result = await contextStorage.run(createApprovalContext(), async () => {
+ const first = await runStep(session, approve);
+ if (typeof first.next !== "function") {
+ throw new TypeError("Expected the answer to schedule an authorization pass.");
+ }
+ return await first.next(first.session, approve);
+ });
+
+ expect(response).toHaveBeenCalledOnce();
+ expect(execute).toHaveBeenCalledOnce();
+ expect(parkedSteps(result.session)).toEqual([]);
+ });
+
+ it("authorizes a pending approval when a sibling's direct answer joins its pass", async () => {
+ const execute = vi.fn(async () => "/workspace");
+ const response = vi.fn(() => ({ status: "allowed" as const }));
+ const runStep = createToolLoopHarness(
+ createConfig(createModel(), execute, { request: () => "user-approval", response }),
+ );
+ const parked = createOneBatchTwoApprovalSession([approvalRequest.approvalId]);
+ const session = withOpenTurn(parked, { sequence: 1, stepIndex: 1, turnId: "turn-1" });
+
+ const result = await contextStorage.run(createApprovalContext(), async () => {
+ const first = await runStep(session, {
+ inputResponses: [{ optionId: "approve", requestId: approvalRequest.approvalId }],
+ });
+ if (typeof first.next !== "function") {
+ throw new TypeError("Expected the answer to schedule an authorization pass.");
+ }
+ return await first.next(first.session, {
+ inputResponses: [{ optionId: "approve", requestId: secondApprovalRequest.approvalId }],
+ });
+ });
+
+ expect(response).toHaveBeenCalledOnce();
+ expect(execute).toHaveBeenCalledTimes(2);
+ expect(parkedSteps(result.session)).toEqual([]);
+ });
+
+ it("keeps the first answer when a repeated answer to the same approval disagrees", async () => {
+ const execute = vi.fn(async () => "eve");
+ const runStep = createToolLoopHarness(createConfig(createModel(), execute));
+ const session = withOpenTurn(createOneBatchTwoApprovalSession(), {
+ sequence: 1,
+ stepIndex: 1,
+ turnId: "turn-1",
+ });
+
+ const result = await contextStorage.run(createApprovalContext(), async () => {
+ const cancelled = await runStep(session, {
+ inputResponses: [{ optionId: "cancel", requestId: approvalRequest.approvalId }],
+ });
+ expect(parkedSteps(cancelled.session)).toHaveLength(1);
+ return await runStep(cancelled.session, {
+ inputResponses: [
+ { optionId: "approve", requestId: approvalRequest.approvalId },
+ { optionId: "approve", requestId: secondApprovalRequest.approvalId },
+ ],
+ });
+ });
+
+ expect(execute).toHaveBeenCalledOnce();
+ expect(execute).toHaveBeenCalledWith(
+ secondToolCall.input,
+ expect.objectContaining({ toolCallId: secondToolCall.toolCallId }),
+ );
+ expect(parkedSteps(result.session)).toEqual([]);
+ });
+
it("executes approved siblings concurrently and exactly once each", async () => {
const bothStarted = Promise.withResolvers<void>();
let started = 0;
diff --git a/packages/eve/src/public/channels/auth.ts b/packages/eve/src/public/channels/auth.ts
index 77017050f..69aa8b870 100644
--- a/packages/eve/src/public/channels/auth.ts
+++ b/packages/eve/src/public/channels/auth.ts
@@ -8,6 +8,7 @@
import { areTokenClaimMatchersSatisfied } from "#channel/auth/token-claims.js";
import { decodeJwt } from "#compiled/jose/index.js";
+import { ANONYMOUS_SESSION_AUTH_CONTEXT } from "#channel/principal-identity.js";
import type { SessionAuthContext } from "#channel/types.js";
import { isEveDevEnvironment } from "#internal/application/dev-environment.js";
import { createLogger } from "#internal/logging.js";
@@ -843,13 +844,6 @@ function isLocalDevelopmentServer(): boolean {
return isEveDevEnvironment();
}
-const ANONYMOUS_SESSION_AUTH_CONTEXT: SessionAuthContext = {
- attributes: {},
- authenticator: "none",
- principalId: "anonymous",
- principalType: "anonymous",
-};
-
const LOCAL_DEV_SESSION_AUTH_CONTEXT: SessionAuthContext = {
attributes: {},
authenticator: "local-dev",