The Open Framework for Building Agents
[1/3] feat(eve): pass the requester to approval response policies (#3928)
Ben Pankow5181b14f055d
diff --git a/.changeset/hitl-requester-responses.md b/.changeset/hitl-requester-responses.mdnew file mode 100644index 000000000..77248c174--- /dev/null+++ b/.changeset/hitl-requester-responses.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Approval response policies now receive `request.principal`, the person whose turn requested the call, so a policy can let only that person approve it in a shared conversation. It is `null` when the caller was unauthenticated or anonymous.diff --git a/docs/tools/human-in-the-loop.md b/docs/tools/human-in-the-loop.mdindex 916c65b91..97058ea6a 100644--- a/docs/tools/human-in-the-loop.md+++ b/docs/tools/human-in-the-loop.md@@ -114,13 +114,50 @@ export default defineTool({The `response` policy receives:- `responder`: the authenticated principal that submitted the response, including its `principalId`, `principalType`, `authenticator`, and `attributes`. Your route or channel supplies this identity.-- `request`: the stable `requestId`, `callId`, `toolName`, and typed `toolInput` for the call being approved.+- `request`: the stable `requestId`, `callId`, `toolName`, and typed `toolInput` for the call being approved, plus `principal`: the authenticated principal whose turn requested the call, or `null` when that caller was unauthenticated or anonymous. eve captures `request.principal` when the approval is requested, so it stays the same while other people continue the session.- `response`: the submitted decision. Response policies run for approval, so its current value is `{ decision: "approve" }`.- `session`: read-only session identity and lineage: `id`, `initiator`, `parent`, and `turn`.- `auth`: narrow `getToken(provider, options?)` and `requireAuth(provider, options?)` capabilities bound to the responder. Use these when authorization depends on a provider identity or permission; an interactive provider flow parks durably and then retries the policy.Return `{ status: "allowed" }` to accept the approval. Return `{ status: "rejected", reason }` to leave the shared request pending so another eligible responder can approve it.+`session.initiator` is the person who started the session, and `request.principal` is the person who asked for this call. In a shared thread they can differ. Compare the full identity of `responder` with `request.principal` to let only the requester approve the call:++```ts title="agent/tools/publish_release.ts"+import { defineTool } from "eve/tools";+import type { SessionAuthContext } from "eve/context";+import { always } from "eve/tools/approval";+import { z } from "zod";++function samePrincipal(a: SessionAuthContext, b: SessionAuthContext): boolean {+ return (+ a.authenticator === b.authenticator &&+ a.issuer === b.issuer &&+ a.principalType === b.principalType &&+ a.principalId === b.principalId+ );+}++export default defineTool({+ description: "Publish a release.",+ inputSchema: z.object({ version: z.string() }),+ approval: {+ request: always(),+ // `request.principal` is null for an unauthenticated or anonymous caller, so no one matches it.+ response: ({ request, responder }) =>+ request.principal !== null && samePrincipal(responder, request.principal)+ ? { status: "allowed" }+ : {+ status: "rejected",+ reason: "Only the person who asked for this release can approve it.",+ },+ },+ async execute(input) {+ return publish(input);+ },+});+```+When a response is refused without starting a turn, the session returns to `session.waiting`. The client finishes the submission and keeps the approval prompt answerable. Submitting an answer does not confirm approval: `approval.settled` or `input.resolved` records the server's decision. You can inspect `approval.candidate` events for the response policy's refusal reason.### Skipping approval for schedule-dispatched turnsdiff --git a/packages/eve/extension-contracts/compatibility/connection/v30.ts b/packages/eve/extension-contracts/compatibility/connection/v30.tsnew file mode 100644index 000000000..b0e8aca27--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/connection/v30.ts@@ -0,0 +1,15 @@+import { defineMcpClientConnection } from "#public/connections/index.js";+import { always } from "#public/tools/approval/index.js";++// Epoch 30 approval requests had no `requester`; it is additive.+export default defineMcpClientConnection({+ description: "Search the support knowledge base.",+ url: "https://support.example.com/mcp",+ approval: {+ request: always(),+ response: ({ request, responder }) =>+ request.toolName.startsWith("search") || responder.principalId === "approver"+ ? { status: "allowed" }+ : { status: "rejected", reason: "Only the approver can run this tool." },+ },+});diff --git a/packages/eve/extension-contracts/compatibility/dynamicTool/v58.ts b/packages/eve/extension-contracts/compatibility/dynamicTool/v58.tsnew file mode 100644index 000000000..611cca7f9--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/dynamicTool/v58.ts@@ -0,0 +1,22 @@+import { defineDynamic, defineTool } from "#public/tools/index.js";+import { always } from "#public/tools/approval/index.js";++// Epoch 58 approval requests had no `requester`; it is additive.+export default defineDynamic({+ events: {+ "turn.started": () => ({+ refund: defineTool({+ description: "Refund a charge after an approver allows it.",+ inputSchema: { type: "object", properties: {} },+ approval: {+ request: always(),+ response: ({ responder }) =>+ responder.principalId === "approver"+ ? { status: "allowed" }+ : { status: "rejected", reason: "Only the approver can refund charges." },+ },+ execute: () => ({ refunded: true }),+ }),+ }),+ },+});diff --git a/packages/eve/extension-contracts/compatibility/tool/v61.ts b/packages/eve/extension-contracts/compatibility/tool/v61.tsnew file mode 100644index 000000000..6d4c747ef--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/tool/v61.ts@@ -0,0 +1,18 @@+import { z } from "zod";+import { defineTool } from "#public/tools/index.js";+import { always } from "#public/tools/approval/index.js";++// Epoch 61 approval requests had no `requester`. Compiled epoch 61 response+// policies still read `responder` and `request`; `requester` is additive.+export default defineTool({+ description: "Refund a charge after an approver allows it.",+ inputSchema: z.object({ chargeId: z.string() }),+ approval: {+ request: always(),+ response: ({ request, responder }) =>+ request.toolName === "refund" && responder.principalId === "approver"+ ? { status: "allowed" }+ : { status: "rejected", reason: "Only the approver can refund charges." },+ },+ execute: ({ chargeId }) => ({ chargeId, refunded: true }),+});diff --git a/packages/eve/extension-contracts/reports/connection/v31.json b/packages/eve/extension-contracts/reports/connection/v31.jsonnew file mode 100644index 000000000..04d9da20e--- /dev/null+++ b/packages/eve/extension-contracts/reports/connection/v31.json@@ -0,0 +1,16 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "connection",+ "epoch": 31,+ "sha256": "ff2c37de7bd134d562b0d14b9d06566edc845b9d25b19fbb037489d151951174",+ "exports": [+ "ConnectionAuthorizationFailedError",+ "ConnectionAuthorizationRequiredError",+ "defineDynamic",+ "defineInteractiveAuthorization",+ "defineMcpClientConnection",+ "defineOpenAPIConnection",+ "isConnectionAuthorizationFailedError",+ "isConnectionAuthorizationRequiredError"+ ]+}diff --git a/packages/eve/extension-contracts/reports/dynamicTool/v59.json b/packages/eve/extension-contracts/reports/dynamicTool/v59.jsonnew file mode 100644index 000000000..80ce488cf--- /dev/null+++ b/packages/eve/extension-contracts/reports/dynamicTool/v59.json@@ -0,0 +1,16 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "dynamicTool",+ "epoch": 59,+ "sha256": "d34b677fc9153dc1e56128828c2d3b63be42f117e8216b36d5a76297f1a1eecd",+ "exports": [+ "DynamicToolEntry",+ "DynamicToolEvents",+ "DynamicToolResult",+ "DynamicToolSet",+ "auto",+ "defineDurableCallback",+ "defineDurableSchema",+ "defineDynamic"+ ]+}diff --git a/packages/eve/extension-contracts/reports/tool/v62.json b/packages/eve/extension-contracts/reports/tool/v62.jsonnew file mode 100644index 000000000..88b17cb7c--- /dev/null+++ b/packages/eve/extension-contracts/reports/tool/v62.json@@ -0,0 +1,28 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "tool",+ "epoch": 62,+ "sha256": "246c006769eb760fff7bdad4fc621a1b12d182492fde22f2c65a42618d8e6450",+ "exports": [+ "AgentRouterInput",+ "AgentRouterTool",+ "WorkflowStepToolContext",+ "WorkflowTool",+ "WorkflowToolDefinition",+ "WorkflowToolInput",+ "WorkflowToolOptions",+ "agentRouter",+ "defaultWebSearch",+ "defineTool",+ "defineWorkflowTool",+ "disableTool",+ "evaluate",+ "isDisabledToolSentinel",+ "isWebSearchToolDefinition",+ "toolOutput",+ "toolOutputPart",+ "toolResultFrom",+ "webSearch",+ "workflow"+ ]+}diff --git a/packages/eve/src/approval/definition.test.ts b/packages/eve/src/approval/definition.test.tsindex 1247f8118..a10cd47c7 100644--- a/packages/eve/src/approval/definition.test.ts+++ b/packages/eve/src/approval/definition.test.ts@@ -30,7 +30,7 @@ describe("approval definitions", () => {getToken: (...args: any[]) => Promise<unknown>;requireAuth: (...args: any[]) => never;};- request: { callId: string; requestId: string; toolName: string };+ request: { callId: string; principal: unknown; requestId: string; toolName: string };response: { decision: "approve" };responder: { principalId: string };session: { id: string; initiator: unknown; turn: unknown };diff --git a/packages/eve/src/approval/definition.ts b/packages/eve/src/approval/definition.tsindex 8357ac079..7bf02cef0 100644--- a/packages/eve/src/approval/definition.ts+++ b/packages/eve/src/approval/definition.ts@@ -43,6 +43,13 @@ export type ApprovalPolicy<TInput = Record<string, unknown>> = (export interface ApprovalRequest<TInput = Record<string, unknown>> {readonly callId: string;readonly requestId: string;+ /**+ * Who requested the tool call: the auth of the caller whose turn made it,+ * captured when the approval was requested. It stays the same while the+ * request is pending, however many people continue the session, and is+ * `null` when that caller was unauthenticated or anonymous.+ */+ readonly principal: SessionAuthContext | null;readonly toolInput?: ApprovalToolInput<TInput>;readonly toolName: string;}diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.tsindex 31506a9cc..c54f93e22 100644--- a/packages/eve/src/compiler/extension-compatibility.ts+++ b/packages/eve/src/compiler/extension-compatibility.ts@@ -22,8 +22,8 @@ interface ExtensionCapabilityContract {const EXTENSION_CAPABILITY_CONTRACTS = {extension: { current: 1, supported: [1], dropped: {} },tool: {- current: 61,- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 29, 30, 31, 32, 34, 35, 54, 55, 61],+ current: 62,+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 29, 30, 31, 32, 34, 35, 54, 55, 61, 62],dropped: {14: "TaskExec.delegated was removed; migrate to workflow-backed background tools",15: "TaskExec replaces stageEffect with send",@@ -67,10 +67,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {},},dynamicTool: {- current: 58,+ current: 59,supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 31, 32, 33, 52, 54,- 58,+ 58, 59,],dropped: {21: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",@@ -152,8 +152,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {},},connection: {- current: 30,- supported: [1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 26, 30],+ current: 31,+ supported: [+ 1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 26, 30, 31,+ ],dropped: {9: "Dynamic connection resolvers no longer receive conversation or channel continuation data",10: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",diff --git a/packages/eve/src/harness/approval-delivery-coordinator.test.ts b/packages/eve/src/harness/approval-delivery-coordinator.test.tsindex 76cabd570..6d238c7dd 100644--- a/packages/eve/src/harness/approval-delivery-coordinator.test.ts+++ b/packages/eve/src/harness/approval-delivery-coordinator.test.ts@@ -2,7 +2,7 @@ import { describe, expect, it, vi } from "vitest";import { jsonSchema } from "ai";import type { ApprovalResponsePolicy } from "#approval/definition.js";import { ContextContainer, contextStorage } from "#context/container.js";-import { SessionKey } from "#context/keys.js";+import { AuthKey, SessionKey } from "#context/keys.js";import {getApprovalAuditState,markApprovalCandidateAuthorizationRequired,@@ -89,6 +89,40 @@ describe("coordinateApprovalDelivery", () => {});}+ function parkedBy(auth: SessionAuthContext): HarnessSession {+ const ctx = new ContextContainer();+ ctx.set(AuthKey, auth);+ return contextStorage.run(ctx, parkedSession);+ }++ it("passes the requester the batch parked with to the response policy", async () => {+ const requester: SessionAuthContext = { ...responder, principalId: "bob" };+ const ingested = await ingest(parkedBy(requester));+ const response = vi.fn<ApprovalResponsePolicy>(() => ({ status: "allowed" }));+ await authorize(ingested.session, response);+ expect(response).toHaveBeenCalledWith(+ expect.objectContaining({+ request: expect.objectContaining({ principal: requester }),+ responder,+ }),+ );+ });++ it("records no requester for an anonymous caller", async () => {+ const anonymous: SessionAuthContext = {+ attributes: {},+ authenticator: "none",+ principalId: "anonymous",+ principalType: "anonymous",+ };+ const ingested = await ingest(parkedBy(anonymous));+ const response = vi.fn<ApprovalResponsePolicy>(() => ({ status: "allowed" }));+ await authorize(ingested.session, response);+ expect(response).toHaveBeenCalledWith(+ expect.objectContaining({ request: expect.objectContaining({ principal: null }) }),+ );+ });+it.each(["rejected", "failed", "allowed"] as const)("explicitly completes %s candidates only after ingestion",async (status) => {diff --git a/packages/eve/src/harness/approval-delivery-coordinator.ts b/packages/eve/src/harness/approval-delivery-coordinator.tsindex 33d56b839..2f3d42768 100644--- a/packages/eve/src/harness/approval-delivery-coordinator.ts+++ b/packages/eve/src/harness/approval-delivery-coordinator.ts@@ -26,7 +26,7 @@ import {type AuthorizationChallenge,} from "#harness/authorization.js";import { isApprovalRequest } from "#harness/input-request-class.js";-import { getPendingInputBatches } from "#harness/pending-input-batches.js";+import { getPendingInputBatches, pendingInputRequester } from "#harness/pending-input-batches.js";import type { HarnessSession, HarnessToolMap, StepInput } from "#harness/types.js";import type { InputRequest } from "#shared/input.js";@@ -326,6 +326,7 @@ async function authorizeCandidate(input: {request: {callId: input.request.action.callId,requestId: input.request.requestId,+ principal: pendingInputRequester(session.state, input.request.requestId),toolInput: input.request.action.input,toolName: input.request.action.toolName,},diff --git a/packages/eve/src/harness/pending-input-batches.ts b/packages/eve/src/harness/pending-input-batches.tsindex 1bbdb122b..1c13d874a 100644--- a/packages/eve/src/harness/pending-input-batches.ts+++ b/packages/eve/src/harness/pending-input-batches.ts@@ -1,7 +1,8 @@import type { ModelMessage } from "ai";import { contextStorage } from "#context/container.js";-import { ActivityRootTurnIdKey } from "#context/keys.js";+import type { SessionAuthContext } from "#channel/types.js";+import { ActivityRootTurnIdKey, AuthKey, SessionKey } from "#context/keys.js";import type { InputRequest } from "#shared/input.js";import type { HarnessSession, SessionStateMap, StepInput } from "#harness/types.js";import { coalesceTurnInputs } from "#harness/messages.js";@@ -32,6 +33,11 @@ export interface PendingInputBatch {readonly event?: PendingInputBatchEvent;readonly activityRootTurnId?: string;readonly requests: readonly InputRequest[];+ /**+ * Auth of the caller whose turn parked the batch, captured when it parked;+ * `null` when that caller was unauthenticated.+ */+ readonly requester?: SessionAuthContext | null;readonly responseAuthRequiredRequestIds?: readonly string[];readonly responseMessages: readonly ModelMessage[];}@@ -138,6 +144,7 @@ function setPendingInputBatches(state[PENDING_INPUT_BATCHES_KEY] = batches.map((batch) => ({event: batch.event,activityRootTurnId: batch.activityRootTurnId,+ requester: batch.requester,responseAuthRequiredRequestIds: batch.responseAuthRequiredRequestIds,toolReplayIdentities: batch.toolReplayIdentities,requests: [...batch.requests],@@ -167,6 +174,7 @@ export function appendPendingInputBatch(input: {event: input.event,activityRootTurnId:input.activityRootTurnId ?? contextStorage.getStore()?.get(ActivityRootTurnIdKey),+ requester: currentRequester(),responseAuthRequiredRequestIds: input.responseAuthRequiredRequestIds,toolReplayIdentities: input.toolReplayIdentities,requests: input.requests,@@ -175,6 +183,27 @@ export function appendPendingInputBatch(input: {]);}+/**+ * Every anonymous caller shares one synthetic identity, so an anonymous+ * requester can't be told apart from another anonymous responder: record none.+ */+function currentRequester(): SessionAuthContext | null {+ const context = contextStorage.getStore();+ const auth = context?.get(AuthKey) ?? context?.get(SessionKey)?.auth.current ?? null;+ return auth?.principalType === "anonymous" ? null : auth;+}++/** The requester recorded on the pending batch that holds `requestId`. */+export function pendingInputRequester(+ state: SessionStateMap | undefined,+ requestId: string,+): SessionAuthContext | null {+ const batch = getPendingInputBatches(state).find((candidate) =>+ candidate.requests.some((request) => request.requestId === requestId),+ );+ return batch?.requester ?? null;+}+export function activityRootTurnIdForInputResponses(state: SessionStateMap | undefined,requestIds: ReadonlySet<string>,