Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): let approved calls read who approved them (#4604)

Rui68b9d58ae646
diff --git a/.changeset/approval-responder-context.md b/.changeset/approval-responder-context.md
new file mode 100644
index 000000000..5f38fe626
--- /dev/null
+++ b/.changeset/approval-responder-context.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Approved `defineTool` calls can read who approved them: `ctx.approval.responder` is the approver and `ctx.approval.responder.getToken(provider)` resolves their token, while the call still runs as the requester.
diff --git a/docs/reference/typescript-api.md b/docs/reference/typescript-api.md
index 399234697..3b791e8de 100644
--- a/docs/reference/typescript-api.md
+++ b/docs/reference/typescript-api.md
@@ -103,12 +103,13 @@ import template from "../../prompts/template.txt?raw";
`ctx` is passed to your tool `execute`, hook handlers, channel event handlers, and connection auth/header resolvers. It is live only while authored code is running, so reaching for it at module top level throws. See [Session context](../guides/session-context) for the full model.
-| Member | Use |
-| --------------------------- | ---------------------------------------------------------------------------- |
-| `ctx.session` | Current session, turn, auth, and optional parent lineage (read-only) |
-| `ctx.getSandbox()` | Live sandbox handle; `stop()` releases compute but preserves durable state |
-| `ctx.getToken(provider)` | Resolve a bearer token for an inline auth provider such as `connect("...")` |
-| `ctx.requireAuth(provider)` | Evict and re-authorize an inline provider, commonly after a downstream `401` |
+| Member | Use |
+| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `ctx.session` | Current session, turn, auth, and optional parent lineage (read-only) |
+| `ctx.getSandbox()` | Live sandbox handle; `stop()` releases compute but preserves durable state |
+| `ctx.getToken(provider)` | Resolve a bearer token for an inline auth provider such as `connect("...")` |
+| `ctx.requireAuth(provider)` | Evict and re-authorize an inline provider, commonly after a downstream `401` |
+| `ctx.approval` | Present only while a call runs after a person approved it: `responder` is who approved it and `responder.getToken(provider)` resolves their token. The call still runs as `ctx.session.auth.current`; see [Human-in-the-loop](/docs/human-in-the-loop) |
Tool definitions accept `availableInSubagents: false` to restrict the tool to top-level root sessions, and `deferred: true` to keep the tool out of the model's tool list so the model finds it with `eve__search` and calls it with `eve__tool`; see [Tools](../tools#keep-a-tool-out-of-the-tool-list). `defineTool` definitions accept `endsTurn: true`, or a function that receives the `execute` output, to end the turn without a reply after a successful call; see [Tools](../tools#end-the-turn-after-a-tool-call). Authored workflow bodies also receive `ctx.agents`, a replay-stable map of callable-agent metadata, and `ctx.agent(name)`, which returns an `AgentSession` whose `send(message, options?)` resolves to a response with `result()`. A `"use step"` helper that receives the context directly should type it as `WorkflowStepToolContext`, which excludes `agents`, `agent`, and `ask`. The root-copy `agent` entry has an empty description when the root omits `description`. See [Workflows as tools](../tools/workflows#delegate-work-ctxagent) for the workflow-only context.
diff --git a/docs/tools/human-in-the-loop.md b/docs/tools/human-in-the-loop.md
index c099d79f0..98322c7a7 100644
--- a/docs/tools/human-in-the-loop.md
+++ b/docs/tools/human-in-the-loop.md
@@ -256,6 +256,27 @@ When a subagent requests input, eve emits the same `input.requested` event on it
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.
+A `defineTool` tool can still act on the approver's behalf when it chooses to. While an approved `defineTool` call runs, `ctx.approval.responder` is the principal who approved it, and `ctx.approval.responder.getToken(provider)` resolves that person's token for an inline provider, as `ctx.getToken(provider)` does for the requester. `ctx.session.auth.current` stays the requester. `ctx.approval` is absent for calls that needed no approval, and workflow tools don't receive it. `ctx.approval.responder.getToken(provider)` never starts a sign-in: when the approver has no token, it throws a `ConnectionAuthorizationFailedError` with `reason: "approver_authorization_required"`.
+
+```ts
+export default defineTool({
+ description: "Grant the requester access to a repository.",
+ inputSchema: z.object({ repo: z.string() }),
+ approval: {
+ request: always(),
+ response: ({ response }) =>
+ itAdmins.includes(response.principal.principalId)
+ ? { status: "allowed" }
+ : { status: "rejected" },
+ },
+ async execute({ repo }, ctx) {
+ const admin = await ctx.approval?.responder.getToken(github);
+ if (admin === undefined) throw new Error("An IT admin must approve this grant.");
+ return await grantAccess(repo, ctx.session.auth.current, admin.token);
+ },
+});
+```
+
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.
### Several requests at once
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 cea5c749d..b08f90465 100644
--- a/e2e/fixtures/agent-tools-hitl/agent/lib/hitl/respond.ts
+++ b/e2e/fixtures/agent-tools-hitl/agent/lib/hitl/respond.ts
@@ -10,6 +10,7 @@ export const SAY = {
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.",
+ releaseGrant: "Alice asks Bob to grant her 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.",
@@ -94,6 +95,11 @@ export function respond(request: MockModelRequest): MockModelResponse {
[call("caller-access", "caller-access")],
() => `Release access: ${outcome("caller-access")}.`,
),
+ [SAY.releaseGrant]: () =>
+ run(
+ [call("release-grant", "release-grant")],
+ () => `Release grant: ${outcome("release-grant")}.`,
+ ),
[SAY.frozen]: () =>
run([call("frozen", "frozen-change")], () => `Frozen change: ${outcome("frozen")}.`),
[SAY.retiring]: () =>
diff --git a/e2e/fixtures/agent-tools-hitl/agent/tools/release-grant.ts b/e2e/fixtures/agent-tools-hitl/agent/tools/release-grant.ts
new file mode 100644
index 000000000..b5d6e9ca9
--- /dev/null
+++ b/e2e/fixtures/agent-tools-hitl/agent/tools/release-grant.ts
@@ -0,0 +1,33 @@
+import { defineTool, type ToolAuthProvider } from "eve/tools";
+import { always } from "eve/tools/approval";
+import { z } from "zod";
+
+/** A per-user credential: each person's token names them, so the result shows whose was used. */
+const releaseAuth: ToolAuthProvider = {
+ credentialOwner: "user",
+ async getToken({ principal }) {
+ return { token: `release-token:${principal.type === "user" ? principal.id : "app"}` };
+ },
+};
+
+export default defineTool({
+ description: "Grant release access with the approver's credentials, on the requester's behalf.",
+ inputSchema: z.object({}),
+ approval: {
+ request: always(),
+ response: ({ response }) =>
+ response.principal.principalId === "bob"
+ ? { status: "allowed" }
+ : { status: "rejected", reason: "Only bob can approve this fixture." },
+ },
+ async execute(_input, ctx) {
+ const requesterToken = await ctx.getToken(releaseAuth);
+ const responderToken = await ctx.approval?.responder.getToken(releaseAuth);
+ return {
+ requester: ctx.session.auth.current?.principalId ?? "none",
+ requesterToken: requesterToken.token,
+ responder: ctx.approval?.responder.principalId ?? "none",
+ responderToken: responderToken?.token ?? "none",
+ };
+ },
+});
diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/README.md b/e2e/fixtures/agent-tools-hitl/evals/hitl/README.md
index c81e56579..59c363b1a 100644
--- a/e2e/fixtures/agent-tools-hitl/evals/hitl/README.md
+++ b/e2e/fixtures/agent-tools-hitl/evals/hitl/README.md
@@ -38,6 +38,7 @@ and [`agent-workflow-tools/evals/hitl`](../../../agent-workflow-tools/evals/hitl
| 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) |
+| An approved call reads who approved it and their credentials | [approved-call-reads-responder](./approvals/approved-call-reads-responder.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) |
diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/approvals/approved-call-reads-responder.eval.ts b/e2e/fixtures/agent-tools-hitl/evals/hitl/approvals/approved-call-reads-responder.eval.ts
new file mode 100644
index 000000000..9b3680f98
--- /dev/null
+++ b/e2e/fixtures/agent-tools-hitl/evals/hitl/approvals/approved-call-reads-responder.eval.ts
@@ -0,0 +1,37 @@
+import { defineEval } from "eve/evals";
+import {
+ SAY,
+ aliceSession,
+ answers,
+ approvalFor,
+ asAlice,
+ asBob,
+ expectResolved,
+} from "../helpers.ts";
+
+export default defineEval({
+ description:
+ "An approved call runs as the requester and also reads the responder and their credentials.",
+ tags: ["hitl", "approval"],
+ timeoutMs: 60_000,
+ async test(t) {
+ const session = await aliceSession(t);
+ const request = approvalFor(await session.send(SAY.releaseGrant, asAlice), "release-grant");
+ const approved = (await session.respond(answers("approve", request), asBob)).expectOk();
+ expectResolved(approved, request, "approved");
+ approved.event("action.result", {
+ count: 1,
+ data: {
+ result: {
+ toolName: "release-grant",
+ output: {
+ requester: "alice",
+ requesterToken: "release-token:alice",
+ responder: "bob",
+ responderToken: "release-token:bob",
+ },
+ },
+ },
+ });
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/dynamicTool/v83.ts b/packages/eve/extension-contracts/compatibility/dynamicTool/v83.ts
new file mode 100644
index 000000000..e4ac75f88
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/dynamicTool/v83.ts
@@ -0,0 +1,19 @@
+import { defineDynamic, defineTool } from "#public/tools/index.js";
+
+// Epoch 83 tool contexts had no `approval`; epoch 84 adds it as optional.
+// Dynamic tools that read the session auth keep observing the requester.
+export default defineDynamic({
+ events: {
+ "turn.started": (_event, ctx) => ({
+ requester: defineTool({
+ deferred: true,
+ description: "Return the active session's requester.",
+ inputSchema: { type: "object", properties: {} },
+ execute: (_input, toolContext) => ({
+ sessionId: ctx.session.id,
+ requester: toolContext.session.auth.current?.principalId ?? null,
+ }),
+ }),
+ }),
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/tool/v89.ts b/packages/eve/extension-contracts/compatibility/tool/v89.ts
new file mode 100644
index 000000000..8a6dfb4f5
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/tool/v89.ts
@@ -0,0 +1,16 @@
+import { z } from "zod";
+import { defineTool } from "#public/tools/index.js";
+import { always } from "#public/tools/approval/index.js";
+
+// Epoch 89 tool contexts had no `approval`; epoch 90 adds it as optional, set
+// only when a call runs after a person approved it. Approved tools that read
+// only `ctx.session.auth` keep running as the requester.
+export default defineTool({
+ description: "Report who requested the release check.",
+ inputSchema: z.object({ release: z.string() }),
+ approval: always(),
+ execute: ({ release }, ctx) => ({
+ release,
+ requester: ctx.session.auth.current?.principalId ?? null,
+ }),
+});
diff --git a/packages/eve/extension-contracts/reports/dynamicTool/v84.json b/packages/eve/extension-contracts/reports/dynamicTool/v84.json
new file mode 100644
index 000000000..bc8494e7b
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicTool/v84.json
@@ -0,0 +1,16 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicTool",
+ "epoch": 84,
+ "sha256": "c62c09c374646c48011c9ed1c3dd45775bf0e72bd77e28f95b7fa53cbd474798",
+ "exports": [
+ "DynamicToolEntry",
+ "DynamicToolEvents",
+ "DynamicToolResult",
+ "DynamicToolSet",
+ "auto",
+ "defineDurableCallback",
+ "defineDurableSchema",
+ "defineDynamic"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/tool/v90.json b/packages/eve/extension-contracts/reports/tool/v90.json
new file mode 100644
index 000000000..d7e640dd2
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/tool/v90.json
@@ -0,0 +1,29 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "tool",
+ "epoch": 90,
+ "sha256": "63716d1ea5206bfac99dfeb9c11f42e8fd63e2a024195a36f187de364140ce13",
+ "exports": [
+ "AgentRouterInput",
+ "AgentRouterTool",
+ "WorkflowStepToolContext",
+ "WorkflowTool",
+ "WorkflowToolDefinition",
+ "WorkflowToolInput",
+ "WorkflowToolOptions",
+ "agentRouter",
+ "decide",
+ "defaultWebSearch",
+ "defineTool",
+ "defineWorkflowTool",
+ "disableTool",
+ "isDisabledToolSentinel",
+ "isWebSearchToolDefinition",
+ "serializeModelInputSchema",
+ "toolOutput",
+ "toolOutputPart",
+ "toolResultFrom",
+ "webSearch",
+ "workflow"
+ ]
+}
diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.ts
index 3f070527e..0fdcf25ea 100644
--- a/packages/eve/src/compiler/extension-compatibility.ts
+++ b/packages/eve/src/compiler/extension-compatibility.ts
@@ -22,10 +22,10 @@ interface ExtensionCapabilityContract {
const EXTENSION_CAPABILITY_CONTRACTS = {
extension: { current: 1, supported: [1], dropped: {} },
tool: {
- current: 89,
+ current: 90,
supported: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 29, 30, 31, 32, 34, 35, 76, 77, 78, 80, 81, 82, 84,
- 85, 86, 87, 88, 89,
+ 85, 86, 87, 88, 89, 90,
],
dropped: {
14: "TaskExec.delegated was removed; migrate to workflow-backed background tools",
@@ -89,10 +89,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
dynamicTool: {
- current: 83,
+ current: 84,
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,
- 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 72, 73, 75, 76, 77, 78, 79, 80, 81, 82, 83,
+ 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 72, 73, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84,
],
dropped: {
21: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
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 91311085e..6a33413ae 100644
--- a/packages/eve/src/execution/session/approval-caller.integration.test.ts
+++ b/packages/eve/src/execution/session/approval-caller.integration.test.ts
@@ -79,12 +79,16 @@ const BOB = testUser("bob");
// need Bob to approve Alice's calls.
const anyoneResponds: ApprovalResponsePolicy = () => ({ status: "allowed" });
-/** Records `ctx.session.auth.current` for every tool that runs. */
+/**
+ * Records `ctx.session.auth.current` for every tool that runs, and in `approvedBy` who
+ * approved each call that ran after an approval.
+ */
function recordingTool(
name: string,
seen: Array<{ tool: string; caller: string | null }>,
log: string[],
approval?: Approval,
+ approvedBy?: Array<{ tool: string; responder: string }>,
) {
return {
loadNamespace: async () => ({
@@ -96,6 +100,9 @@ function recordingTool(
// 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 });
+ if (ctx.approval !== undefined) {
+ approvedBy?.push({ tool: name, responder: ctx.approval.responder.principalId });
+ }
log.push(`end ${name}`);
return { ran: name };
},
@@ -136,6 +143,7 @@ async function withChainRun(
} = {},
) {
const seen: Array<{ tool: string; caller: string | null }> = [];
+ const approvedBy: Array<{ tool: string; responder: string }> = [];
const log: string[] = [];
const secondRequesters: Array<string | null> = [];
const secondApproval: Approval = {
@@ -165,9 +173,10 @@ async function withChainRun(
seen,
log,
options.firstApproval ?? { request: always(), response: anyoneResponds },
+ approvedBy,
),
- recordingTool("read_notes", seen, log),
- recordingTool("publish_change", seen, log, secondApproval),
+ recordingTool("read_notes", seen, log, undefined, approvedBy),
+ recordingTool("publish_change", seen, log, secondApproval, approvedBy),
...(options.modules ?? []),
],
});
@@ -235,7 +244,7 @@ async function withChainRun(
await run.cancel().catch(() => {});
}
});
- return { log, secondRequesters, seen, stages };
+ return { approvedBy, log, secondRequesters, seen, stages };
}
function turnBoundaries(stage: Stage) {
@@ -248,7 +257,7 @@ describe("approval caller", () => {
it.each([false, true])(
"runs a call another person approves as its requester (unmatched stub: %s)",
async (withStub) => {
- const { secondRequesters, seen, stages } = await withChainRun(
+ const { approvedBy, secondRequesters, seen, stages } = await withChainRun(
`approval-caller-${withStub}`,
async (run) => {
await run.approve(BOB);
@@ -280,6 +289,11 @@ describe("approval caller", () => {
{ tool: "publish_change", caller: "alice" },
]);
expect(secondRequesters).toEqual(["alice"]);
+ // Each approved call reads who approved it; the call that needed no approval reads nobody.
+ expect(approvedBy).toEqual([
+ { tool: "deploy_change", responder: "bob" },
+ { tool: "publish_change", responder: "alice" },
+ ]);
},
60_000,
);
diff --git a/packages/eve/src/execution/tool-auth.integration.test.ts b/packages/eve/src/execution/tool-auth.integration.test.ts
index ec537e1e8..94acea9ba 100644
--- a/packages/eve/src/execution/tool-auth.integration.test.ts
+++ b/packages/eve/src/execution/tool-auth.integration.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import {
buildApprovalResponseAuth,
+ createToolExecuteWithAuth,
handleApprovalResponsePolicyError,
} from "#execution/tool-auth.js";
import { evictScopedToken, resolveScopedToken } from "#runtime/connections/scoped-authorization.js";
@@ -909,4 +910,182 @@ describe("tool-hosted authorization", () => {
}),
).rejects.toThrow("auth required");
});
+
+ it.each([
+ ["the requester approves their own call", "user-1", 1, "token:user-1"],
+ ["someone else approves the call", "user-2", 2, "token:user-2"],
+ ] as const)(
+ "shares an explicit auth key between requester and approver lookups when %s",
+ async (_case, approverId, fetches, approverToken) => {
+ const fetched: string[] = [];
+ const provider: AuthorizationDefinition = {
+ principalType: "user",
+ async getToken({ principal }) {
+ const id = principal.type === "user" ? principal.id : "app";
+ fetched.push(id);
+ return { token: `token:${id}` };
+ },
+ };
+ const runtime = await createTestRuntime({ tools: [] });
+ const execute = createToolExecuteWithAuth({
+ scope: "grant-tool",
+ execute: async (_input, ctx) => ({
+ approver: (await ctx.approval!.responder.getToken(provider, { authKey: "github" })).token,
+ requester: (await ctx.getToken(provider, { authKey: "github" })).token,
+ }),
+ });
+
+ const result = await runtime.runAsSession({ sessionId: "session_shared_key" }, async () => {
+ seedUserPrincipal();
+ return await execute(
+ {},
+ {
+ messages: [],
+ toolCallId: "call_grant",
+ approval: {
+ responder: {
+ attributes: {},
+ authenticator: "test-idp",
+ issuer: "test-idp",
+ principalId: approverId,
+ principalType: "user",
+ },
+ },
+ },
+ );
+ });
+
+ expect(result).toEqual({ approver: approverToken, requester: "token:user-1" });
+ expect(fetched).toHaveLength(fetches);
+ },
+ );
+
+ describe("when the requester approves their own call", () => {
+ const selfApproval = {
+ responder: {
+ attributes: {},
+ authenticator: "test-idp",
+ issuer: "test-idp",
+ principalId: "user-1",
+ principalType: "user",
+ },
+ } as const;
+ const tokenProvider = (token: string, fetched: string[]): AuthorizationDefinition => ({
+ principalType: "user",
+ async getToken() {
+ fetched.push(token);
+ return { token };
+ },
+ });
+ const run = async (
+ read: (
+ ctx: ToolContext,
+ github: AuthorizationDefinition,
+ linear: AuthorizationDefinition,
+ ) => Promise<unknown>,
+ ) => {
+ const fetched: string[] = [];
+ const github = tokenProvider("github-secret", fetched);
+ const linear = tokenProvider("linear-secret", fetched);
+ const runtime = await createTestRuntime({ tools: [] });
+ const execute = createToolExecuteWithAuth({
+ scope: "grant-tool",
+ execute: async (_input, ctx) => await read(ctx, github, linear),
+ });
+ const outcome = runtime.runAsSession({ sessionId: "session_mixed_providers" }, async () => {
+ seedUserPrincipal();
+ return await execute(
+ {},
+ { messages: [], toolCallId: "call_grant", approval: selfApproval },
+ );
+ });
+ return { fetched, outcome };
+ };
+
+ it.each([
+ [
+ "requester first",
+ async (ctx: ToolContext, a: AuthorizationDefinition, b: AuthorizationDefinition) => {
+ await ctx.getToken(a);
+ await ctx.approval!.responder.getToken(b);
+ },
+ ],
+ [
+ "approver first",
+ async (ctx: ToolContext, a: AuthorizationDefinition, b: AuthorizationDefinition) => {
+ await ctx.approval!.responder.getToken(a);
+ await ctx.getToken(b);
+ },
+ ],
+ ] as const)(
+ "rejects two anonymous providers across both getters (%s)",
+ async (_order, read) => {
+ const { fetched, outcome } = await run(read);
+ await expect(outcome).rejects.toThrow(/explicit auth keys/);
+ expect(fetched).toEqual(["github-secret"]);
+ },
+ );
+
+ it("returns each provider's own token under distinct explicit keys", async () => {
+ const { fetched, outcome } = await run(async (ctx, github, linear) => ({
+ requester: (await ctx.getToken(github, { authKey: "github" })).token,
+ approver: (await ctx.approval!.responder.getToken(linear, { authKey: "linear" })).token,
+ }));
+ await expect(outcome).resolves.toEqual({
+ requester: "github-secret",
+ approver: "linear-secret",
+ });
+ expect(fetched).toEqual(["github-secret", "linear-secret"]);
+ });
+ });
+
+ it("fails an approved call's approver token lookup without starting a sign-in", async () => {
+ let starts = 0;
+ const provider: AuthorizationDefinition = {
+ principalType: "user",
+ async getToken() {
+ throw requiredError();
+ },
+ async startAuthorization() {
+ starts += 1;
+ return { challenge: { url: "https://idp.example/auth" } };
+ },
+ async completeAuthorization() {
+ return { token: "after-signin" };
+ },
+ };
+ const runtime = await createTestRuntime({ tools: [] });
+ const execute = createToolExecuteWithAuth({
+ scope: "grant-tool",
+ execute: async (_input, ctx) => await ctx.approval!.responder.getToken(provider),
+ });
+
+ const outcome = runtime.runAsSession({ sessionId: "session_approver_token" }, async () => {
+ seedUserPrincipal();
+ // An interactive sign-in is possible here; the approver's lookup must still not start one.
+ loadContext().set(CallbackBaseUrlKey, "https://app.example");
+ return await execute(
+ {},
+ {
+ messages: [],
+ toolCallId: "call_grant",
+ approval: {
+ responder: {
+ attributes: {},
+ authenticator: "test-idp",
+ principalId: "bob",
+ principalType: "user",
+ },
+ },
+ },
+ );
+ });
+
+ await expect(outcome).rejects.toSatisfy(isConnectionAuthorizationFailedError);
+ await expect(outcome).rejects.toMatchObject({
+ reason: "approver_authorization_required",
+ retryable: false,
+ });
+ expect(starts).toBe(0);
+ });
});
diff --git a/packages/eve/src/execution/tool-auth.ts b/packages/eve/src/execution/tool-auth.ts
index 2f72e47b4..6bc9be7d9 100644
--- a/packages/eve/src/execution/tool-auth.ts
+++ b/packages/eve/src/execution/tool-auth.ts
@@ -1,7 +1,12 @@
import { buildBaseToolContext } from "#context/build-base-tool-context.js";
import type { SessionAuthContext } from "#channel/types.js";
import type { ApprovalResponseAuth } from "#approval/definition.js";
-import type { ToolAuthOptions, ToolContext, ToolExecuteOptions } from "#tools/definition.js";
+import type {
+ ApprovedCall,
+ ToolAuthOptions,
+ ToolContext,
+ ToolExecuteOptions,
+} from "#tools/definition.js";
import { createAuthorizationContext } from "#runtime/authorization-context.js";
import { handleAuthorizationError } from "#runtime/connections/scoped-authorization.js";
@@ -19,6 +24,9 @@ export function createToolExecuteWithAuth<TInput>(input: ToolExecuteWithAuthInpu
messages: options.messages,
getToken: auth.getToken,
requireAuth: auth.requireAuth,
+ ...(options.approval !== undefined && {
+ approval: approvalOf(options.approval.responder, auth),
+ }),
};
return auth.run(() => {
return input.execute(toolInput, ctx);
@@ -26,6 +34,19 @@ export function createToolExecuteWithAuth<TInput>(input: ToolExecuteWithAuthInpu
};
}
+/** What an approved call reads about the person who approved it. */
+function approvalOf(
+ responder: SessionAuthContext,
+ auth: ReturnType<typeof createAuthorizationContext>,
+): ApprovedCall {
+ return {
+ responder: {
+ ...responder,
+ getToken: (provider, options) => auth.getResponderToken(responder, provider, options),
+ },
+ };
+}
+
/** Binds the same capability to the person responding to an approval. */
export function buildApprovalResponseAuth(input: {
readonly responder: SessionAuthContext;
diff --git a/packages/eve/src/harness/hitl/approved-calls.test.ts b/packages/eve/src/harness/hitl/approved-calls.test.ts
index 0d5574a9d..4d75fd4d0 100644
--- a/packages/eve/src/harness/hitl/approved-calls.test.ts
+++ b/packages/eve/src/harness/hitl/approved-calls.test.ts
@@ -47,6 +47,7 @@ it("settles calls a cancellation cut short, and keeps their siblings' results",
messages: [],
position: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
publish: async () => {},
+ responderOf: () => undefined,
requests: [approval("call-finished", "finished"), approval("call-cut", "cut")],
tools: new Map([
["finished", finished],
@@ -73,6 +74,7 @@ it("leaves a call the cancellation stopped before it started without a result",
messages: [],
position: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
publish: async () => {},
+ responderOf: () => undefined,
requests: [approval("call-unstarted", "unstarted")],
tools: new Map([["unstarted", unstarted]]),
});
diff --git a/packages/eve/src/harness/hitl/approved-calls.ts b/packages/eve/src/harness/hitl/approved-calls.ts
index 9e4bd4425..80a93e4b5 100644
--- a/packages/eve/src/harness/hitl/approved-calls.ts
+++ b/packages/eve/src/harness/hitl/approved-calls.ts
@@ -8,6 +8,7 @@ import {
} from "ai";
import { createRuntimeToolResultFromValue } from "#harness/action-result-helpers.js";
+import type { SessionAuthContext } from "#channel/types.js";
import { isInlineAuthorizationToolResult } from "#harness/inline-tool-authorization.js";
import { toolCallModelOutput } from "#harness/tool-call-io.js";
import { projectDeltaPresentation, projectResultPresentation } from "#harness/tool-presentation.js";
@@ -61,6 +62,8 @@ export async function runApprovedCalls(input: {
readonly abortSignal: AbortSignal | undefined;
/** The step attempt's telemetry, which hears each execution as the AI SDK reports it. */
readonly telemetry?: TelemetryOptions;
+ /** Who approved each request, which the call reads as `ctx.approval`; it still runs as the requester. */
+ readonly responderOf: (request: InputRequest) => SessionAuthContext | undefined;
}): Promise<{
readonly settled: readonly ApprovedCallResult[];
readonly toolResults: readonly TypedToolResult<ToolSet>[];
@@ -145,7 +148,9 @@ export async function runApprovedCalls(input: {
const startedAt = performance.now();
try {
started = true;
+ const responder = input.responderOf(request);
const executed = execute(args, {
+ ...(responder !== undefined && { approval: { responder } }),
abortSignal: input.abortSignal,
messages: [...input.messages],
toolCallId: callId,
diff --git a/packages/eve/src/harness/hitl/candidates.ts b/packages/eve/src/harness/hitl/candidates.ts
index 37c275db1..430a46c65 100644
--- a/packages/eve/src/harness/hitl/candidates.ts
+++ b/packages/eve/src/harness/hitl/candidates.ts
@@ -37,6 +37,11 @@ export interface ApprovalResponderIdentity {
export interface ApprovalSettlementAuditRecord {
readonly actor: ApprovalResponderIdentity;
+ /**
+ * The full auth of the person who approved, present only when allowed. The approved call reads
+ * it as `ctx.approval.responder`; it never runs as it.
+ */
+ readonly responder?: SessionAuthContext;
/** `unavailable`: the request's entry was gone, so its call is reported unavailable, never run. */
readonly outcome: "allowed" | "cancelled" | "unavailable";
readonly requestId: string;
@@ -310,6 +315,7 @@ function settleRequest(input: {
const settlement: ApprovalSettlementAuditRecord = {
actor: projectResponder(input.responder),
+ ...(input.outcome === "allowed" && { responder: input.responder }),
candidateId: input.candidateId,
outcome: input.outcome,
requestId: input.requestId,
@@ -402,3 +408,11 @@ export function retireActiveCandidates(
}
return next;
}
+
+/** The full auth of whoever approved `requestId`, when a person allowed it. */
+export function responderOfRequest(
+ state: SessionStateMap | undefined,
+ requestId: string,
+): SessionAuthContext | undefined {
+ return readApprovalState(state).settlements[requestId]?.responder;
+}
diff --git a/packages/eve/src/harness/hitl/intake.ts b/packages/eve/src/harness/hitl/intake.ts
index 496804f05..3b097fde7 100644
--- a/packages/eve/src/harness/hitl/intake.ts
+++ b/packages/eve/src/harness/hitl/intake.ts
@@ -26,7 +26,7 @@ import {
withdrawSignIns,
} from "./approvals.js";
import { rejectApprovedCall, runApprovedCalls, type ApprovedCallResult } from "./approved-calls.js";
-import { getApprovalAuditState, retireActiveCandidates } from "./candidates.js";
+import { getApprovalAuditState, responderOfRequest, retireActiveCandidates } from "./candidates.js";
import { coordinateApprovalDelivery } from "./coordinator.js";
import { deliver, resolveTypedApproval, turnInputOnly, withoutTurnInput } from "./delivery.js";
import { recheckApprovedCall } from "#harness/tools.js";
@@ -331,6 +331,7 @@ export async function runApprovedLocalCalls(
position: step.position(),
publish: step.publish,
requests,
+ responderOf: (request) => responderOfRequest(step.session.state, request.requestId),
telemetry: attempt?.telemetry,
tools,
});
diff --git a/packages/eve/src/public/tools/index.ts b/packages/eve/src/public/tools/index.ts
index f427fe9c5..1fe85cb6f 100644
--- a/packages/eve/src/public/tools/index.ts
+++ b/packages/eve/src/public/tools/index.ts
@@ -7,6 +7,8 @@ export {
defineTool,
disableTool,
isDisabledToolSentinel,
+ type ApprovalResponder,
+ type ApprovedCall,
type ToolLabelDefinition,
type ToolAuthOptions,
type ToolAuthProvider,
diff --git a/packages/eve/src/runtime/authorization-context.ts b/packages/eve/src/runtime/authorization-context.ts
index 3cce7b556..eb200d193 100644
--- a/packages/eve/src/runtime/authorization-context.ts
+++ b/packages/eve/src/runtime/authorization-context.ts
@@ -22,6 +22,20 @@ export function createAuthorizationContext(input: {
if (provider === undefined) throw missingProviderError("ctx.getToken");
return await execution.getToken(resolve(provider, options));
},
+ /**
+ * The given responder's stored token, resolved through this execution's
+ * providers; never starts or completes a sign-in.
+ */
+ async getResponderToken(
+ responder: SessionAuthContext,
+ provider: ToolAuthProvider,
+ options?: ToolAuthOptions,
+ ): Promise<TokenResult> {
+ return await execution.getResponderToken({
+ ...resolve(provider, options),
+ boundResponder: responder,
+ });
+ },
requireAuth(provider?: ToolAuthProvider, options?: ToolAuthOptions): never {
if (provider === undefined) throw missingProviderError("ctx.requireAuth");
return execution.requireAuth(resolve(provider, options));
diff --git a/packages/eve/src/runtime/connections/scoped-authorization.ts b/packages/eve/src/runtime/connections/scoped-authorization.ts
index 38fe76f8e..676c9de7e 100644
--- a/packages/eve/src/runtime/connections/scoped-authorization.ts
+++ b/packages/eve/src/runtime/connections/scoped-authorization.ts
@@ -105,6 +105,25 @@ export function createAuthorizationExecution(
return requireAuth(scoped, error);
}
},
+ /**
+ * Resolves a stored token for the bound responder, who isn't part of this
+ * execution: it never starts or completes a sign-in, so a missing token
+ * fails terminally instead of reaching the interruption boundary.
+ */
+ async getResponderToken(scoped: ScopedAuthorization): Promise<TokenResult> {
+ try {
+ return await resolveScopedToken(scoped);
+ } catch (error) {
+ if (!isConnectionAuthorizationRequiredError(error)) {
+ throw error;
+ }
+ throw new ConnectionAuthorizationFailedError(scoped.scope, {
+ message: `The approver of "${scoped.scope}" has no token for this provider, and an approved call doesn't start a sign-in.`,
+ reason: "approver_authorization_required",
+ retryable: false,
+ });
+ }
+ },
requireAuth,
async handleError(error: unknown, scoped?: ScopedAuthorization): Promise<AuthorizationSignal> {
if (scoped !== undefined && isConnectionAuthorizationRequiredError(error)) {
diff --git a/packages/eve/src/tools/definition.ts b/packages/eve/src/tools/definition.ts
index 3d2380b35..650e518e9 100644
--- a/packages/eve/src/tools/definition.ts
+++ b/packages/eve/src/tools/definition.ts
@@ -5,6 +5,7 @@ import type {
} from "#compiled/@standard-schema/spec/index.js";
import type { ToolApproval } from "#approval/definition.js";
+import type { SessionAuthContext } from "#channel/types.js";
import type { SessionContext } from "#context/session-context.js";
import { stampDefinitionKey } from "#internal/authored-definition/source-identity.js";
import type { JsonObject } from "#shared/json.js";
@@ -23,7 +24,10 @@ type ApprovalContextInput<TInput> = unknown extends TInput ? Record<string, unkn
export type { ToolAuthDefinition, ToolAuthOptions, ToolAuthProvider } from "#tools/auth.js";
export type { ToolModelOutput, ToolModelOutputPart } from "#tools/model-output.js";
-export type ToolExecuteOptions = Omit<ToolExecutionOptions<unknown>, "context">;
+export type ToolExecuteOptions = Omit<ToolExecutionOptions<unknown>, "context"> & {
+ /** Who approved the call, when it runs after a person approved it. */
+ readonly approval?: { readonly responder: SessionAuthContext };
+};
export type ToolExecuteFn<TInput = unknown, TOutput = unknown> = (
input: TInput,
@@ -216,8 +220,41 @@ export type ToolContext = SessionContext & {
* token returned by {@link getToken}.
*/
requireAuth(provider: ToolAuthProvider, options?: ToolAuthOptions): never;
+ /**
+ * The person who approved this call. Present only when the call runs after a
+ * person approved it; absent for calls that needed no approval.
+ */
+ readonly approval?: ApprovedCall;
};
+/**
+ * The approval behind an approved tool call. The call still runs as the
+ * requester, `ctx.session.auth.current`; this only lets it read who approved
+ * it and act with their credentials where the tool chooses to.
+ */
+export interface ApprovedCall {
+ /** Who approved the call: the same principal its response policy saw. */
+ readonly responder: ApprovalResponder;
+}
+
+/**
+ * The person who approved a call, with access to their own credentials. A
+ * transient object built for each approved call: its identity fields are the
+ * stored responder record, and `getToken` is not serialized with them.
+ */
+export interface ApprovalResponder extends SessionAuthContext {
+ /**
+ * Resolves the responder's token for an inline provider, as
+ * {@link ToolContext.getToken} does for the requester. It never starts a
+ * sign-in: when the responder has no token, it throws a non-retryable
+ * `ConnectionAuthorizationFailedError` with
+ * `reason: "approver_authorization_required"`. It shares the call's
+ * providers with `ctx.getToken`, so two inline providers without provider
+ * metadata need `options.authKey` across both getters too.
+ */
+ getToken(provider: ToolAuthProvider, options?: ToolAuthOptions): Promise<TokenResult>;
+}
+
/**
* Public tool definition authored in `agent/tools/*.ts`.
*