The Open Framework for Building Agents
[2/2] fix(eve): run only the approved call as its approver (#4364)
Ben Pankowa8262be2ba5c
diff --git a/.changeset/approval-caller-scope.md b/.changeset/approval-caller-scope.mdnew file mode 100644index 000000000..e8023c2f2--- /dev/null+++ b/.changeset/approval-caller-scope.md@@ -0,0 +1,5 @@+---+"eve": patch+---++When someone other than the person who asked approves a tool call, only that call now runs as the approver. Before, the approver became the caller for the rest of the turn, so later tool calls and approvals in that turn also ran with the approver's identity and credentials.diff --git a/docs/tools/human-in-the-loop.md b/docs/tools/human-in-the-loop.mdindex c69595941..b3d451d86 100644--- a/docs/tools/human-in-the-loop.md+++ b/docs/tools/human-in-the-loop.md@@ -226,6 +226,8 @@ The run picks back up exactly where it parked. Because the pause is durable, notWhen 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.+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.See [Sessions, runs & streaming](/docs/concepts/sessions-runs-and-streaming) for the full event and resume contract that this builds on.diff --git a/packages/eve/src/context/caller-scope.ts b/packages/eve/src/context/caller-scope.tsnew file mode 100644index 000000000..7ad69a912--- /dev/null+++ b/packages/eve/src/context/caller-scope.ts@@ -0,0 +1,69 @@+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.tsindex ea6a48396..981c8a609 100644--- a/packages/eve/src/execution/coordination-dispatch-shared.ts+++ b/packages/eve/src/execution/coordination-dispatch-shared.ts@@ -1,3 +1,4 @@+import type { SessionAuthContext } from "#channel/types.js";/** Shared owner-side dispatch context preparation. */import { buildAdapterContext } from "#channel/adapter-context.js";@@ -110,6 +111,7 @@ export async function prepareCoordinationDispatch(input: {const ctx = await deserializeContext(input.serializedContext);const prepared = await prepareActionDispatch({batch: {+ approvers: pending.approvers,event,requests,},@@ -135,6 +137,7 @@ 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.tsindex 00bcf7dca..f157cee99 100644--- a/packages/eve/src/execution/coordination-dispatch-step.ts+++ b/packages/eve/src/execution/coordination-dispatch-step.ts@@ -56,7 +56,11 @@ async function dispatchCoordination(for (const task of prepared.plan) {const start = {agentContext: captureAgentSessionContext(prepared, task.callId, agentLimits),- auth: { current: prepared.auth, initiator: prepared.initiatorAuth },+ // An approved call runs as whoever approved it; the rest as the turn's caller.+ auth: {+ current: batch.approvers?.[task.callId] ?? prepared.auth,+ initiator: prepared.initiatorAuth,+ },batchEvent: batch.event,owner: input.workflowToolRunOwner,parentSession: prepared.parentSession,diff --git a/packages/eve/src/execution/session/active-turn.ts b/packages/eve/src/execution/session/active-turn.tsindex ab6317677..f50487ad3 100644--- a/packages/eve/src/execution/session/active-turn.ts+++ b/packages/eve/src/execution/session/active-turn.ts@@ -3,6 +3,7 @@ import { mapHeldInputResponsesStep } from "#execution/proxied-deliver-step.js";import { routeDeliverToChildren } from "#execution/route-child-delivery.js";import { admitSessionInboxPayload } from "#execution/session/admission.js";import {+ isSteeringDelivery,isSteeringMessage,type SteeringOptions,type SteeringTurn,@@ -202,8 +203,13 @@ export class ActiveTurn {delivery = mapped.delivery;}this.admitted.delete(sequence);- this.input.queue.replaceDelivery(sequence, undefined);- return delivery;+ // Someone else's answers settle the held request, but the rest of their+ // delivery waits for the turn to end, as their messages do.+ const split = isSteeringDelivery(delivery, this.identity, { heldOnPerson: true })+ ? undefined+ : splitAnswers(delivery);+ this.input.queue.replaceDelivery(sequence, split?.rest);+ return split?.answers ?? delivery;}return undefined;}@@ -297,3 +303,20 @@ function asBoundaryMessage(event: RuntimeEvent): WorkflowToolRunMessage | undefiif (event.message.kind === "agent-started") return event.message;return undefined;}++function splitAnswers(delivery: DeliverHookPayload): {+ readonly answers: DeliverHookPayload;+ readonly rest: DeliverHookPayload | undefined;+} {+ const answers = delivery.payloads.flatMap((payload) =>+ payload.inputResponses === undefined ? [] : [{ inputResponses: payload.inputResponses }],+ );+ const rest = delivery.payloads.flatMap((payload) => {+ const { inputResponses: _answers, ...other } = payload;+ return Object.keys(other).length === 0 ? [] : [other];+ });+ return {+ answers: { ...delivery, payloads: answers },+ rest: rest.length === 0 ? undefined : { ...delivery, payloads: rest },+ };+}diff --git a/packages/eve/src/execution/session/answer-caller.test.ts b/packages/eve/src/execution/session/answer-caller.test.tsnew file mode 100644index 000000000..f0f564441--- /dev/null+++ b/packages/eve/src/execution/session/answer-caller.test.ts@@ -0,0 +1,82 @@+import { describe, expect, it } from "vitest";+import type { SessionAuthContext } from "#channel/types.js";+import { attributeAnswers } from "#execution/session/answer-caller.js";+import { appendPendingInputBatch } from "#harness/pending-input-batches.js";+import type { InputRequest } from "#shared/input.js";++const approval: InputRequest = {+ action: { callId: "call-1", input: {}, kind: "tool-call", toolName: "deploy" },+ display: "confirmation",+ kind: "tool-approval",+ options: [+ { id: "approve", label: "Approve" },+ { id: "cancel", label: "Cancel" },+ ],+ prompt: "Approve tool call: deploy",+ requestId: "approval-1",+};+const question: InputRequest = {+ action: { callId: "call-2", input: {}, kind: "tool-call", toolName: "ask" },+ kind: "question",+ options: [{ id: "saturday", label: "Saturday" }],+ prompt: "Which day?",+ requestId: "question-1",+};+const bob: SessionAuthContext = {+ attributes: { team: "infra" },+ authenticator: "test",+ principalId: "bob",+ principalType: "user",+};+const state = appendPendingInputBatch({+ requests: [approval, question],+ responseMessages: [],+ session: {+ agent: { modelReference: { id: "test" }, system: "", tools: [] },+ compaction: { recentWindowSize: 10, threshold: 0.8 },+ continuationToken: "test",+ history: [],+ sessionId: "session-1",+ },+}).state;+const approve = { optionId: "approve", requestId: approval.requestId };+const saturday = { optionId: "saturday", requestId: question.requestId };++describe("attributeAnswers", () => {+ it("carries the responder on approval answers and leaves other answers plain", () => {+ expect(+ attributeAnswers({+ responder: bob,+ state,+ stepInput: { inputResponses: [approve, saturday] },+ }),+ ).toEqual({+ attributedInputResponses: [{ auth: bob, response: approve }],+ inputResponses: [saturday],+ });+ });++ // Channels such as Discord deliver button presses with `auth: null`.+ it("attributes an approval sent with null auth to no one, never to the turn's caller", () => {+ expect(+ attributeAnswers({ responder: null, state, stepInput: { inputResponses: [approve] } }),+ ).toEqual({ attributedInputResponses: [{ auth: null, response: approve }] });+ });++ it("leaves a message or a stale answer to its sender", () => {+ expect(+ attributeAnswers({+ responder: bob,+ state,+ stepInput: { inputResponses: [approve], message: "Also do the other thing." },+ }),+ ).toBeUndefined();+ expect(+ attributeAnswers({+ responder: bob,+ state,+ stepInput: { inputResponses: [{ optionId: "approve", requestId: "answered-earlier" }] },+ }),+ ).toBeUndefined();+ });+});diff --git a/packages/eve/src/execution/session/answer-caller.ts b/packages/eve/src/execution/session/answer-caller.tsnew file mode 100644index 000000000..fbe11ff1c--- /dev/null+++ b/packages/eve/src/execution/session/answer-caller.ts@@ -0,0 +1,47 @@+import type { SessionAuthContext } from "#channel/types.js";+import { getPendingInputBatches } from "#harness/pending-input-batches.js";+import type { SessionStateMap, StepInput } from "#harness/types.js";++/**+ * Answering a request does not make the responder the turn's caller. When+ * `stepInput` only answers pending requests, returns it with each approval+ * answer carrying its responder, so approval policies and the approved call+ * see the responder while the turn keeps its caller. Returns `undefined` when+ * the input carries anything else, such as a message or a stale answer; its+ * sender becomes the caller.+ */+export function attributeAnswers(input: {+ readonly responder: SessionAuthContext | null;+ readonly state: SessionStateMap | undefined;+ readonly stepInput: StepInput | undefined;+}): StepInput | undefined {+ const { stepInput } = input;+ const responses = stepInput?.inputResponses ?? [];+ if (stepInput === undefined || stepInput.message !== undefined || responses.length === 0) {+ return undefined;+ }+ const requests = new Map(+ getPendingInputBatches(input.state).flatMap((batch) =>+ batch.requests.map((request) => [request.requestId, request.kind] as const),+ ),+ );+ if (!responses.every((response) => requests.has(response.requestId))) return undefined;++ const approvals = responses.filter(+ (response) => requests.get(response.requestId) === "tool-approval",+ );+ const others = responses.filter(+ (response) => requests.get(response.requestId) !== "tool-approval",+ );+ // An unauthenticated approval stays attributed to no one; it must never pass+ // as the turn's caller.+ const { inputResponses: _answered, ...rest } = stepInput;+ const result: StepInput = {+ ...rest,+ attributedInputResponses: [+ ...(stepInput.attributedInputResponses ?? []),+ ...approvals.map((response) => ({ auth: input.responder, response })),+ ],+ };+ return others.length === 0 ? result : { ...result, inputResponses: others };+}diff --git a/packages/eve/src/execution/session/approval-caller.integration.test.ts b/packages/eve/src/execution/session/approval-caller.integration.test.tsnew file mode 100644index 000000000..1c9304140--- /dev/null+++ b/packages/eve/src/execution/session/approval-caller.integration.test.ts@@ -0,0 +1,428 @@+import { MockLanguageModelV4 } from "ai/test";+import { describe, expect, it } from "vitest";+import { markMockModel } from "#internal/mock-model-identity.js";+import {+ textStreamResult,+ toolCallStreamResult,+ toolCallsStreamResult,+} from "#internal/testing/approval-resume.js";+import { defineAgent } from "#public/definitions/agent.js";+import { defineDynamic } from "#dynamic/definition.js";+import type { Approval } from "#approval/definition.js";+import { workflowEntry } from "#execution/session/entry.js";+import {+ sessionCommandHookToken,+ sessionInboxHookToken,+} from "#execution/session-inbox/address.js";+import { createTestRuntime } from "#internal/testing/app-harness.js";+import { buildSerializedContext, withTimeout } from "#internal/testing/entry-test-helpers.js";+import { captureTurnEvents, filterEventsByType } from "#internal/testing/events.js";+import { resumeHook, start } from "#internal/workflow/runtime.js";+import { always } from "#tools/approval/policies.js";+import { defineTool } from "#tools/definition.js";+import {+ type WorkflowExecuteToolDefinition,+ defineWorkflowTool,+} from "#tools/workflow-definition.js";+import { reportCallerWorkflow } from "#internal/testing/workflow-tool-fixtures.js";++// Scripted model: calls each tool the first message names, in the order it+// names them, once each, then replies. "in parallel" calls them all in one step.+const scriptedModel = markMockModel(+ new MockLanguageModelV4({+ doStream: async ({ prompt, tools }) => {+ const first = JSON.stringify(prompt.find((message) => message.role === "user")?.content);+ const chain = (tools ?? [])+ .map((tool) => tool.name)+ .filter((name) => first.includes(name))+ .sort((a, b) => first.indexOf(a) - first.indexOf(b));+ const done = new Set(+ prompt.flatMap((message) =>+ message.role === "tool"+ ? message.content.flatMap((part) =>+ part.type === "tool-result" ? [part.toolName] : [],+ )+ : [],+ ),+ );+ if (first.includes("in parallel")) {+ return done.size > 0+ ? textStreamResult("All done.")+ : toolCallsStreamResult(+ chain.map((name) => ({ input: "{}", toolCallId: `call-${name}`, toolName: name })),+ );+ }+ const next = chain.find((name) => !done.has(name));+ return next === undefined+ ? textStreamResult("All done.")+ : toolCallStreamResult({ input: "{}", toolCallId: `call-${next}`, toolName: next });+ },+ modelId: "scripted-model",+ provider: "eve-test",+ }),+);++function testUser(principalId: string) {+ return {+ attributes: {},+ authenticator: "test",+ issuer: "test",+ principalId,+ principalType: "user" as const,+ };+}+const ALICE = testUser("alice");+const BOB = testUser("bob");++/** Records `ctx.session.auth.current` for every tool that runs. */+function recordingTool(+ name: string,+ seen: Array<{ tool: string; caller: string | null }>,+ log: string[],+ approval?: Approval,+) {+ return {+ loadNamespace: async () => ({+ default: defineTool({+ approval,+ description: `Run ${name}.`,+ execute: async (_input, ctx) => {+ log.push(`start ${name}`);+ // Yield so calls running in parallel interleave before reading the caller.+ await new Promise((resolve) => setTimeout(resolve, 20));+ seen.push({ tool: name, caller: ctx.session.auth.current?.principalId ?? null });+ log.push(`end ${name}`);+ return { ran: name };+ },+ inputSchema: {},+ }),+ }),+ logicalPath: `tools/${name}.ts`,+ };+}++type User = ReturnType<typeof testUser>;+type Stage = Awaited<ReturnType<ReturnType<typeof captureTurnEvents>["nextTurn"]>>;++interface ChainRun {+ /** Approves the pending request for `toolName`, or the first one. */+ readonly approve: (approver: User | null, toolName?: string) => Promise<Stage>;+ /** Reads the session's next turn segment. */+ readonly next: (label: string) => Promise<Stage>;+ /** Sends `payload` as one delivery on the session's command inbox. */+ readonly deliver: (auth: User, payload: Record<string, unknown>) => Promise<Stage>;+ readonly send: (auth: User, message: string) => Promise<Stage>;+ readonly stages: Stage[];+}++/**+ * Starts a session where Alice asks for deploy_change, read_notes, then+ * publish_change, the first and last gated, and hands `body` the run.+ */+async function withChainRun(+ name: string,+ body: (run: ChainRun) => Promise<void>,+ options: {+ readonly message?: string;+ readonly model?: MockLanguageModelV4;+ readonly modules?: NonNullable<Parameters<typeof createTestRuntime>[0]>["modules"];+ } = {},+) {+ const seen: Array<{ tool: string; caller: string | null }> = [];+ const log: string[] = [];+ const secondRequesters: Array<string | null> = [];+ const secondApproval: Approval = {+ request: always(),+ response: ({ request }) => {+ secondRequesters.push(request.principal?.principalId ?? null);+ return { status: "allowed" };+ },+ };+ const runtime = await createTestRuntime({+ agent: {+ definition: defineAgent({+ model: defineDynamic({+ events: {+ "step.started": () => ({+ model: options.model ?? scriptedModel,+ modelContextWindowTokens: 200_000,+ }),+ },+ }),+ }),+ name,+ },+ modules: [+ recordingTool("deploy_change", seen, log, always()),+ recordingTool("read_notes", seen, log),+ recordingTool("publish_change", seen, log, secondApproval),+ ...(options.modules ?? []),+ ],+ });+ const continuationToken = `http:${name}`;+ const stages: Stage[] = [];++ await runtime.run(async () => {+ const run = await start(workflowEntry, [+ {+ kind: "initial",+ ownerDeploymentId: "dpl_inline",+ input: {+ message: options.message ?? "Use deploy_change, then read_notes, then publish_change.",+ },+ serializedContext: {+ ...buildSerializedContext({ auth: ALICE, channelKind: "http", continuationToken }),+ "eve.capabilities": { requestInput: true },+ },+ },+ ]);+ const commandInbox = sessionInboxHookToken(sessionCommandHookToken(run.runId));+ const stream = captureTurnEvents(run);+ const next = async (label: string) => {+ const stage = await withTimeout(stream.nextTurn(), label);+ stages.push(stage);+ return stage;+ };+ try {+ await next("first approval");+ await body({+ next,+ stages,+ async approve(approver, toolName) {+ const request = stages+ .flatMap((stage) => filterEventsByType(stage, "input.requested"))+ .flatMap((event) => event.data.requests)+ .filter((entry) => toolName === undefined || entry.action.toolName === toolName)+ .at(toolName === undefined ? -1 : 0);+ expect(request?.kind).toBe("tool-approval");+ await resumeHook(commandInbox, {+ auth: approver,+ kind: "send",+ payload: { inputResponses: [{ optionId: "approve", requestId: request!.requestId }] },+ });+ return await next("approved");+ },+ async deliver(auth, payload) {+ await resumeHook(commandInbox, { auth, kind: "send", payload });+ return await next("delivered");+ },+ async send(auth, message) {+ await resumeHook(sessionInboxHookToken(continuationToken), {+ auth,+ kind: "send",+ payload: { message },+ });+ return await next("message");+ },+ });+ } finally {+ stream.dispose();+ await run.cancel().catch(() => {});+ }+ });+ return { log, secondRequesters, seen, stages };+}++function turnBoundaries(stage: Stage) {+ return stage+ .filter((event) => event.type === "turn.started" || event.type === "turn.completed")+ .map((event) => `${event.type} ${(event.data as { turnId: string }).turnId}`);+}++describe("approval caller", () => {+ it("runs only the call another person approves as that person", async () => {+ const { secondRequesters, seen, stages } = await withChainRun(+ "approval-caller",+ async (run) => {+ await run.approve(BOB);+ await run.approve(ALICE);+ },+ );++ // Bob's approval resumes Alice's turn; it does not start his own.+ expect(stages.map(turnBoundaries)).toEqual([+ ["turn.started turn_0"],+ [],+ ["turn.completed turn_0"],+ ]);+ expect(seen).toEqual([+ { tool: "deploy_change", caller: "bob" },+ { tool: "read_notes", caller: "alice" },+ { tool: "publish_change", caller: "alice" },+ ]);+ expect(secondRequesters).toEqual(["alice"]);+ }, 60_000);++ it("lets the requester steer the turn after someone else approves a call", async () => {+ const { seen, stages } = await withChainRun("approval-caller-steer", async (run) => {+ await run.approve(BOB);+ // The turn is still Alice's, so her message steers past publish_change.+ const steered = await run.send(ALICE, "Never mind, skip publishing.");+ expect(filterEventsByType(steered, "input.resolved")[0]?.data.resolutions).toMatchObject([+ { outcome: "ignored" },+ ]);+ });++ expect(stages.map(turnBoundaries)).toEqual([+ ["turn.started turn_0"],+ [],+ ["turn.completed turn_0"],+ ]);+ expect(seen).toEqual([+ { tool: "deploy_change", caller: "bob" },+ { tool: "read_notes", caller: "alice" },+ ]);+ }, 60_000);++ it("starts an approved workflow tool's run as its approver", async () => {+ const { stages } = await withChainRun(+ "approval-caller-workflow",+ async (run) => {+ await run.approve(BOB);+ },+ {+ message: "Use report_caller, then read_notes.",+ modules: [+ {+ loadNamespace: async () => ({+ default: defineWorkflowTool({+ approval: always(),+ description: "Report who runs this.",+ execute: reportCallerWorkflow as WorkflowExecuteToolDefinition["execute"],+ inputSchema: {},+ }),+ }),+ logicalPath: "tools/report_caller.ts",+ },+ ],+ },+ );++ const results = stages+ .flat()+ .flatMap((event) => (event.type === "action.result" ? [event.data.result] : []));+ expect(results.find((result) => result.callId === "call-report_caller")?.output).toEqual({+ caller: "bob",+ });+ }, 60_000);++ it("keeps the rest of another person's delivery out of the turn their answer resumes", async () => {+ const { seen, secondRequesters, stages } = await withChainRun(+ "approval-caller-mixed",+ async (run) => {+ const request = filterEventsByType(run.stages[0]!, "input.requested")[0]!.data.requests[0]!;+ await run.deliver(BOB, {+ inputResponses: [{ optionId: "approve", requestId: request.requestId }],+ message: "Bob here: also delete the staging database.",+ });+ await run.approve(ALICE);+ // Bob's message waited for Alice's turn to end, then started his own.+ await run.next("Bob's turn");+ },+ );++ expect(seen).toEqual([+ { tool: "deploy_change", caller: "bob" },+ { tool: "read_notes", caller: "alice" },+ { tool: "publish_change", caller: "alice" },+ ]);+ expect(secondRequesters).toEqual(["alice"]);+ const received = stages.flatMap((stage) => filterEventsByType(stage, "message.received"));+ expect(received.map((event) => event.data.turnId)).toEqual(["turn_0", "turn_1"]);+ }, 60_000);++ it("never credits an approval sent with null auth to the turn's caller", async () => {+ 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.+ const refused = await run.approve(null, "publish_change");+ expect(filterEventsByType(refused, "input.resolved")).toEqual([]);+ await run.approve(ALICE, "publish_change");+ },+ );++ expect(seen.map((entry) => entry.caller)).toEqual(["alice", "alice", "alice"]);+ expect(secondRequesters).toEqual(["alice"]);+ expect(stages.flatMap((stage) => filterEventsByType(stage, "approval.settled"))).toMatchObject([+ { data: { outcome: "approved", responderPrincipalId: "alice" } },+ ]);+ }, 60_000);++ it("runs approved calls in parallel, each as its own approver", async () => {+ const { log, seen } = await withChainRun(+ "approval-caller-parallel",+ async (run) => {+ await run.approve(BOB, "deploy_change");+ await run.approve(ALICE, "publish_change");+ },+ { message: "Call in parallel: deploy_change, publish_change." },+ );++ // Both calls were running at once.+ 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"],+ ["publish_change", "alice"],+ ]),+ );+ }, 60_000);++ it("does not reuse an earlier approver for a later call with the same 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(+ new MockLanguageModelV4({+ doStream: async ({ prompt }) => {+ const last = prompt.at(-1);+ if (last?.role === "tool") return textStreamResult("Done.");+ const again = JSON.stringify(prompt).includes("Run it again");+ return toolCallStreamResult({+ input: JSON.stringify({ gated: !again }),+ toolCallId: "call-repeated",+ toolName: "report_caller",+ });+ },+ }),+ );+ const { stages } = await withChainRun(+ "approval-caller-repeated-id",+ async (run) => {+ await run.approve(BOB, "report_caller");+ await run.send(ALICE, "Run it again, please.");+ },+ {+ message: "Report who runs report_caller.",+ model,+ modules: [+ {+ loadNamespace: async () => ({+ default: defineWorkflowTool({+ approval: ({ toolInput }) =>+ (toolInput as { gated?: boolean } | undefined)?.gated === true+ ? "user-approval"+ : "not-applicable",+ description: "Report who runs this.",+ execute: reportCallerWorkflow as WorkflowExecuteToolDefinition["execute"],+ inputSchema: {},+ }),+ }),+ logicalPath: "tools/report_caller.ts",+ },+ ],+ },+ );++ const callers = stages+ .flat()+ .flatMap((event) =>+ event.type === "action.result" && event.data.result.callId === "call-repeated"+ ? [(event.data.result.output as { caller: string }).caller]+ : [],+ );+ expect(callers).toEqual(["bob", "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.tsindex 0d1a5bec4..358b84f33 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@@ -125,6 +125,7 @@ function setup(: "https://notes.example.com",instanceKey: variation === "destination" ? `turn-${sequence}` : undefined,description: "Save notes",+ headers: { "X-Caller": (ctx) => ctx.session.auth.current?.principalId ?? "none" },spec: {openapi: "3.0.0",info: { title: "Notes", version: "1.0.0" },@@ -649,6 +650,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");expect(getPendingInputBatches(readDurableSession(resumed.sessionState).state)).toEqual([]);expect(resumed.serializedContext).not.toHaveProperty("eve.pendingConnectionCalls");// The approval held its turn, so approving it resumes the same turn.@@ -738,3 +741,9 @@ describe("turn connection approval restoration", () => {expect(fixture.fetch).toHaveBeenCalledOnce();});});++function callerHeader(call: readonly unknown[] | undefined): string | null {+ const [input, init] = (call ?? []) as [Request | string | URL, RequestInit | undefined];+ const headers = new Headers(input instanceof Request ? input.headers : init?.headers);+ return headers.get("x-caller");+}diff --git a/packages/eve/src/execution/session/turn-step.ts b/packages/eve/src/execution/session/turn-step.tsindex 402bd9b8f..e229512b4 100644--- a/packages/eve/src/execution/session/turn-step.ts+++ b/packages/eve/src/execution/session/turn-step.ts@@ -50,6 +50,7 @@ import {} from "#harness/messages.js";import { consumeDeferredStepInput } from "#harness/pending-input-batches.js";import type { HandleEventFn, HarnessSession, StepInput, StepResult } from "#harness/types.js";+import { attributeAnswers } from "#execution/session/answer-caller.js";import type {DurableStepResult,TurnStepInput,@@ -164,6 +165,7 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>}const previousAuth = ctx.get(AuthKey);+ const hadInitiator = ctx.has(InitiatorAuthKey);// Apply deliver-time auth ferried via `resumeHook` (initial-turn// input has no auth; it was seeded by buildRunContext).@@ -304,6 +306,25 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>}resolved = results.length === 0 ? undefined : results.reduce(coalesceTurnInputs);}+ // A delivery without auth acts as the session's current identity, so+ // only a delivery that names its sender can be answered by someone else.+ const answers =+ delivery?.auth === undefined+ ? undefined+ : attributeAnswers({+ responder: delivery.auth,+ state: durableSession.state,+ stepInput: resolved,+ });+ if (answers !== undefined) {+ // The responder settles the request; the turn keeps its caller and+ // initiator. Adapter state from the answer stays: channels record the+ // responder and their prompt cards there, not the reply destination.+ resolved = answers;+ if (previousAuth === undefined) ctx.delete(AuthKey);+ else ctx.set(AuthKey, previousAuth);+ if (!hadInitiator) ctx.delete(InitiatorAuthKey);+ }const ignoredActiveDelivery =delivery !== undefined && resolved === undefined && !isHarnessBetweenTurns(initialSession);if (ignoredActiveDelivery) {diff --git a/packages/eve/src/harness/approval-candidates.ts b/packages/eve/src/harness/approval-candidates.tsindex e0dcdef8a..00e4a2b6c 100644--- a/packages/eve/src/harness/approval-candidates.ts+++ b/packages/eve/src/harness/approval-candidates.ts@@ -38,6 +38,8 @@ export interface ApprovalResponderIdentity {export interface ApprovalSettlementAuditRecord {readonly actor: ApprovalResponderIdentity;+ /** The approver's full auth, which the approved call runs as. Absent for cancellations. */+ readonly approver?: SessionAuthContext;readonly outcome: "allowed" | "cancelled";readonly requestId: string;readonly settledAt: number;@@ -274,10 +276,10 @@ export function settleAllowedCandidate(input: {throw new Error(`Unknown approval candidate "${input.candidateId}".`);}return settleRequest({- actor: projectResponder(candidate.responder),candidateId: candidate.candidateId,outcome: candidate.decision === "cancel" ? "cancelled" : "allowed",requestId: candidate.requestId,+ responder: candidate.responder,settledAt: input.settledAt,state: expiredState,});@@ -293,9 +295,9 @@ export function settleDirectApprovalResponse(input: {}): ApprovalStateTransition {const state = expireApprovalCandidates({ now: input.settledAt, state: input.state });return settleRequest({- actor: projectResponder(input.actor),outcome: input.outcome,requestId: input.requestId,+ responder: input.actor,settledAt: input.settledAt,state,});@@ -324,10 +326,10 @@ export function getApprovalAuditState(state: SessionStateMap | undefined): {}function settleRequest(input: {- readonly actor: ApprovalResponderIdentity;readonly candidateId?: string;readonly outcome: ApprovalSettlementAuditRecord["outcome"];readonly requestId: string;+ readonly responder: SessionAuthContext;readonly settledAt: number;readonly state: SessionStateMap | undefined;}): ApprovalStateTransition {@@ -338,7 +340,8 @@ function settleRequest(input: {}const settlement: ApprovalSettlementAuditRecord = {- actor: input.actor,+ actor: projectResponder(input.responder),+ ...(input.outcome === "allowed" && { approver: input.responder }),candidateId: input.candidateId,outcome: input.outcome,requestId: input.requestId,@@ -468,3 +471,11 @@ function writeApprovalState(): SessionStateMap {return { ...state, [APPROVAL_STATE_KEY]: approvalState };}++/** 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/approved-call-callers.ts b/packages/eve/src/harness/approved-call-callers.tsnew file mode 100644index 000000000..f78a8ae4f--- /dev/null+++ b/packages/eve/src/harness/approved-call-callers.ts@@ -0,0 +1,62 @@+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 "#harness/approval-candidates.js";+import type { ResolvedInputBatch } from "#harness/input-request-resolution.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",+);++/**+ * Records who approved each call in `resolved`, so each approved call runs as+ * its approver while the rest of the turn keeps the turn's own caller.+ */+export function setApprovedCallCallers(+ resolved: readonly ResolvedInputBatch[] | undefined,+ state: SessionStateMap | undefined,+): void {+ const ctx = contextStorage.getStore();+ if (ctx === undefined) return;+ const callers = new Map<string, SessionAuthContext>();+ for (const batch of resolved ?? []) {+ for (const { outcome, request } of batch.inputs) {+ if (outcome !== "approved" || request.action === undefined) continue;+ const approver = approverOfRequest(state, request.requestId);+ if (approver !== undefined) callers.set(request.action.callId, approver);+ }+ }+ ctx.setVirtualContext(ApprovedCallCallersKey, callers);+}++/** 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/coordination.ts b/packages/eve/src/harness/coordination.tsindex 734f919cf..d731fbd5d 100644--- a/packages/eve/src/harness/coordination.ts+++ b/packages/eve/src/harness/coordination.ts@@ -1,3 +1,4 @@+import type { SessionAuthContext } from "#channel/types.js";import type { ModelMessage } from "ai";import { createActionResultEvent } from "#protocol/message.js";@@ -46,6 +47,8 @@ interface PendingCoordinationEventMetadata {/** Serializable pending coordination batch stored on `session.state`. */export interface PendingCoordinationBatch {+ /** Who approved each call this batch runs for an approval, by call id. */+ readonly approvers?: Readonly<Record<string, SessionAuthContext>>;/** Workflow tool runs pending coordination, including agent tools. */readonly tasks: readonly RuntimeWorkflowTaskRequest[];readonly event: PendingCoordinationEventMetadata;@@ -158,6 +161,7 @@ function approvedSiblingCalls(* Stores one pending coordination batch on the session.*/export function setPendingCoordinationBatch<T extends { readonly state?: SessionStateMap }>(input: {+ readonly approvers?: PendingCoordinationBatch["approvers"];readonly tasks: readonly RuntimeWorkflowTaskRequest[];readonly event: PendingCoordinationEventMetadata;readonly responseMessages: readonly ModelMessage[];@@ -166,6 +170,7 @@ export function setPendingCoordinationBatch<T extends { readonly state?: SessionassertUniqueCoordinationCallIds(input.tasks);const state = { ...input.session.state };state[PENDING_COORDINATION_BATCH_KEY] = {+ ...(input.approvers !== undefined && { approvers: input.approvers }),tasks: [...input.tasks],event: input.event,responseMessages: [...input.responseMessages],diff --git a/packages/eve/src/harness/messages.test.ts b/packages/eve/src/harness/messages.test.tsindex 499e72994..34e26851e 100644--- a/packages/eve/src/harness/messages.test.ts+++ b/packages/eve/src/harness/messages.test.ts@@ -92,6 +92,22 @@ describe("coalesceDeliveries", () => {});describe("coalesceTurnInputs", () => {+ it("keeps answers that carry their responder", () => {+ const bob = {+ attributes: {},+ authenticator: "test",+ principalId: "bob",+ principalType: "user",+ };+ const saved = { inputResponses: [{ optionId: "approve", requestId: "approval-1" }] };+ const answer = { auth: bob, response: { optionId: "cancel", requestId: "approval-2" } };++ expect(coalesceTurnInputs(saved, { attributedInputResponses: [answer] })).toEqual({+ ...saved,+ attributedInputResponses: [answer],+ });+ });+it("joins two messages with a double newline", () => {const result = coalesceTurnInputs({ message: "hello" }, { message: "world" });diff --git a/packages/eve/src/harness/messages.ts b/packages/eve/src/harness/messages.tsindex 3b30ee400..5962cfd02 100644--- a/packages/eve/src/harness/messages.ts+++ b/packages/eve/src/harness/messages.ts@@ -160,7 +160,13 @@ export function coalesceTurnInputs(a: StepInput, b: StepInput): StepInput {});const outputSchema = b.outputSchema ?? a.outputSchema;+ const attributedInputResponses = [+ ...(a.attributedInputResponses ?? []),+ ...(b.attributedInputResponses ?? []),+ ];+const result: {+ attributedInputResponses?: StepInput["attributedInputResponses"];inputResponses?: readonly InputResponse[];message?: string | UserContent;context?: readonly string[];@@ -171,6 +177,10 @@ export function coalesceTurnInputs(a: StepInput, b: StepInput): StepInput {result.inputResponses = inputResponses;}+ if (attributedInputResponses.length > 0) {+ result.attributedInputResponses = attributedInputResponses;+ }+if (message !== undefined) {result.message = message;}diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.tsindex 800a69911..524516627 100644--- a/packages/eve/src/harness/tool-loop.ts+++ b/packages/eve/src/harness/tool-loop.ts@@ -191,6 +191,7 @@ import {workingTaskIds,} from "#execution/tasks/model-step.js";import { renderFinalOutputWhileWorkingError } from "#execution/tasks/render.js";+import { setApprovedCallCallers } from "#harness/approved-call-callers.js";import {classifyModelCallError,ContentFilteredModelResponseError,@@ -1204,6 +1205,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {const replayRequests = (pending.resolvedInputs ?? []).flatMap((batch) =>batch.inputs.filter((input) => input.outcome === "approved"),);+ setApprovedCallCallers(pending.resolvedInputs, session.state);if (replayRequests.length > 0) {const replayTools = buildResponseAuthorizationTools({authoredTools: config.tools,diff --git a/packages/eve/src/harness/tools.ts b/packages/eve/src/harness/tools.tsindex 9d5a01471..b091bd870 100644--- a/packages/eve/src/harness/tools.ts+++ b/packages/eve/src/harness/tools.ts@@ -16,6 +16,7 @@ import { normalizeToolJsonOutput } from "#harness/tool-model-output.js";import { toolCallModelOutput } from "#harness/tool-call-io.js";import type { ToolExecuteOptions } from "#tools/definition.js";import { isAsyncIterable } from "#shared/async-iterable.js";+import { iterateAsApprover, runAsApprover } from "#harness/approved-call-callers.js";type NativeApprovalStatus = Exclude<ApprovalStatus, boolean>;@@ -121,13 +122,17 @@ export function wrapToolExecute(return (input, options) => {let output: unknown;try {- output = execute(input, options);+ output = runAsApprover(options.toolCallId, () => execute(input, options));} catch (error) {return Promise.reject(error);}if (isAsyncIterable(output)) {- return normalizeToolExecuteIterable(output, definition.name, options);+ return normalizeToolExecuteIterable(+ iterateAsApprover(options.toolCallId, output),+ definition.name,+ options,+ );}return Promise.resolve(output).then((value) =>diff --git a/packages/eve/src/harness/workflow-dispatch.ts b/packages/eve/src/harness/workflow-dispatch.tsindex 0ecadf932..9834a0565 100644--- a/packages/eve/src/harness/workflow-dispatch.ts+++ b/packages/eve/src/harness/workflow-dispatch.ts@@ -1,4 +1,6 @@import type { ModelMessage } from "ai";+import type { SessionAuthContext } from "#channel/types.js";+import { approverOfRequest } from "#harness/approval-candidates.js";import { commitCallEntry, isTaskTool } from "#execution/tasks/model-step.js";import {createCoordinationRequestFromToolCall,@@ -43,7 +45,13 @@ export function dispatchApprovedWorkflowCalls(input: {tools: input.tools,turnId: batch.event.turnId,});+ const approvers: Record<string, SessionAuthContext> = {};+ for (const { request } of approved) {+ const approver = approverOfRequest(input.session.state, request.requestId);+ if (approver !== undefined) approvers[request.action.callId] = approver;+ }return setPendingCoordinationBatch({+ approvers,tasks: deferred.workflowRequests,event: batch.event,responseMessages: input.messages.slice(-1),diff --git a/packages/eve/src/internal/testing/app-harness.ts b/packages/eve/src/internal/testing/app-harness.tsindex 32cc60e9c..3cc4910cf 100644--- a/packages/eve/src/internal/testing/app-harness.ts+++ b/packages/eve/src/internal/testing/app-harness.ts@@ -41,6 +41,8 @@ import { mockSandbox, type MockSandbox } from "#internal/testing/mocks/mock-sand*/interface TestAppDescriptor {readonly agent?: {+ /** Full agent definition; overrides `model` and `limits`. */+ readonly definition?: import("#public/definitions/agent.js").AgentDefinition;readonly limits?: {readonly maxInputTokensPerSession?: number | false;readonly maxOutputTokensPerSession?: number | false;@@ -169,6 +171,7 @@ export async function createTestRuntime(descriptor: TestAppDescriptor = {}): Proname: descriptor.agent?.name ?? DEFAULT_AGENT_NAME,model: descriptor.agent?.model ?? TEST_DEFAULT_MODEL_ID,limits: descriptor.agent?.limits,+ agent: descriptor.agent?.definition,modules: [{loadNamespace: async () => {diff --git a/packages/eve/src/internal/testing/workflow-tool-fixtures.ts b/packages/eve/src/internal/testing/workflow-tool-fixtures.tsindex cc1f2834c..ec8784f80 100644--- a/packages/eve/src/internal/testing/workflow-tool-fixtures.ts+++ b/packages/eve/src/internal/testing/workflow-tool-fixtures.ts@@ -258,3 +258,8 @@ export async function receiveDelegatedResultWorkflow(token: string): Promise<unkusing result = createHook<unknown>({ token });return await result;}++export async function reportCallerWorkflow(_input: unknown, ctx: WorkflowToolContext) {+ "use workflow";+ return { caller: ctx.session.auth.current?.principalId ?? null };+}