Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): run approved calls as the requesting principal (#4515)

Rui9559de83b65e
diff --git a/.changeset/requester-approved-calls.md b/.changeset/requester-approved-calls.md
new file mode 100644
index 000000000..d2efb8f32
--- /dev/null
+++ b/.changeset/requester-approved-calls.md
@@ -0,0 +1,5 @@
+---
+"eve": minor
+---
+
+Approved calls now always run as the requester. This closes a privilege escalation: when another person approved a call, it ran with the approver's identity and credentials, so a requester could get a tool to act with access they don't have. The call now keeps the identity and credentials of the person whose turn requested it, and approved workflow and agent calls are rechecked before dispatch. This reverses the execution-identity rule from #4368. Tools that should only proceed for certain approvers can still check `response.principal` in their `approval.response` policy.
diff --git a/docs/tools/human-in-the-loop.md b/docs/tools/human-in-the-loop.md
index 6017f5f16..7d8ec3d80 100644
--- a/docs/tools/human-in-the-loop.md
+++ b/docs/tools/human-in-the-loop.md
@@ -232,7 +232,7 @@ The run picks back up exactly where it parked. Because the pause is durable, not
When a subagent requests input, eve emits the same `input.requested` event on its parent session. Answering through that parent session routes the response directly to the blocked child without invoking the parent model.
-If a tool is approved by another user, only the approved call runs with that user's auth. Subsequent tool calls in the turn stay with the original owner.
+Approval is consent only. An approved tool call runs with the requesting user's identity, connections, and credentials, including its policy recheck. The approver's access is never lent to the call. Subsequent tool calls in the turn also stay with the original owner.
For approval requests, a follow-up message that doesn't match an option steers the turn instead of answering it. eve cancels the turn's pending approval, so the call doesn't run and `input.resolved` reports `outcome: "ignored"`, and the model reads the message next. This happens even when the message is sent with `turnPolicy: "queue"`, because a turn held on a person can't end until they act. Calls the person already approved in the same batch still run. A message from someone other than the person the turn serves waits until the turn ends. Cancelling the turn withdraws its approval: the call doesn't run, `input.resolved` reports `outcome: "cancelled"`, and a later answer to it approves nothing.
diff --git a/e2e/fixtures/agent-tools-hitl/agent/lib/hitl/respond.ts b/e2e/fixtures/agent-tools-hitl/agent/lib/hitl/respond.ts
index 812f9c9f0..cea5c749d 100644
--- a/e2e/fixtures/agent-tools-hitl/agent/lib/hitl/respond.ts
+++ b/e2e/fixtures/agent-tools-hitl/agent/lib/hitl/respond.ts
@@ -9,6 +9,8 @@ export const SAY = {
oauthChecked: "Alice asks for an OAuth-checked change.",
firstEcho: "Alice asks for a guarded echo of the first note.",
secondEcho: "Alice asks for a guarded echo of the second note.",
+ callerAccess: "Alice asks to check release access.",
+ frozen: "Alice asks for the frozen change.",
retiring: "Alice asks for the retiring change.",
checkAccess: "Alice asks to check her Fixture Auth access.",
checkAndPublish: "Alice asks to check her access and publish the draft together.",
@@ -87,6 +89,13 @@ export function respond(request: MockModelRequest): MockModelResponse {
[call("echo-second", "guarded-echo", { note: "second" })],
() => `Second echo: ${outcome("echo-second")}.`,
),
+ [SAY.callerAccess]: () =>
+ run(
+ [call("caller-access", "caller-access")],
+ () => `Release access: ${outcome("caller-access")}.`,
+ ),
+ [SAY.frozen]: () =>
+ run([call("frozen", "frozen-change")], () => `Frozen change: ${outcome("frozen")}.`),
[SAY.retiring]: () =>
run([call("retiring", "retiring-change")], () => `Retiring change: ${outcome("retiring")}.`),
[SAY.checkAccess]: () =>
diff --git a/e2e/fixtures/agent-tools-hitl/agent/tools/caller-access.ts b/e2e/fixtures/agent-tools-hitl/agent/tools/caller-access.ts
new file mode 100644
index 000000000..c5a8ff345
--- /dev/null
+++ b/e2e/fixtures/agent-tools-hitl/agent/tools/caller-access.ts
@@ -0,0 +1,19 @@
+import { defineTool } from "eve/tools";
+import { always } from "eve/tools/approval";
+import { z } from "zod";
+
+export default defineTool({
+ description: "Check whether the executing caller has fixture release access.",
+ inputSchema: z.object({}),
+ approval: {
+ request: always(),
+ response: ({ response }) =>
+ response.principal.principalId === "bob"
+ ? { status: "allowed" }
+ : { status: "rejected", reason: "Only bob can approve this fixture." },
+ },
+ execute: (_input, ctx) => ({
+ actor: ctx.session.auth.current?.principalId ?? "none",
+ allowed: ctx.session.auth.current?.principalId === "bob",
+ }),
+});
diff --git a/e2e/fixtures/agent-tools-hitl/agent/tools/frozen-change.ts b/e2e/fixtures/agent-tools-hitl/agent/tools/frozen-change.ts
new file mode 100644
index 000000000..d43384d2a
--- /dev/null
+++ b/e2e/fixtures/agent-tools-hitl/agent/tools/frozen-change.ts
@@ -0,0 +1,29 @@
+import { defineState } from "eve/context";
+import { defineTool } from "eve/tools";
+import { z } from "zod";
+
+const executions = defineState("frozen-change.executions", () => 0);
+const freezeStarted = defineState("frozen-change.freeze-started", () => false);
+
+/** A freeze begins after consent, but applies only to the requesting caller. */
+export default defineTool({
+ description: "Apply the fixture change unless the requester's change freeze is on.",
+ inputSchema: z.object({}),
+ approval: {
+ request: ({ session }) =>
+ freezeStarted.get() && session.auth.current?.attributes?.flag === "freeze"
+ ? { type: "denied", reason: "A change freeze is in effect." }
+ : "user-approval",
+ response: ({ response }) => {
+ if (response.principal.principalId !== "bob")
+ return { status: "rejected", reason: "Only bob can approve this fixture." };
+ // Simulate a policy change between asking and execution. Bob is not frozen.
+ freezeStarted.update(() => true);
+ return { status: "allowed" };
+ },
+ },
+ async execute() {
+ executions.update((count) => count + 1);
+ return { change: "frozen", executions: executions.get() };
+ },
+});
diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/README.md b/e2e/fixtures/agent-tools-hitl/evals/hitl/README.md
index 843be9cef..57582455f 100644
--- a/e2e/fixtures/agent-tools-hitl/evals/hitl/README.md
+++ b/e2e/fixtures/agent-tools-hitl/evals/hitl/README.md
@@ -37,6 +37,8 @@ and [`agent-workflow-tools/evals/hitl`](../../../agent-workflow-tools/evals/hitl
| An answer to a request that is not open authorizes nothing | [stale-answer-authorizes-nothing](./approvals/stale-answer-authorizes-nothing.eval.ts) |
| A `once()` grant is reused | [once-grant-is-reused](./approvals/once-grant-is-reused.eval.ts) |
| An approved call runs with the asking step's tools | [approved-call-uses-asking-step-tools](./approvals/approved-call-uses-asking-step-tools.eval.ts) |
+| Approval keeps the requester's identity and permissions | [approved-call-keeps-requester](./approvals/approved-call-keeps-requester.eval.ts) |
+| A recheck denies a change frozen for the requester | [recheck-denies-at-run-time](./approvals/recheck-denies-at-run-time.eval.ts) |
| A rejected responder leaves the approval open | [rejected-responder-leaves-approval-open](./response-policies/rejected-responder-leaves-approval-open.eval.ts) |
| An allowed responder settles the approval | [allowed-responder-settles](./response-policies/allowed-responder-settles.eval.ts) |
| A responder's authorization, then settlement | [responder-authorization-then-settles](./response-policies/responder-authorization-then-settles.eval.ts) |
diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/approvals/approved-call-keeps-requester.eval.ts b/e2e/fixtures/agent-tools-hitl/evals/hitl/approvals/approved-call-keeps-requester.eval.ts
new file mode 100644
index 000000000..ddcb476a3
--- /dev/null
+++ b/e2e/fixtures/agent-tools-hitl/evals/hitl/approvals/approved-call-keeps-requester.eval.ts
@@ -0,0 +1,29 @@
+import { defineEval } from "eve/evals";
+import {
+ SAY,
+ aliceSession,
+ answers,
+ approvalFor,
+ asAlice,
+ asBob,
+ expectResolved,
+} from "../helpers.ts";
+
+export default defineEval({
+ description: "Approval supplies consent, not the responder's release access.",
+ tags: ["hitl", "approval"],
+ timeoutMs: 60_000,
+ async test(t) {
+ const session = await aliceSession(t);
+ const request = approvalFor(await session.send(SAY.callerAccess, asAlice), "caller-access");
+ const approved = (await session.respond(answers("approve", request), asBob)).expectOk();
+ expectResolved(approved, request, "approved");
+ approved.event("approval.settled", {
+ data: { responderPrincipalId: "bob", outcome: "approved" },
+ });
+ approved.event("action.result", {
+ count: 1,
+ data: { result: { toolName: "caller-access", output: { actor: "alice", allowed: false } } },
+ });
+ },
+});
diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/approvals/recheck-denies-at-run-time.eval.ts b/e2e/fixtures/agent-tools-hitl/evals/hitl/approvals/recheck-denies-at-run-time.eval.ts
new file mode 100644
index 000000000..a39bdffd1
--- /dev/null
+++ b/e2e/fixtures/agent-tools-hitl/evals/hitl/approvals/recheck-denies-at-run-time.eval.ts
@@ -0,0 +1,46 @@
+import { defineEval } from "eve/evals";
+
+import {
+ ALICE,
+ SAY,
+ aliceSession,
+ answers,
+ approvalFor,
+ as,
+ asBob,
+ expectNotRun,
+ expectResolved,
+} from "../helpers.ts";
+
+/**
+ * Bob approves Alice's change as a freeze begins for Alice only. His
+ * approval stands, but eve checks the tool's policy again right before the
+ * call runs, and the freeze denies it: the change never runs.
+ */
+export default defineEval({
+ description: "An approved call whose policy now denies it does not run.",
+ tags: ["hitl", "approval"],
+ timeoutMs: 60_000,
+ async test(t) {
+ const session = await aliceSession(t);
+ const request = approvalFor(
+ await session.send(SAY.frozen, as(ALICE, "freeze")),
+ "frozen-change",
+ );
+
+ const frozen = (await session.respond(answers("approve", request), asBob)).expectOk();
+ expectResolved(frozen, request, "approved");
+ expectNotRun(frozen, "frozen-change");
+ frozen.event("action.result", {
+ count: 1,
+ data: {
+ status: "rejected",
+ result: {
+ output: { code: "TOOL_EXECUTION_DENIED", message: "A change freeze is in effect." },
+ toolName: "frozen-change",
+ },
+ },
+ });
+ frozen.event("message.completed", { data: { message: "Frozen change: not run." } });
+ },
+});
diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/helpers.ts b/e2e/fixtures/agent-tools-hitl/evals/hitl/helpers.ts
index 8db4495b3..7291abc30 100644
--- a/e2e/fixtures/agent-tools-hitl/evals/hitl/helpers.ts
+++ b/e2e/fixtures/agent-tools-hitl/evals/hitl/helpers.ts
@@ -16,7 +16,7 @@ export const BOB = "bob";
export const RELEASE_MANAGER = "e2e-approval-responder";
/** Headers for one person on the scripted hitl model; `flag` feeds fixture policies. */
-export function as(principalId: string, flag?: "retire") {
+export function as(principalId: string, flag?: "retire" | "freeze") {
return {
headers: {
"x-eve-fixture-model": "hitl",
diff --git a/packages/eve/src/context/caller-scope.ts b/packages/eve/src/context/caller-scope.ts
deleted file mode 100644
index 7ad69a912..000000000
--- a/packages/eve/src/context/caller-scope.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import type { SessionAuthContext } from "#channel/types.js";
-import { type AlsContext, contextStorage } from "#context/container.js";
-import type { ContextKey } from "#context/key.js";
-import { AuthKey, type Session, SessionKey } from "#context/keys.js";
-
-/**
- * Runs `fn` with `caller` as the session's current caller. Writes still reach
- * the outer context; only reads of the caller change, so work running beside
- * `fn` in the same step keeps the outer caller.
- */
-export function runAsCaller<T>(caller: SessionAuthContext, fn: () => T): T {
- const outer = contextStorage.getStore();
- if (outer === undefined) return fn();
- return contextStorage.run(new CallerScope(outer, caller), fn);
-}
-
-class CallerScope implements AlsContext {
- readonly #caller: SessionAuthContext;
- readonly #outer: AlsContext;
-
- constructor(outer: AlsContext, caller: SessionAuthContext) {
- this.#outer = outer;
- this.#caller = caller;
- }
-
- get localDevRequest() {
- return this.#outer.localDevRequest;
- }
-
- get<T>(key: ContextKey<T>): T | undefined {
- if (key.name === AuthKey.name) return this.#caller as T;
- if (key.name === SessionKey.name) {
- const session = this.#outer.get(SessionKey);
- if (session === undefined) return undefined;
- const scoped: Session = { ...session, auth: { ...session.auth, current: this.#caller } };
- return scoped as T;
- }
- return this.#outer.get(key);
- }
-
- require<T>(key: ContextKey<T>): T {
- if (!this.has(key)) throw new Error(`Context key "${key.name}" is not set.`);
- return this.get(key) as T;
- }
-
- has<T>(key: ContextKey<T>): boolean {
- return key.name === AuthKey.name || this.#outer.has(key);
- }
-
- set<T>(key: ContextKey<T>, valueOrUpdater: T | ((current: T | undefined) => T)): T {
- return this.#outer.set(key, valueOrUpdater);
- }
-
- ensure<T>(key: ContextKey<T>, create: () => T): T {
- return this.#outer.ensure(key, create);
- }
-
- delete<T>(key: ContextKey<T>): boolean {
- return this.#outer.delete(key);
- }
-
- entries(): Iterable<readonly [ContextKey<unknown>, unknown]> {
- return this.#outer.entries();
- }
-
- setVirtualContext<T>(key: ContextKey<T>, value: T): void {
- this.#outer.setVirtualContext(key, value);
- }
-}
diff --git a/packages/eve/src/execution/coordination-dispatch-shared.ts b/packages/eve/src/execution/coordination-dispatch-shared.ts
index 029b12c81..3781013d3 100644
--- a/packages/eve/src/execution/coordination-dispatch-shared.ts
+++ b/packages/eve/src/execution/coordination-dispatch-shared.ts
@@ -1,4 +1,3 @@
-import type { SessionAuthContext } from "#channel/types.js";
/** Shared owner-side dispatch context preparation. */
import { buildAdapterContext } from "#channel/adapter-context.js";
@@ -106,7 +105,7 @@ export async function prepareCoordinationDispatch(input: {
waiting.event.turnId || activeTurnId(turnPosition(storedProjection(durableSession.state)));
const ctx = await deserializeContext(input.serializedContext);
const prepared = await prepareActionDispatch({
- batch: { approvers: waiting.approvers, event: { ...waiting.event, turnId }, requests },
+ batch: { event: { ...waiting.event, turnId }, requests },
ctx,
durableSession,
plan: () => requests,
@@ -116,7 +115,6 @@ export async function prepareCoordinationDispatch(input: {
}
interface DispatchBatch {
- readonly approvers?: Readonly<Record<string, SessionAuthContext>>;
readonly event: {
readonly sequence: number;
readonly stepIndex: number;
diff --git a/packages/eve/src/execution/coordination-dispatch-step.ts b/packages/eve/src/execution/coordination-dispatch-step.ts
index f5f8423d1..8921530ae 100644
--- a/packages/eve/src/execution/coordination-dispatch-step.ts
+++ b/packages/eve/src/execution/coordination-dispatch-step.ts
@@ -59,9 +59,8 @@ async function dispatchCoordination(
for (const task of prepared.plan) {
const start = {
agentContext: captureAgentSessionContext(prepared, task.callId, agentLimits),
- // An approved call runs as whoever approved it; the rest as the turn's caller.
auth: {
- current: batch.approvers?.[task.callId] ?? prepared.auth,
+ current: prepared.auth,
initiator: prepared.initiatorAuth,
},
batchEvent: batch.event,
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 6dbda7d6b..91311085e 100644
--- a/packages/eve/src/execution/session/approval-caller.integration.test.ts
+++ b/packages/eve/src/execution/session/approval-caller.integration.test.ts
@@ -246,7 +246,7 @@ function turnBoundaries(stage: Stage) {
describe("approval caller", () => {
it.each([false, true])(
- "runs only the call another person approves as that person (unmatched stub: %s)",
+ "runs a call another person approves as its requester (unmatched stub: %s)",
async (withStub) => {
const { secondRequesters, seen, stages } = await withChainRun(
`approval-caller-${withStub}`,
@@ -275,7 +275,7 @@ describe("approval caller", () => {
["turn.completed turn_0"],
]);
expect(seen).toEqual([
- { tool: "deploy_change", caller: "bob" },
+ { tool: "deploy_change", caller: "alice" },
{ tool: "read_notes", caller: "alice" },
{ tool: "publish_change", caller: "alice" },
]);
@@ -300,12 +300,12 @@ describe("approval caller", () => {
["turn.completed turn_0"],
]);
expect(seen).toEqual([
- { tool: "deploy_change", caller: "bob" },
+ { tool: "deploy_change", caller: "alice" },
{ tool: "read_notes", caller: "alice" },
]);
}, 60_000);
- it("starts an approved workflow tool's run as its approver", async () => {
+ it("starts an approved workflow tool's run as its requester", async () => {
const { stages } = await withChainRun(
"approval-caller-workflow",
async (run) => {
@@ -333,7 +333,7 @@ describe("approval caller", () => {
.flat()
.flatMap((event) => (event.type === "action.result" ? [event.data.result] : []));
expect(results.find((result) => result.callId === "call-report_caller")?.output).toEqual({
- caller: "bob",
+ caller: "alice",
});
}, 60_000);
@@ -353,7 +353,7 @@ describe("approval caller", () => {
);
expect(seen).toEqual([
- { tool: "deploy_change", caller: "bob" },
+ { tool: "deploy_change", caller: "alice" },
{ tool: "read_notes", caller: "alice" },
{ tool: "publish_change", caller: "alice" },
]);
@@ -383,7 +383,7 @@ describe("approval caller", () => {
]);
}, 60_000);
- it("runs approved calls in parallel, each as its own approver", async () => {
+ it("runs approved calls in parallel as their requester", async () => {
const { log, seen } = await withChainRun(
"approval-caller-parallel",
async (run) => {
@@ -397,13 +397,13 @@ describe("approval caller", () => {
expect(log.slice(0, 2).every((entry) => entry.startsWith("start "))).toBe(true);
expect(new Map(seen.map((entry) => [entry.tool, entry.caller]))).toEqual(
new Map([
- ["deploy_change", "bob"],
+ ["deploy_change", "alice"],
["publish_change", "alice"],
]),
);
}, 60_000);
- it("does not reuse an earlier approver for a later call with the same call id", async () => {
+ it("keeps requester identity when a later call repeats an approved call id", async () => {
// Some providers repeat call ids. Turn 1's report_caller is gated and Bob
// approves it; turn 2 calls it again ungated, with the same id.
const model = markMockModel(
@@ -458,6 +458,6 @@ describe("approval caller", () => {
? [(event.data.result.output as { caller: string }).caller]
: [],
);
- expect(callers).toEqual(["bob", "alice"]);
+ expect(callers).toEqual(["alice", "alice"]);
}, 60_000);
});
diff --git a/packages/eve/src/execution/session/turn-connection-approval.integration.test.ts b/packages/eve/src/execution/session/turn-connection-approval.integration.test.ts
index eb6b0e8c7..d56eb40c3 100644
--- a/packages/eve/src/execution/session/turn-connection-approval.integration.test.ts
+++ b/packages/eve/src/execution/session/turn-connection-approval.integration.test.ts
@@ -703,8 +703,8 @@ describe("turn connection approval restoration", () => {
getApprovalAuditState(readDurableSession(resumed.sessionState).state).settlements,
).toEqual([expect.objectContaining({ outcome: "allowed", requestId: request.requestId })]);
expect(fixture.fetch).toHaveBeenCalledOnce();
- // Bob approved Alice's call, so the approved request goes out as Bob.
- expect(callerHeader(fixture.fetch.mock.calls[0])).toBe("bob");
+ // Bob supplies consent; the connection request still uses Alice's credentials.
+ expect(callerHeader(fixture.fetch.mock.calls[0])).toBe("alice");
expect(suspendedSteps(readDurableSession(resumed.sessionState).state)).toEqual([]);
expect(resumed.serializedContext).not.toHaveProperty("eve.pendingConnectionCalls");
expect(fixture.events.filter((event) => event.type === "turn.started")).toHaveLength(1);
diff --git a/packages/eve/src/harness/hitl/approvals.ts b/packages/eve/src/harness/hitl/approvals.ts
index d27177620..8f2e5032c 100644
--- a/packages/eve/src/harness/hitl/approvals.ts
+++ b/packages/eve/src/harness/hitl/approvals.ts
@@ -1,4 +1,3 @@
-import type { SessionAuthContext } from "#channel/types.js";
import type { ModelMessage } from "ai";
import type { getApprovalAuditState } from "#harness/hitl/candidates.js";
@@ -117,11 +116,10 @@ export function parkOnApprovals(
};
}
-/** Approved workflow and agent calls join the runs their steps wait on, as their approvers. */
+/** Approved workflow and agent calls join the runs their requesting steps wait on. */
export function dispatch(
view: SessionView,
input: {
- readonly approvers: Readonly<Record<string, SessionAuthContext>>;
readonly tasks: readonly RuntimeWorkflowTaskRequest[];
},
): Transition {
@@ -130,15 +128,9 @@ export function dispatch(
const tasks = input.tasks.filter((task) => calls.has(task.callId));
if (tasks.length === 0) return step;
const dispatched = withoutApproved(step, new Set(tasks.map((task) => task.callId)));
- const approvers = { ...step.approvers };
- for (const { callId } of tasks) {
- const approver = input.approvers[callId];
- if (approver !== undefined) approvers[callId] = approver;
- }
return {
...dispatched,
tasks: [...step.tasks, ...tasks],
- ...(Object.keys(approvers).length > 0 && { approvers }),
};
});
return { events: [], turn: { ...view.turn, suspended } };
diff --git a/packages/eve/src/harness/hitl/approved-call-callers.ts b/packages/eve/src/harness/hitl/approved-call-callers.ts
deleted file mode 100644
index 4b3b79b8e..000000000
--- a/packages/eve/src/harness/hitl/approved-call-callers.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-import type { SessionAuthContext } from "#channel/types.js";
-import { runAsCaller } from "#context/caller-scope.js";
-import { contextStorage } from "#context/container.js";
-import { ContextKey } from "#context/key.js";
-import { approverOfRequest } from "./candidates.js";
-import type { InputRequest } from "#shared/input.js";
-import type { SessionStateMap } from "#harness/types.js";
-
-/**
- * The person who approved each call the current step replays, by call id.
- * Step-local: set before the replay, never serialized.
- */
-const ApprovedCallCallersKey = new ContextKey<ReadonlyMap<string, SessionAuthContext>>(
- "eve.approvedCallCallers",
-);
-
-/** Who approved each of the `approved` calls, by call id. */
-export function approversOf(
- approved: readonly InputRequest[],
- state: SessionStateMap | undefined,
-): Readonly<Record<string, SessionAuthContext>> {
- const approvers: Record<string, SessionAuthContext> = {};
- for (const request of approved) {
- if (request.action === undefined) continue;
- const approver = approverOfRequest(state, request.requestId);
- if (approver !== undefined) approvers[request.action.callId] = approver;
- }
- return approvers;
-}
-
-/**
- * Records who approved each of the `approved` calls, so each runs as its approver while the rest
- * of the turn keeps the turn's own caller.
- */
-export function setApprovedCallCallers(
- approved: readonly InputRequest[],
- state: SessionStateMap | undefined,
-): void {
- const ctx = contextStorage.getStore();
- if (ctx === undefined) return;
- ctx.setVirtualContext(
- ApprovedCallCallersKey,
- new Map(Object.entries(approversOf(approved, state))),
- );
-}
-
-/** Runs `fn` as the call's approver when `callId` is an approved call; otherwise as is. */
-export function runAsApprover<T>(callId: string | undefined, fn: () => T): T {
- const approver =
- callId === undefined
- ? undefined
- : contextStorage.getStore()?.get(ApprovedCallCallersKey)?.get(callId);
- return approver === undefined ? fn() : runAsCaller(approver, fn);
-}
-
-/** A streaming call's body runs on each `next()`, so each one runs as the approver too. */
-export async function* iterateAsApprover<T>(
- callId: string | undefined,
- iterable: AsyncIterable<T>,
-): AsyncIterable<T> {
- const iterator = iterable[Symbol.asyncIterator]();
- try {
- while (true) {
- const result = await runAsApprover(callId, () => iterator.next());
- if (result.done === true) return;
- yield result.value;
- }
- } finally {
- await iterator.return?.();
- }
-}
diff --git a/packages/eve/src/harness/hitl/approved-calls.ts b/packages/eve/src/harness/hitl/approved-calls.ts
index 4539ec1b6..9e4bd4425 100644
--- a/packages/eve/src/harness/hitl/approved-calls.ts
+++ b/packages/eve/src/harness/hitl/approved-calls.ts
@@ -122,32 +122,14 @@ export async function runApprovedCalls(input: {
approvedTools: input.approvedTools,
});
if (recheck.denied) {
- // The policy refused the call it approved earlier, so it doesn't run.
- await input.publish(
- createActionResultEvent({
- ...at,
- rejected: true,
- result: {
- callId,
- isError: true,
- kind: "tool-result",
- output: {
- code: "TOOL_EXECUTION_DENIED",
- message: recheck.reason ?? TOOL_EXECUTION_DENIED_MESSAGE,
- tool: { result: "not_run" },
- },
- toolName,
- },
+ settled.push(
+ await rejectApprovedCall({
+ request,
+ reason: recheck.reason,
+ position: at,
+ publish: input.publish,
}),
);
- settled.push({
- part: {
- output: { reason: recheck.reason, type: "execution-denied" },
- toolCallId: callId,
- toolName,
- type: "tool-result",
- },
- });
return { settled, toolResults };
}
let output: unknown;
@@ -278,6 +260,45 @@ function interruptedResult(callId: string, toolName: string): ApprovedCallResult
};
}
+/** Records an approved call refused by its final request-policy check. */
+export async function rejectApprovedCall(input: {
+ readonly request: InputRequest;
+ readonly reason?: string;
+ readonly position: {
+ readonly sequence: number;
+ readonly stepIndex: number;
+ readonly turnId: string;
+ };
+ readonly publish: HandleEventFn;
+}): Promise<ApprovedCallResult> {
+ const { callId, toolName } = input.request.action;
+ await input.publish(
+ createActionResultEvent({
+ ...input.position,
+ rejected: true,
+ result: {
+ callId,
+ isError: true,
+ kind: "tool-result",
+ toolName,
+ output: {
+ code: "TOOL_EXECUTION_DENIED",
+ message: input.reason ?? TOOL_EXECUTION_DENIED_MESSAGE,
+ tool: { result: "not_run" },
+ },
+ },
+ }),
+ );
+ return {
+ part: {
+ output: { reason: input.reason, type: "execution-denied" },
+ toolCallId: callId,
+ toolName,
+ type: "tool-result",
+ },
+ };
+}
+
type ToolExecutionStart = Parameters<NonNullable<Telemetry["onToolExecutionStart"]>>[0];
type ToolExecutionEnd = Parameters<NonNullable<Telemetry["onToolExecutionEnd"]>>[0];
diff --git a/packages/eve/src/harness/hitl/candidates.ts b/packages/eve/src/harness/hitl/candidates.ts
index 26ee28891..35efe8105 100644
--- a/packages/eve/src/harness/hitl/candidates.ts
+++ b/packages/eve/src/harness/hitl/candidates.ts
@@ -37,8 +37,6 @@ export interface ApprovalResponderIdentity {
export interface ApprovalSettlementAuditRecord {
readonly actor: ApprovalResponderIdentity;
- /** The approver's full auth, which the approved call runs as. Present only when allowed. */
- readonly approver?: SessionAuthContext;
/** `unavailable`: the request's entry was gone, so its call is reported unavailable, never run. */
readonly outcome: "allowed" | "cancelled" | "unavailable";
readonly requestId: string;
@@ -312,7 +310,6 @@ function settleRequest(input: {
const settlement: ApprovalSettlementAuditRecord = {
actor: projectResponder(input.responder),
- ...(input.outcome === "allowed" && { approver: input.responder }),
candidateId: input.candidateId,
outcome: input.outcome,
requestId: input.requestId,
@@ -465,11 +462,3 @@ export function retireActiveCandidates(
}
return next;
}
-
-/** The full auth of whoever approved `requestId`, when it was allowed. */
-export function approverOfRequest(
- state: SessionStateMap | undefined,
- requestId: string,
-): SessionAuthContext | undefined {
- return readApprovalState(state).settlements[requestId]?.approver;
-}
diff --git a/packages/eve/src/harness/hitl/intake.ts b/packages/eve/src/harness/hitl/intake.ts
index 161428761..496804f05 100644
--- a/packages/eve/src/harness/hitl/intake.ts
+++ b/packages/eve/src/harness/hitl/intake.ts
@@ -25,11 +25,11 @@ import {
stepForRequest,
withdrawSignIns,
} from "./approvals.js";
-import { runApprovedCalls } from "./approved-calls.js";
+import { rejectApprovedCall, runApprovedCalls, type ApprovedCallResult } from "./approved-calls.js";
import { getApprovalAuditState, retireActiveCandidates } from "./candidates.js";
import { coordinateApprovalDelivery } from "./coordinator.js";
import { deliver, resolveTypedApproval, turnInputOnly, withoutTurnInput } from "./delivery.js";
-import { approversOf, setApprovedCallCallers } from "./approved-call-callers.js";
+import { recheckApprovedCall } from "#harness/tools.js";
import type { InputRequest } from "#shared/input.js";
import type { InstrumentationAttempt } from "#instrumentation/runtime.js";
import { activeTurnId } from "#harness/session-machine/view.js";
@@ -233,14 +233,33 @@ export function hasApprovedWork(step: Step): boolean {
*/
export async function dispatchApprovedWorkflows(step: Step, work: ApprovedWork): Promise<boolean> {
const tasks: RuntimeWorkflowTaskRequest[] = [];
- const approved: InputRequest[] = [];
+ const denied: ApprovedCallResult[] = [];
for (const parked of step.view().turn.suspended) {
const tools = work.toolsOf(parked);
- const requests = (parked.approved ?? []).filter(
- (request) => tools.get(request.action.toolName)?.workflowId !== undefined,
- );
+ const requests: InputRequest[] = [];
+ for (const request of parked.approved ?? []) {
+ const tool = tools.get(request.action.toolName);
+ if (tool?.workflowId === undefined) continue;
+ const recheck = await recheckApprovedCall(tool, {
+ abortSignal: step.config.abortSignal,
+ callId: request.action.callId,
+ input: request.action.input,
+ approvedTools: grantedApprovalKeys(step.view(), (approved) =>
+ tools.get(approved.action.toolName)?.approvalKey?.(approved.action.input),
+ ),
+ });
+ if (recheck.denied) {
+ denied.push(
+ await rejectApprovedCall({
+ request,
+ reason: recheck.reason,
+ position: step.position(),
+ publish: step.publish,
+ }),
+ );
+ } else requests.push(request);
+ }
if (requests.length === 0) continue;
- approved.push(...requests);
const dispatched = collectWorkflowCalls({
session: step.session,
toolCalls: requests.map(({ action }) => ({
@@ -254,10 +273,9 @@ export async function dispatchApprovedWorkflows(step: Step, work: ApprovedWork):
step.session = dispatched.session;
tasks.push(...dispatched.workflowRequests);
}
+ if (denied.length > 0) await step.apply(settle(step.view(), { results: denied }));
if (tasks.length === 0) return false;
- await step.apply(
- dispatch(step.view(), { approvers: approversOf(approved, step.session.state), tasks }),
- );
+ await step.apply(dispatch(step.view(), { tasks }));
if (tasks.some((task) => task.entry.entryPoint === "execute")) {
await step.apply(hold(step.view(), { on: "tasks" }));
}
@@ -267,7 +285,7 @@ export async function dispatchApprovedWorkflows(step: Step, work: ApprovedWork):
/**
* Runs approved local calls once the step has started and its budget allows it, as the AI SDK ran
* them before the model read their results: each with the tools of the step that asked, as
- * whoever approved it, and in the step's first attempt. A call that needs a sign-in holds the
+ * the turn's requester, and in the step's first attempt. A call that needs a sign-in holds the
* turn.
*/
export async function runApprovedLocalCalls(
@@ -290,7 +308,6 @@ export async function runApprovedLocalCalls(
.filter((name) => tools.get(name)?.frameworkTool === true),
),
);
- setApprovedCallCallers(approved, step.session.state);
const position = step.position();
const attempt =
approved.length === 0
diff --git a/packages/eve/src/harness/session-machine/state.ts b/packages/eve/src/harness/session-machine/state.ts
index bff2c6f02..3c167153c 100644
--- a/packages/eve/src/harness/session-machine/state.ts
+++ b/packages/eve/src/harness/session-machine/state.ts
@@ -36,8 +36,6 @@ export interface SuspendedStep {
readonly approved?: readonly InputRequest[];
/** Workflow and agent calls the runtime runs for the step. */
readonly tasks: readonly RuntimeWorkflowTaskRequest[];
- /** Who approved each task an approval started, by call id: the task runs as them. */
- readonly approvers?: Readonly<Record<string, SessionAuthContext>>;
readonly responseAuthRequiredRequestIds?: readonly string[];
/** The caller whose turn parked the step; `null` when unauthenticated. */
readonly requester?: SessionAuthContext | null;
diff --git a/packages/eve/src/harness/session-machine/view.ts b/packages/eve/src/harness/session-machine/view.ts
index 3295f8a5f..75c5c08ba 100644
--- a/packages/eve/src/harness/session-machine/view.ts
+++ b/packages/eve/src/harness/session-machine/view.ts
@@ -1,4 +1,3 @@
-import type { SessionAuthContext } from "#channel/types.js";
import type { TokenUsage } from "#shared/token-usage.js";
import type { ModelMessage } from "ai";
@@ -122,8 +121,6 @@ export interface RuntimeWait {
readonly callIds: readonly string[];
readonly tasks: readonly RuntimeWorkflowTaskRequest[];
readonly taskToolCalls: readonly TaskToolCall[];
- /** Who approved each task an approval started, by call id. */
- readonly approvers: Readonly<Record<string, SessionAuthContext>>;
}
/** The calls suspended steps wait on the runtime for, or `undefined` when none do. */
@@ -138,7 +135,6 @@ export function runtimeWait(state: SessionStateMap | undefined): RuntimeWait | u
const tasks = waiting.flatMap((entry) => entry.tasks);
const taskToolCalls = waiting.flatMap((entry) => entry.taskToolCalls);
return {
- approvers: Object.assign({}, ...waiting.map((entry) => entry.step.approvers)),
callIds: [...tasks.map((task) => task.callId), ...taskToolCalls.map((call) => call.callId)],
event: first.step.event,
taskToolCalls,
diff --git a/packages/eve/src/harness/tools.ts b/packages/eve/src/harness/tools.ts
index 7a91a4426..48ea2b836 100644
--- a/packages/eve/src/harness/tools.ts
+++ b/packages/eve/src/harness/tools.ts
@@ -18,7 +18,6 @@ import { createLogger } from "#internal/logging.js";
import type { ToolExecuteOptions } from "#tools/definition.js";
import { isAsyncIterable } from "#shared/async-iterable.js";
import { executeWithToolStub } from "#tool-stubs/execute.js";
-import { iterateAsApprover, runAsApprover } from "#harness/hitl/approved-call-callers.js";
const log = createLogger("harness.tools");
@@ -105,19 +104,14 @@ export function wrapToolExecute(
const run = () => execute(input, options);
let output: unknown;
try {
- output = runAsApprover(options.toolCallId, () =>
- call === undefined ? run() : executeWithToolStub(call.toolName, call.input, options, run),
- );
+ output =
+ call === undefined ? run() : executeWithToolStub(call.toolName, call.input, options, run);
} catch (error) {
return Promise.reject(error);
}
if (isAsyncIterable(output)) {
- return normalizeToolExecuteIterable(
- iterateAsApprover(options.toolCallId, output),
- toolName,
- options,
- );
+ return normalizeToolExecuteIterable(output, toolName, options);
}
return Promise.resolve(output).then((value) =>
diff --git a/packages/eve/src/harness/workflow-approval-resume.integration.test.ts b/packages/eve/src/harness/workflow-approval-resume.integration.test.ts
index 527b4d2f9..8d52c238c 100644
--- a/packages/eve/src/harness/workflow-approval-resume.integration.test.ts
+++ b/packages/eve/src/harness/workflow-approval-resume.integration.test.ts
@@ -1,4 +1,5 @@
import { jsonSchema } from "ai";
+import type { ApprovalContext } from "#approval/definition.js";
import { MockLanguageModelV4 } from "ai/test";
import { describe, expect, it, vi } from "vitest";
import { ContextContainer, contextStorage } from "#context/container.js";
@@ -139,6 +140,52 @@ function resultCallIds(session: HarnessSession) {
}
describe("workflow approval resume (real AI SDK)", () => {
+ it.each(["workflow", "agent"])("rechecks an approved %s call before dispatch", async (kind) => {
+ let frozen = false;
+ const policy = vi.fn((ctx: ApprovalContext) =>
+ frozen && ctx.session.auth.current?.principalId === "user-1"
+ ? { type: "denied" as const, reason: "A change freeze is in effect." }
+ : ("user-approval" as const),
+ );
+ const tool = {
+ ...workflow("deploy", policy),
+ ...(kind === "agent" && { workflowId: "workflow//./agent/subagents/release//run" }),
+ };
+ const fixture = setup([tool]);
+ const initial = await fixture.step(fixture.session, { message: "Deploy Alice's release." });
+ const [request] = requests(initial.session);
+ expect(request).toBeDefined();
+ frozen = true;
+ const start = fixture.events.length;
+ const approved = await fixture.step(initial.session, {
+ inputResponses: [{ optionId: "approve", requestId: request!.requestId }],
+ });
+ expect(runtimeWait(approved.session.state)).toBeUndefined();
+ expect(policy.mock.calls.at(-1)?.[0].session.auth.current?.principalId).toBe("user-1");
+ expect(
+ fixture.events.slice(start).filter((event) => event.type === "action.result"),
+ ).toMatchObject([
+ {
+ data: {
+ status: "rejected",
+ result: {
+ output: {
+ code: "TOOL_EXECUTION_DENIED",
+ message: "A change freeze is in effect.",
+ },
+ },
+ },
+ },
+ ]);
+ expect(
+ approved.session.history
+ .flatMap((message) => (message.role === "tool" ? message.content : []))
+ .filter((part) => part.type === "tool-result"),
+ ).toMatchObject([
+ { output: { type: "execution-denied", reason: "A change freeze is in effect." } },
+ ]);
+ });
+
it("resumes the held turn before dispatch and replays accompanying input after completion", async () => {
const fixture = setup([workflow("deploy", always())]);
const initial = await fixture.step(fixture.session, { message: "Deploy Alice's release." });
diff --git a/scripts/guard-invariants.mjs b/scripts/guard-invariants.mjs
index e0f5e5c32..7fbd8f326 100644
--- a/scripts/guard-invariants.mjs
+++ b/scripts/guard-invariants.mjs
@@ -125,9 +125,8 @@
* so telemetry ownership survives renamed and namespaced tools.
* rule 50 — The human-in-the-loop lifecycle in `harness/hitl/` is
* reached only through its `index.ts`, its request vocabulary
- * (`approval-prompt`, `budget-request`), and the approvers that
- * approved calls run as (`approved-call-callers`), so replacing it
- * changes one seam.
+ * (`approval-prompt`, `budget-request`), so replacing it changes one
+ * seam.
* rule 51 — Only the session machine (`harness/session-machine/`) and the
* human-in-the-loop lifecycle it delegates to
* (`harness/hitl/`) build lifecycle events and read the
@@ -502,7 +501,7 @@ function checkRule47(posix, lines, violations) {
const HUMAN_INPUT_DIR = "packages/eve/src/harness/hitl/";
const HUMAN_INPUT_PRIVATE_IMPORT_RE =
- /["'](?:#harness\/|(?:\.\.?\/)+)hitl\/(?!(?:index|approval-prompt|approved-call-callers|budget-request)\.js["'])/;
+ /["'](?:#harness\/|(?:\.\.?\/)+)hitl\/(?!(?:index|approval-prompt|budget-request)\.js["'])/;
/** @param {string} posix @param {string[]} lines @param {Violation[]} violations */
function checkRule50(posix, lines, violations) {