Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): approvals - standardize approval policies (#293)

Andrew Barba78ef30aa243a
diff --git a/.changeset/bright-owls-approve.md b/.changeset/bright-owls-approve.md
new file mode 100644
index 000000000..a116ac2af
--- /dev/null
+++ b/.changeset/bright-owls-approve.md
@@ -0,0 +1,5 @@
+---
+"eve": minor
+---
+
+Standardize authored tools and connections on an `approval` function that receives the active session context and returns AI SDK 7 approval statuses, with synchronous and asynchronous policies supported. Boolean results remain supported as aliases for user approval and no approval, schedules no longer accept approval configuration, and no AI SDK 6 `needsApproval` adapter remains.
diff --git a/apps/fixtures/weather-agent/agent/tools/get_weather.ts b/apps/fixtures/weather-agent/agent/tools/get_weather.ts
index 000fe8917..5d104b4bb 100644
--- a/apps/fixtures/weather-agent/agent/tools/get_weather.ts
+++ b/apps/fixtures/weather-agent/agent/tools/get_weather.ts
@@ -5,7 +5,7 @@ import { z } from "zod";
const sleep = (ms: number) => new Promise((res) => setTimeout(res, ms));
export default defineTool({
- needsApproval: never(),
+ approval: never(),
description: "Get the current weather for a city.",
inputSchema: z.object({
city: z.string(),
diff --git a/apps/frameworks/nuxt/agent/tools/get_weather.ts b/apps/frameworks/nuxt/agent/tools/get_weather.ts
index 19401e064..ef51ad41d 100644
--- a/apps/frameworks/nuxt/agent/tools/get_weather.ts
+++ b/apps/frameworks/nuxt/agent/tools/get_weather.ts
@@ -5,7 +5,7 @@ import { z } from "zod";
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
export default defineTool({
- needsApproval: never(),
+ approval: never(),
description: "Get the current weather for a city.",
inputSchema: z.object({
city: z.string(),
diff --git a/apps/frameworks/sveltekit/agent/tools/get_weather.ts b/apps/frameworks/sveltekit/agent/tools/get_weather.ts
index 19401e064..ef51ad41d 100644
--- a/apps/frameworks/sveltekit/agent/tools/get_weather.ts
+++ b/apps/frameworks/sveltekit/agent/tools/get_weather.ts
@@ -5,7 +5,7 @@ import { z } from "zod";
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
export default defineTool({
- needsApproval: never(),
+ approval: never(),
description: "Get the current weather for a city.",
inputSchema: z.object({
city: z.string(),
diff --git a/apps/templates/web-chat-next/agent/tools/randomize.ts b/apps/templates/web-chat-next/agent/tools/randomize.ts
index c5e0efb91..f50717dff 100644
--- a/apps/templates/web-chat-next/agent/tools/randomize.ts
+++ b/apps/templates/web-chat-next/agent/tools/randomize.ts
@@ -3,7 +3,7 @@ import { never } from "eve/tools/approval";
import { z } from "zod";
export default defineTool({
- needsApproval: never(),
+ approval: never(),
description:
"Generate a random result: pick one of the given choices, or a random number between min and max.",
inputSchema: z.object({
diff --git a/docs/guides/frontend/overview.mdx b/docs/guides/frontend/overview.mdx
index 4766b8676..182bad3d1 100644
--- a/docs/guides/frontend/overview.mdx
+++ b/docs/guides/frontend/overview.mdx
@@ -100,7 +100,7 @@ Assistant text, reasoning, tool calls, and tool results stream into `data` as th
## Human-in-the-loop prompts
-Tools opt into approval with `needsApproval`, and the model can also ask a question with `ask_question` — see [Human-in-the-loop](/docs/human-in-the-loop) for the server-side model. Either way the stream emits an `input.requested` event, and the pending request rides on a `dynamic-tool` part of the latest message at `part.toolMetadata?.eve?.inputRequest`. Read it, then answer through the same session with `send()`:
+Tools opt into approval with `approval`, and the model can also ask a question with `ask_question` — see [Human-in-the-loop](/docs/human-in-the-loop) for the server-side model. Either way the stream emits an `input.requested` event, and the pending request rides on a `dynamic-tool` part of the latest message at `part.toolMetadata?.eve?.inputRequest`. Read it, then answer through the same session with `send()`:
```tsx
const request = agent.data.messages
diff --git a/docs/guides/frontend/use-eve-agent-svelte.mdx b/docs/guides/frontend/use-eve-agent-svelte.mdx
index 6ec911ca6..83c4a9955 100644
--- a/docs/guides/frontend/use-eve-agent-svelte.mdx
+++ b/docs/guides/frontend/use-eve-agent-svelte.mdx
@@ -78,7 +78,7 @@ await agent.send({
## Human-in-the-loop prompts
-A tool opts into approval with `needsApproval` ([Tools](../../tools)). When one fires, the pending request rides along on a `dynamic-tool` part of the latest message at `part.toolMetadata?.eve?.inputRequest`. Read it, then answer through the same session with `agent.send({ inputResponses })`:
+A tool opts into approval with `approval` ([Tools](../../tools)). When one fires, the pending request rides along on a `dynamic-tool` part of the latest message at `part.toolMetadata?.eve?.inputRequest`. Read it, then answer through the same session with `agent.send({ inputResponses })`:
```ts
import type { EveDynamicToolPart, EveMessagePart } from "eve/svelte";
diff --git a/docs/guides/frontend/use-eve-agent-vue.mdx b/docs/guides/frontend/use-eve-agent-vue.mdx
index efdcebe97..105be0d2e 100644
--- a/docs/guides/frontend/use-eve-agent-vue.mdx
+++ b/docs/guides/frontend/use-eve-agent-vue.mdx
@@ -89,7 +89,7 @@ async function onFileChange(event: Event) {
## Human-in-the-loop prompts
-A tool opts into approval with `needsApproval` ([Tools](../../tools)). When it triggers, the pending request shows up as a `dynamic-tool` part on the latest message at `part.toolMetadata?.eve?.inputRequest`. Read it, then answer through the same session with `send({ inputResponses })`:
+A tool opts into approval with `approval` ([Tools](../../tools)). When it triggers, the pending request shows up as a `dynamic-tool` part on the latest message at `part.toolMetadata?.eve?.inputRequest`. Read it, then answer through the same session with `send({ inputResponses })`:
```ts
import type { EveDynamicToolPart, EveMessagePart } from "eve/vue";
diff --git a/docs/reference/typescript-api.md b/docs/reference/typescript-api.md
index b2e4cbff3..1e5ccade7 100644
--- a/docs/reference/typescript-api.md
+++ b/docs/reference/typescript-api.md
@@ -51,7 +51,7 @@ export default defineTool({
| `defineEvalConfig` | `eve/evals` | `evals/evals.config.ts` | [Evals](../evals/overview) |
| `useEveAgent` | `eve/react`, `eve/vue`, `eve/svelte` | frontend | [Frontend](../guides/frontend/overview) |
-A few non-`define*` helpers round out the set: `disableTool` and `ExperimentalWorkflow` from `eve/tools` (see [Default harness](../concepts/default-harness)), the route verbs `GET`/`POST`/`PUT`/`PATCH`/`DELETE`/`WS` from `eve/channels`, the approval predicates `always`/`once`/`never` from `eve/tools/approval`, and the channel auth helpers `localDev`/`vercelOidc`/`placeholderAuth` from `eve/channels/auth`. To wrap a built-in tool, import its default value from `eve/tools/defaults` (`bash`, `readFile`, `writeFile`, `glob`, `grep`, `webFetch`, `webSearch`, `todo`, `loadSkill`). `AgentReasoningDefinition` is exported from `eve` for the top-level `defineAgent({ reasoning })` setting. `AgentWorkflowDefinition` and `AgentWorkflowWorldDefinition` are exported from `eve` for the `defineAgent({ experimental: { workflow } })` config shape.
+A few non-`define*` helpers round out the set: `disableTool` and `ExperimentalWorkflow` from `eve/tools` (see [Default harness](../concepts/default-harness)), the route verbs `GET`/`POST`/`PUT`/`PATCH`/`DELETE`/`WS` from `eve/channels`, the approval policies `always`/`once`/`never` from `eve/tools/approval`, and the channel auth helpers `localDev`/`vercelOidc`/`placeholderAuth` from `eve/channels/auth`. To wrap a built-in tool, import its default value from `eve/tools/defaults` (`bash`, `readFile`, `writeFile`, `glob`, `grep`, `webFetch`, `webSearch`, `todo`, `loadSkill`). `AgentReasoningDefinition` is exported from `eve` for the top-level `defineAgent({ reasoning })` setting. `AgentWorkflowDefinition` and `AgentWorkflowWorldDefinition` are exported from `eve` for the `defineAgent({ experimental: { workflow } })` config shape.
## Runtime context (`ctx`)
diff --git a/docs/subagents.mdx b/docs/subagents.mdx
index b505fc131..cb5f1bb6c 100644
--- a/docs/subagents.mdx
+++ b/docs/subagents.mdx
@@ -88,7 +88,7 @@ A declared subagent's tool name is the bare path-derived name, with no prefix. `
Because the name lives in the same runtime tool namespace as authored tools, a subagent named `researcher` collides with a tool named `researcher`. eve rejects the build rather than picking a winner, so keep subagent directory names distinct from tool names.
-Do not rely on subagent delegation by itself as an approval boundary. Put sensitive tools behind `needsApproval`, connection approval, route/session authorization, or other controls wherever those tools can be called.
+Do not rely on subagent delegation by itself as an approval boundary. Put sensitive tools behind `approval`, connection approval, route/session authorization, or other controls wherever those tools can be called.
Each delegated subagent spins up its own child session and stream. The parent stream carries only the control-plane events `subagent.called` and `subagent.completed`. To follow the child's full progress, read `subagent.called.data.childSessionId` and subscribe at `GET /eve/v1/session/:childSessionId/stream`.
diff --git a/docs/tools/human-in-the-loop.md b/docs/tools/human-in-the-loop.md
index a9b0af5b6..51743574e 100644
--- a/docs/tools/human-in-the-loop.md
+++ b/docs/tools/human-in-the-loop.md
@@ -13,7 +13,7 @@ Either way the run parks at `session.waiting`, durably, for as long as it takes
## Approvals
-Approval is a property of a [tool](/docs/tools) that pauses for a person before it runs. Gate a tool with `needsApproval` and the helpers from `eve/tools/approval`:
+Approval is a property of a [tool](/docs/tools) that pauses for a person before it runs. Gate a tool with `approval` and the helpers from `eve/tools/approval`:
```ts title="agent/tools/refund_charge.ts"
import { defineTool } from "eve/tools";
@@ -22,8 +22,8 @@ import { z } from "zod";
export default defineTool({
description: "Refund a charge.",
- inputSchema: z.object({ chargeId: z.string(), amount: z.number() }),
- needsApproval: always(), // or once() / never() / a predicate
+ inputSchema: z.object({ tenantId: z.string(), chargeId: z.string(), amount: z.number() }),
+ approval: always(), // or once() / never() / a policy
async execute(input) {
return refund(input);
},
@@ -36,14 +36,24 @@ export default defineTool({
| `once()` | Require approval only the first time the tool runs in a session; auto-allow after. |
| `always()` | Require approval before every call. |
-By default, omitted `needsApproval` behaves like `never()`, so tool calls may execute without human approval. Require human approval or other safeguards for sensitive, irreversible, regulated, financial, healthcare, employment, housing, legal, safety-impacting, user-impacting, or external side-effecting actions.
+By default, omitted `approval` behaves like `never()`, so tool calls may execute without human approval. Require human approval or other safeguards for sensitive, irreversible, regulated, financial, healthcare, employment, housing, legal, safety-impacting, user-impacting, or external side-effecting actions.
-When the decision depends on the input, pass your own predicate instead of a helper. It receives `{ toolName, toolInput, approvedTools }` and returns a boolean. `toolInput` can be undefined, so guard the access. To require approval only when an amount crosses a threshold:
+When the decision depends on the input, pass your own policy instead of a helper. It receives the same session context as tool execution, plus `{ toolName, toolInput, approvedTools }`, and returns an AI SDK 7 approval status synchronously or as a promise. Use `ctx.session.auth.current` to guard by the caller of the current turn and `ctx.session.auth.initiator` to guard by the caller that created the session. Return `"user-approval"` to pause for a person or `"not-applicable"` to continue without a prompt. `toolInput` can be undefined, so guard the access. This policy denies cross-tenant calls, then requires approval only when an amount crosses a threshold:
```ts
-needsApproval: ({ toolInput }) => (toolInput?.amount ?? 0) > 1000,
+approval: ({ session, toolInput }) => {
+ const callerTenant = session.auth.current?.attributes.tenantId;
+ if (callerTenant === undefined || callerTenant !== toolInput?.tenantId) {
+ return { type: "denied", reason: "Caller cannot access this tenant." };
+ }
+ return (toolInput?.amount ?? 0) > 1000 ? "user-approval" : "not-applicable";
+},
```
+For compatibility with the previous predicate shape, policies may return booleans: `true` is treated as `"user-approval"` and `false` as `"not-applicable"`. Boolean promises are supported too.
+
+Policies can also return `"approved"` or `"denied"` to decide automatically. Use `{ type: "approved" | "denied", reason }` when the model should receive a reason. The `Approval`, `ApprovalContext`, and `ApprovalStatus` types are exported from both `eve/tools` and `eve/tools/approval`.
+
Gating a side effect on approval is also how you make non-idempotent work safe across replays: a charge or email that sits behind `always()` can't fire from a re-run step without a fresh human decision.
## Questions
diff --git a/docs/tools/overview.mdx b/docs/tools/overview.mdx
index 3c51181f0..1a2782af5 100644
--- a/docs/tools/overview.mdx
+++ b/docs/tools/overview.mdx
@@ -46,7 +46,7 @@ eve never runs authored tools during discovery. The model sees descriptors first
## Gate a tool on human approval
-A tool can require a person to sign off before it runs. Set `needsApproval` with the helpers from `eve/tools/approval`:
+A tool can require a person to sign off before it runs. Set `approval` with the helpers from `eve/tools/approval`:
```ts title="agent/tools/refund_charge.ts"
import { defineTool } from "eve/tools";
@@ -56,14 +56,14 @@ import { z } from "zod";
export default defineTool({
description: "Refund a charge.",
inputSchema: z.object({ chargeId: z.string(), amount: z.number() }),
- needsApproval: always(), // or once() / never() / a predicate
+ approval: always(), // or once() / never() / a policy
async execute(input) {
return refund(input);
},
});
```
-Approval is one half of eve's [human-in-the-loop](./human-in-the-loop) model — the page covers the `always/once/never` helpers, input-dependent predicates, and how a gated call pauses and resumes durably.
+Approval is one half of eve's [human-in-the-loop](./human-in-the-loop) model — the page covers the `always/once/never` helpers, input-dependent policies, and how a gated call pauses and resumes durably.
## Shape what the model sees with `toModelOutput`
diff --git a/docs/tutorial/guard-the-spend.mdx b/docs/tutorial/guard-the-spend.mdx
index db92bb9ac..895c5817f 100644
--- a/docs/tutorial/guard-the-spend.mdx
+++ b/docs/tutorial/guard-the-spend.mdx
@@ -5,7 +5,7 @@ description: "Part 8 of the Build an Agent tutorial. Gate expensive queries with
A single warehouse query can scan terabytes and run up the bill. So before the analytics assistant fires off an expensive scan, make it stop and check with you. The agent pauses, asks you, and resumes with your answer. That's human-in-the-loop, and you wire it up with one field on the tool.
-`needsApproval` runs before `execute`. Return `true` and the turn parks on an approval request; you answer, and the run picks up from that exact step. The function gets the tool input, so you can make the decision cost-based.
+`approval` runs before `execute`. Return `"user-approval"` and the turn parks on an approval request; you answer, and the run picks up from that exact step. The function gets the tool input, so you can make the decision cost-based.
## Estimate, then gate
@@ -32,7 +32,8 @@ export default defineTool({
description: "Run a read-only SQL query against the analytics tables.",
inputSchema: z.object({ sql: z.string() }),
// Cost-based gate: only the expensive queries need a human yes.
- needsApproval: ({ toolInput }) => estimateScanGb(toolInput?.sql ?? "") > THRESHOLD_GB,
+ approval: ({ toolInput }) =>
+ estimateScanGb(toolInput?.sql ?? "") > THRESHOLD_GB ? "user-approval" : "not-applicable",
async execute({ sql }) {
const { columns, rows } = await runReadOnlySql(sql);
return { columns, rows: rows.slice(0, 500), truncated: rows.length > 500 };
@@ -50,7 +51,7 @@ Ask for something that forces a large unfiltered scan:
Total revenue across all customers, all time, broken out by day.
```
-The model proposes the query, `needsApproval` returns `true`, and the turn parks. The stream emits `input.requested`, then `session.waiting`. How the prompt looks depends on the channel, whether buttons in the TUI, Block Kit in Slack, or a UI control on the web. Approve it and the run resumes from exactly that step, then the query runs. Deny it and the tool is skipped, with the model told why.
+The model proposes the query, `approval` returns `"user-approval"`, and the turn parks. The stream emits `input.requested`, then `session.waiting`. How the prompt looks depends on the channel, whether buttons in the TUI, Block Kit in Slack, or a UI control on the web. Approve it and the run resumes from exactly that step, then the query runs. Deny it and the tool is skipped, with the model told why.
Each session has exactly one active continuation. Answer an approval against a stale handle and it's rejected, so there's no way to double-resume the same parked turn.
diff --git a/docs/tutorial/ship-it.mdx b/docs/tutorial/ship-it.mdx
index 5907fb8c2..a9998546e 100644
--- a/docs/tutorial/ship-it.mdx
+++ b/docs/tutorial/ship-it.mdx
@@ -142,7 +142,7 @@ Across the nine steps you built and shipped one agent, and along the way you use
- **The sandbox** to compute and chart beyond SQL in an isolated `/workspace`.
- **State** (`defineState`) to remember the team's glossary across turns.
- **Dynamic skills** (`defineDynamic`) to load the right team playbook per caller.
-- **Human-in-the-loop** approval (`needsApproval`) to gate expensive queries.
+- **Human-in-the-loop** approval (`approval`) to gate expensive queries.
- **Channel auth** to turn a request into an authenticated principal.
- **Deployment** to Vercel, with the runtime behind your web app.
diff --git a/e2e/fixtures/agent-subagents-hitl/agent/subagents/stock-price/tools/get_stock_price.ts b/e2e/fixtures/agent-subagents-hitl/agent/subagents/stock-price/tools/get_stock_price.ts
index 7a6c6ebe0..97a7f0c6f 100644
--- a/e2e/fixtures/agent-subagents-hitl/agent/subagents/stock-price/tools/get_stock_price.ts
+++ b/e2e/fixtures/agent-subagents-hitl/agent/subagents/stock-price/tools/get_stock_price.ts
@@ -15,7 +15,7 @@ export default defineTool({
inputSchema: z.object({
ticker: z.string().describe("Stock ticker symbol"),
}),
- needsApproval: () => true,
+ approval: () => "user-approval",
async execute(input) {
const ticker = input.ticker.toUpperCase();
const data = MOCK_PRICES[ticker];
diff --git a/e2e/fixtures/agent-subagents-hitl/evals/hitl.eval.ts b/e2e/fixtures/agent-subagents-hitl/evals/hitl.eval.ts
index 26ecbc2e3..a4bfdbc6f 100644
--- a/e2e/fixtures/agent-subagents-hitl/evals/hitl.eval.ts
+++ b/e2e/fixtures/agent-subagents-hitl/evals/hitl.eval.ts
@@ -19,7 +19,7 @@ function subagentOutputs(events: readonly HandleMessageStreamEvent[]): string[]
/**
* Parent/child HITL proxying: the stock-price subagent's tool approval
- * (`needsApproval: () => true`) surfaces on the parent stream, the approval
+ * (`approval: () => "user-approval"`) surfaces on the parent stream, the approval
* routes back down, and the child's result splices into the parent reply.
* Parking is server-side.
*/
diff --git a/e2e/fixtures/agent-tools-hitl/agent/tools/dynamic-guarded-echo.ts b/e2e/fixtures/agent-tools-hitl/agent/tools/dynamic-guarded-echo.ts
index 0d5262885..59b824f7f 100644
--- a/e2e/fixtures/agent-tools-hitl/agent/tools/dynamic-guarded-echo.ts
+++ b/e2e/fixtures/agent-tools-hitl/agent/tools/dynamic-guarded-echo.ts
@@ -13,7 +13,7 @@ export default defineDynamic({
inputSchema: z.object({
note: z.string().optional(),
}),
- needsApproval: () => true,
+ approval: () => "user-approval",
async execute(input) {
return {
echoed: input.note ?? null,
diff --git a/e2e/fixtures/agent-tools-hitl/agent/tools/guarded-echo.ts b/e2e/fixtures/agent-tools-hitl/agent/tools/guarded-echo.ts
index f2f8fc56a..7402b3541 100644
--- a/e2e/fixtures/agent-tools-hitl/agent/tools/guarded-echo.ts
+++ b/e2e/fixtures/agent-tools-hitl/agent/tools/guarded-echo.ts
@@ -13,7 +13,7 @@ export default defineTool({
inputSchema: z.object({
note: z.string().optional().describe("Any note string."),
}),
- needsApproval: once(),
+ approval: once(),
async execute(input) {
return {
echoed: input.note ?? null,
diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/dynamic-guarded-replay.eval.ts b/e2e/fixtures/agent-tools-hitl/evals/hitl/dynamic-guarded-replay.eval.ts
index a679ae09c..cb5ec7a42 100644
--- a/e2e/fixtures/agent-tools-hitl/evals/hitl/dynamic-guarded-replay.eval.ts
+++ b/e2e/fixtures/agent-tools-hitl/evals/hitl/dynamic-guarded-replay.eval.ts
@@ -6,11 +6,11 @@ const TOOL_NAME = "dynamic_guarded_echo";
/**
* HITL flow: a session-scoped dynamic tool's approval gate survives durable
- * replay. If replay drops `needsApproval`, the tool executes immediately and
+ * replay. If replay drops `approval`, the tool executes immediately and
* this eval fails before approval.
*/
export default defineEval({
- description: "HITL smoke: replayed dynamic tools preserve needsApproval.",
+ description: "HITL smoke: replayed dynamic tools preserve approval.",
async test(t) {
await t.send(`Call the \`${TOOL_NAME}\` tool with note "before-approval".`);
const [request] = t.expectInputRequests({
diff --git a/e2e/fixtures/agent-tools-sandbox/agent/tools/bash.ts b/e2e/fixtures/agent-tools-sandbox/agent/tools/bash.ts
index 0f70bcd07..7822464cf 100644
--- a/e2e/fixtures/agent-tools-sandbox/agent/tools/bash.ts
+++ b/e2e/fixtures/agent-tools-sandbox/agent/tools/bash.ts
@@ -3,7 +3,7 @@ import { never } from "eve/tools/approval";
/**
* Bash tool exposed to the model for the sandbox-bootstrap smoke
- * test. `needsApproval: never()` keeps the smoke test single-turn
+ * test. `approval: never()` keeps the smoke test single-turn
* and avoids tripping the HITL machinery already exercised by
* `tool-approval.ts` / `tool-denial.ts`.
*
@@ -14,5 +14,5 @@ import { never } from "eve/tools/approval";
*/
export default defineTool({
...defineBashTool(),
- needsApproval: never(),
+ approval: never(),
});
diff --git a/e2e/fixtures/agent-tools/agent/tools/always-throws.ts b/e2e/fixtures/agent-tools/agent/tools/always-throws.ts
index 95646aeb8..ae116e3fb 100644
--- a/e2e/fixtures/agent-tools/agent/tools/always-throws.ts
+++ b/e2e/fixtures/agent-tools/agent/tools/always-throws.ts
@@ -11,7 +11,7 @@ import { z } from "zod";
* tool-error result), the harness does NOT emit `turn.failed`, and the
* session remains usable for a follow-up message.
*
- * `needsApproval: never()` keeps the test single-turn from a HITL
+ * `approval: never()` keeps the test single-turn from a HITL
* perspective so the throw path is the only thing under test.
*/
export default defineTool({
@@ -20,7 +20,7 @@ export default defineTool({
inputSchema: z.object({
reason: z.string().describe("Free-form reason for the call. The tool ignores it and throws."),
}),
- needsApproval: never(),
+ approval: never(),
async execute(_input) {
throw new Error("always-throws: intentional failure for smoke-test coverage");
},
diff --git a/packages/eve/src/context/build-dynamic-tools.ts b/packages/eve/src/context/build-dynamic-tools.ts
index 5f1cc4a92..865c70e2e 100644
--- a/packages/eve/src/context/build-dynamic-tools.ts
+++ b/packages/eve/src/context/build-dynamic-tools.ts
@@ -10,7 +10,7 @@ import {
import type { DurableDynamicToolMetadata } from "#context/keys.js";
import { buildCallbackContext } from "#context/build-callback-context.js";
import { createLogger } from "#internal/logging.js";
-import type { NeedsApprovalContext } from "#public/definitions/tool.js";
+import type { ApprovalContext, ApprovalStatus } from "#public/definitions/approval.js";
const log = createLogger("dynamic-tools");
@@ -53,7 +53,7 @@ function replayTools(metadata: readonly DurableDynamicToolMetadata[]): HarnessTo
execute: (input: unknown) => stepFn(m.closureVars, input, buildCallbackContext()),
inputSchema: jsonSchema(m.inputSchema),
name: m.name,
- needsApproval: buildReplayedNeedsApproval(m),
+ approval: buildReplayedApproval(m),
outputSchema: m.outputSchema === undefined ? undefined : jsonSchema(m.outputSchema),
});
}
@@ -61,24 +61,24 @@ function replayTools(metadata: readonly DurableDynamicToolMetadata[]): HarnessTo
return tools;
}
-function buildReplayedNeedsApproval(
+function buildReplayedApproval(
metadata: DurableDynamicToolMetadata,
-): HarnessToolDefinition["needsApproval"] | undefined {
- if (metadata.needsApprovalStepFnName === undefined) {
+): HarnessToolDefinition["approval"] | undefined {
+ if (metadata.approvalStepFnName === undefined) {
return undefined;
}
- const approvalStepFn = lookupStepFunction(metadata.needsApprovalStepFnName);
+ const approvalStepFn = lookupStepFunction(metadata.approvalStepFnName);
if (approvalStepFn === null) {
log.warn(
- `Dynamic tool "${metadata.name}" references approval function "${metadata.needsApprovalStepFnName}" ` +
+ `Dynamic tool "${metadata.name}" references approval function "${metadata.approvalStepFnName}" ` +
"which is not registered — requiring approval by default.",
);
- return () => true;
+ return () => "user-approval";
}
- return (approvalCtx: NeedsApprovalContext) =>
- Boolean(approvalStepFn(metadata.closureVars ?? {}, approvalCtx));
+ return async (approvalCtx: ApprovalContext) =>
+ (await approvalStepFn(metadata.closureVars ?? {}, approvalCtx)) as ApprovalStatus;
}
/**
diff --git a/packages/eve/src/context/dynamic-tool-lifecycle.test.ts b/packages/eve/src/context/dynamic-tool-lifecycle.test.ts
index d25dfb23a..975535583 100644
--- a/packages/eve/src/context/dynamic-tool-lifecycle.test.ts
+++ b/packages/eve/src/context/dynamic-tool-lifecycle.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vitest";
import type { DynamicToolEntry } from "#shared/dynamic-tool-definition.js";
import type { DurableDynamicToolMetadata } from "#context/keys.js";
+import type { ApprovalContext } from "#public/definitions/approval.js";
import { defineTool } from "#public/definitions/tool.js";
vi.mock("#context/build-callback-context.js", () => ({
@@ -444,6 +445,24 @@ function createCtx(): ContextContainer {
return ctx;
}
+function createApprovalContext(input: {
+ readonly toolInput?: Record<string, unknown>;
+ readonly toolName: string;
+}): ApprovalContext {
+ return {
+ approvedTools: new Set(),
+ getSandbox: vi.fn(),
+ getSkill: vi.fn(),
+ session: {
+ auth: { current: null, initiator: null },
+ id: "test-session",
+ turn: { id: "test-turn", sequence: 0 },
+ },
+ toolInput: input.toolInput,
+ toolName: input.toolName,
+ } as ApprovalContext;
+}
+
function makeEvent(type: string): HandleMessageStreamEvent {
return { type, data: {} } as HandleMessageStreamEvent;
}
@@ -853,13 +872,13 @@ describe("framework dynamic tools (no bundler transform)", () => {
expect(tools[0]!.name).toBe("analytics");
});
- it("propagates needsApproval from a step-scoped entry into the harness tool", async () => {
+ it("propagates approval from a step-scoped entry into the harness tool", async () => {
const ctx = createCtx();
- const approvalFn = vi.fn(() => true);
+ const approvalFn = vi.fn(() => "user-approval" as const);
const entry: DynamicToolEntry = {
description: "destructive op",
inputSchema: { type: "object" },
- needsApproval: approvalFn,
+ approval: approvalFn,
execute: async (): Promise<unknown> => ({ ok: true }),
};
const resolver = createResolver("connection", ["step.started"], () => ({ risky: entry }));
@@ -876,25 +895,20 @@ describe("framework dynamic tools (no bundler transform)", () => {
const tools = buildDynamicTools(ctx);
expect(tools).toHaveLength(1);
expect(tools[0]!.name).toBe("risky");
- expect(tools[0]!.needsApproval).toBe(approvalFn);
- expect(
- tools[0]!.needsApproval!({
- approvedTools: new Set(),
- toolInput: undefined,
- toolName: "risky",
- }),
- ).toBe(true);
+ expect(tools[0]!.approval).toBe(approvalFn);
+ const approvalCtx = createApprovalContext({ toolName: "risky" });
+ expect(tools[0]!.approval!(approvalCtx)).toBe("user-approval");
expect(testRegistry.has("eve:framework-dynamic:connection:risky")).toBe(false);
expect(testRegistry.has("eve:dynamic-tool-approval:connection:risky")).toBe(false);
});
- it("replays needsApproval from session-scoped dynamic tools", async () => {
+ it("replays approval from session-scoped dynamic tools", async () => {
const ctx = createCtx();
- const approvalFn = vi.fn(() => true);
+ const approvalFn = vi.fn(async () => "user-approval" as const);
const entry: DynamicToolEntry = {
description: "destructive op",
inputSchema: { type: "object" },
- needsApproval: approvalFn,
+ approval: approvalFn,
execute: async (): Promise<unknown> => ({ ok: true }),
};
const resolver = createResolver("session_guard", ["session.started"], () => ({
@@ -913,18 +927,12 @@ describe("framework dynamic tools (no bundler transform)", () => {
const tools = buildDynamicTools(ctx);
expect(tools).toHaveLength(1);
expect(tools[0]!.name).toBe("guarded");
- expect(
- tools[0]!.needsApproval!({
- approvedTools: new Set(),
- toolInput: { draftId: "draft_123" },
- toolName: "guarded",
- }),
- ).toBe(true);
- expect(approvalFn).toHaveBeenCalledExactlyOnceWith({
- approvedTools: new Set(),
+ const approvalCtx = createApprovalContext({
toolInput: { draftId: "draft_123" },
toolName: "guarded",
});
+ await expect(tools[0]!.approval!(approvalCtx)).resolves.toBe("user-approval");
+ expect(approvalFn).toHaveBeenCalledExactlyOnceWith(approvalCtx);
});
it("propagates outputSchema from dynamic entries into harness tools and metadata", async () => {
@@ -960,7 +968,7 @@ describe("framework dynamic tools (no bundler transform)", () => {
expect((tools[0]!.outputSchema as { jsonSchema: unknown }).jsonSchema).toEqual(outputSchema);
});
- it("leaves needsApproval undefined when a step-scoped entry omits it", async () => {
+ it("leaves approval undefined when a step-scoped entry omits it", async () => {
const ctx = createCtx();
const resolver = createResolver("connection", ["step.started"], () => ({
safe: createFrameworkTool("read-only op"),
@@ -975,7 +983,7 @@ describe("framework dynamic tools (no bundler transform)", () => {
const tools = buildDynamicTools(ctx);
expect(tools).toHaveLength(1);
- expect(tools[0]!.needsApproval).toBeUndefined();
+ expect(tools[0]!.approval).toBeUndefined();
});
it("re-dispatch updates the registered step function", async () => {
diff --git a/packages/eve/src/context/dynamic-tool-lifecycle.ts b/packages/eve/src/context/dynamic-tool-lifecycle.ts
index 134b35e19..372340ba3 100644
--- a/packages/eve/src/context/dynamic-tool-lifecycle.ts
+++ b/packages/eve/src/context/dynamic-tool-lifecycle.ts
@@ -1,7 +1,7 @@
import { jsonSchema, zodSchema, type FlexibleSchema, type ModelMessage } from "ai";
import type { HarnessToolDefinition } from "#harness/execute-tool.js";
-import type { NeedsApprovalContext } from "#public/definitions/tool.js";
+import type { ApprovalContext } from "#public/definitions/approval.js";
import type { DynamicToolEntry } from "#shared/dynamic-tool-definition.js";
import type { HandleMessageStreamEvent } from "#protocol/message.js";
import {
@@ -36,7 +36,7 @@ function toHarnessToolDefinition(name: string, entry: DynamicToolEntry): Harness
entry.execute(input as Record<string, unknown>, buildCallbackContext()),
inputSchema: convertInputSchema(entry.inputSchema),
name,
- needsApproval: entry.needsApproval,
+ approval: entry.approval,
outputSchema: convertOptionalOutputSchema(entry.outputSchema),
...(entry.toModelOutput !== undefined
? { toModelOutput: entry.toModelOutput as (output: unknown) => unknown }
@@ -291,14 +291,12 @@ async function resolveToolsFromEvent(
serializedClosureVars = {};
}
- let needsApprovalStepFnName: string | undefined;
- if (entry.needsApproval !== undefined) {
- needsApprovalStepFnName = `eve:dynamic-tool-approval:${resolver.slug}:${entryKey}`;
- const originalNeedsApproval = entry.needsApproval.bind(entry);
- registerStepFunction(
- needsApprovalStepFnName,
- (_closureVars: unknown, approvalCtx: unknown) =>
- originalNeedsApproval(approvalCtx as NeedsApprovalContext),
+ let approvalStepFnName: string | undefined;
+ if (entry.approval !== undefined) {
+ approvalStepFnName = `eve:dynamic-tool-approval:${resolver.slug}:${entryKey}`;
+ const originalApproval = entry.approval.bind(entry);
+ registerStepFunction(approvalStepFnName, (_closureVars: unknown, approvalCtx: unknown) =>
+ originalApproval(approvalCtx as ApprovalContext),
);
}
@@ -313,7 +311,7 @@ async function resolveToolsFromEvent(
resolverSlug: resolver.slug,
entryKey,
executeStepFnName,
- needsApprovalStepFnName,
+ approvalStepFnName,
closureVars: serializedClosureVars,
});
}
diff --git a/packages/eve/src/context/keys.ts b/packages/eve/src/context/keys.ts
index 0badc4201..8e623cbdc 100644
--- a/packages/eve/src/context/keys.ts
+++ b/packages/eve/src/context/keys.ts
@@ -98,7 +98,7 @@ export interface DurableDynamicToolMetadata {
readonly resolverSlug: string;
readonly entryKey: string;
readonly executeStepFnName?: string;
- readonly needsApprovalStepFnName?: string;
+ readonly approvalStepFnName?: string;
readonly closureVars?: Record<string, unknown>;
}
diff --git a/packages/eve/src/execution/node-step.ts b/packages/eve/src/execution/node-step.ts
index 79f17af9b..e01404122 100644
--- a/packages/eve/src/execution/node-step.ts
+++ b/packages/eve/src/execution/node-step.ts
@@ -221,7 +221,7 @@ function resolveHarnessToolDefinition(input: {
}),
inputSchema: def.inputStandardSchema ?? jsonSchema(def.inputSchema ?? {}),
name: def.name,
- needsApproval: def.needsApproval,
+ approval: def.approval,
outputSchema: def.outputStandardSchema ?? maybeJsonSchema(def.outputSchema),
toModelOutput: def.toModelOutput,
};
diff --git a/packages/eve/src/harness/execute-tool.ts b/packages/eve/src/harness/execute-tool.ts
index b0cb87ff6..2712fabe2 100644
--- a/packages/eve/src/harness/execute-tool.ts
+++ b/packages/eve/src/harness/execute-tool.ts
@@ -1,6 +1,6 @@
import type { FlexibleSchema } from "ai";
-import type { NeedsApprovalContext } from "#public/definitions/tool.js";
+import type { Approval } from "#public/definitions/approval.js";
/**
* Runtime-owned action metadata attached to one harness-visible tool.
@@ -24,7 +24,7 @@ export interface HarnessToolDefinition {
readonly execute?: (input: any) => any;
readonly inputSchema: FlexibleSchema;
readonly name: string;
- readonly needsApproval?: (ctx: NeedsApprovalContext) => boolean;
+ readonly approval?: Approval;
readonly outputSchema?: FlexibleSchema;
readonly runtimeAction?: HarnessRuntimeActionDefinition;
readonly toModelOutput?: (output: unknown) => unknown;
diff --git a/packages/eve/src/harness/input-extraction.integration.test.ts b/packages/eve/src/harness/input-extraction.integration.test.ts
new file mode 100644
index 000000000..dd8d45910
--- /dev/null
+++ b/packages/eve/src/harness/input-extraction.integration.test.ts
@@ -0,0 +1,100 @@
+import { generateText, jsonSchema, tool, type ToolApprovalStatus, type ToolSet } from "ai";
+import { MockLanguageModelV4 } from "ai/test";
+import { describe, expect, it, vi } from "vitest";
+
+import { extractToolApprovalInputRequests } from "#harness/input-extraction.js";
+
+const usage = {
+ inputTokens: {
+ cacheRead: undefined,
+ cacheWrite: undefined,
+ noCache: 1,
+ total: 1,
+ },
+ outputTokens: {
+ reasoning: undefined,
+ text: 1,
+ total: 1,
+ },
+};
+
+async function generateToolCall(status: ToolApprovalStatus): Promise<{
+ readonly execute: ReturnType<typeof vi.fn>;
+ readonly step: Awaited<ReturnType<typeof generateText<ToolSet>>>["steps"][number];
+}> {
+ const execute = vi.fn(async () => ({ ok: true }));
+ const model = new MockLanguageModelV4({
+ doGenerate: {
+ content: [
+ {
+ input: JSON.stringify({ command: "rm -rf /tmp/demo" }),
+ toolCallId: "call-1",
+ toolName: "bash",
+ type: "tool-call",
+ },
+ ],
+ finishReason: { raw: undefined, unified: "tool-calls" },
+ usage,
+ warnings: [],
+ },
+ });
+
+ const result = await generateText({
+ model,
+ prompt: "Delete the temp directory.",
+ toolApproval: () => status,
+ tools: {
+ bash: tool({
+ description: "Run shell commands.",
+ execute,
+ inputSchema: jsonSchema({ type: "object" }),
+ }),
+ },
+ });
+
+ return { execute, step: result.steps[0]! };
+}
+
+describe("AI SDK 7 automatic approval extraction", () => {
+ it("keeps automatic approval records out of the human input queue", async () => {
+ const { execute, step } = await generateToolCall("approved");
+
+ expect(execute).toHaveBeenCalledExactlyOnceWith(
+ { command: "rm -rf /tmp/demo" },
+ expect.any(Object),
+ );
+ expect(step.content).toContainEqual(
+ expect.objectContaining({ isAutomatic: true, type: "tool-approval-request" }),
+ );
+ expect(extractToolApprovalInputRequests({ content: step.content })).toEqual([]);
+ });
+
+ it("keeps automatic denial records out of the human input queue", async () => {
+ const { execute, step } = await generateToolCall({
+ reason: "Blocked by policy.",
+ type: "denied",
+ });
+
+ expect(execute).not.toHaveBeenCalled();
+ expect(step.content).toContainEqual(
+ expect.objectContaining({
+ approved: false,
+ reason: "Blocked by policy.",
+ type: "tool-approval-response",
+ }),
+ );
+ expect(extractToolApprovalInputRequests({ content: step.content })).toEqual([]);
+ });
+
+ it("continues to queue unresolved user approval requests", async () => {
+ const { execute, step } = await generateToolCall("user-approval");
+
+ expect(execute).not.toHaveBeenCalled();
+ expect(extractToolApprovalInputRequests({ content: step.content })).toEqual([
+ expect.objectContaining({
+ action: expect.objectContaining({ callId: "call-1", toolName: "bash" }),
+ requestId: expect.any(String),
+ }),
+ ]);
+ });
+});
diff --git a/packages/eve/src/harness/input-extraction.test.ts b/packages/eve/src/harness/input-extraction.test.ts
index a7721f366..21d092840 100644
--- a/packages/eve/src/harness/input-extraction.test.ts
+++ b/packages/eve/src/harness/input-extraction.test.ts
@@ -164,6 +164,26 @@ describe("extractToolApprovalInputRequests", () => {
]);
});
+ it("skips automatic approval decisions", () => {
+ const result = extractToolApprovalInputRequests({
+ content: [
+ {
+ approvalId: "approval-1",
+ isAutomatic: true,
+ toolCall: {
+ input: { command: "rm -rf /tmp" },
+ toolCallId: "call-1",
+ toolName: "bash",
+ type: "tool-call",
+ },
+ type: "tool-approval-request",
+ },
+ ],
+ });
+
+ expect(result).toEqual([]);
+ });
+
it("skips approval requests without matching tool-call data", () => {
const result = extractToolApprovalInputRequests({
content: [
diff --git a/packages/eve/src/harness/input-extraction.ts b/packages/eve/src/harness/input-extraction.ts
index a2cf4db6c..a9dcf1a42 100644
--- a/packages/eve/src/harness/input-extraction.ts
+++ b/packages/eve/src/harness/input-extraction.ts
@@ -83,6 +83,11 @@ export function extractToolApprovalInputRequests(input: {
readonly toolCall?: TypedToolCall<ToolSet>;
readonly toolCallId?: string;
};
+ // AI SDK records automatic decisions as request/response pairs for history;
+ // only unresolved requests should become eve input.
+ if (approvalRequest.isAutomatic === true) {
+ continue;
+ }
const toolCall =
approvalRequest.toolCall ??
(approvalRequest.toolCallId === undefined
diff --git a/packages/eve/src/harness/input-requests.test.ts b/packages/eve/src/harness/input-requests.test.ts
index d1716a6f9..e364c8b97 100644
--- a/packages/eve/src/harness/input-requests.test.ts
+++ b/packages/eve/src/harness/input-requests.test.ts
@@ -1,6 +1,8 @@
import { jsonSchema, type ModelMessage } from "ai";
import { describe, expect, it } from "vitest";
+import { ContextContainer, contextStorage } from "#context/container.js";
+import { SessionKey } from "#context/keys.js";
import { once } from "#public/tools/approval/approval-helpers.js";
import type { InputRequest } from "#runtime/input/types.js";
import type { HarnessToolDefinition } from "#harness/execute-tool.js";
@@ -13,11 +15,9 @@ import {
resolvePendingInput,
setPendingInputBatch,
} from "#harness/input-requests.js";
-import { buildToolSet } from "#harness/tools.js";
+import { buildToolApproval, buildToolSet } from "#harness/tools.js";
import type { HarnessSession, HarnessToolMap } from "#harness/types.js";
-type NeedsApprovalFn = (input: unknown, context: unknown) => Promise<boolean> | boolean;
-
function createHarnessSession(): HarnessSession {
return {
agent: {
@@ -656,8 +656,8 @@ describe("resolvePendingInput", () => {
// A tool requiring both approval and auth is approved first, then its
// execute parks for sign-in. On resume the step re-runs and the toolset
// is rebuilt from the persisted approvedTools. The recorded approval must
- // survive on session.state across the park, so needsApproval returns
- // false and the user is never asked to approve a second time.
+ // survive on session.state across the park, so approval returns
+ // "not-applicable" and the user is never asked to approve a second time.
// See research/per-tool-auth-known-issues.md, issue 3.
const session = setPendingInputBatch({
requests: [
@@ -718,7 +718,7 @@ describe("resolvePendingInput", () => {
execute: async () => ({ ok: true }),
inputSchema: jsonSchema({ type: "object" }),
name: "linear_whoami",
- needsApproval: once(),
+ approval: once(),
},
],
]);
@@ -727,9 +727,30 @@ describe("resolvePendingInput", () => {
approvedTools: getApprovedTools(result.session),
tools,
});
- const needsApproval = (rebuilt.linear_whoami as { needsApproval?: NeedsApprovalFn })
- .needsApproval;
+ const approval = buildToolApproval(rebuilt);
+ if (typeof approval !== "function") throw new TypeError("Expected generic approval function.");
+
+ const ctx = new ContextContainer();
+ ctx.set(SessionKey, {
+ auth: { current: null, initiator: null },
+ sessionId: "sess-test",
+ turn: { id: "turn-test", sequence: 0 },
+ });
- return expect(needsApproval?.({}, {})).resolves.toBe(false);
+ return expect(
+ contextStorage.run(ctx, () =>
+ approval({
+ messages: [],
+ runtimeContext: {},
+ toolCall: {
+ input: {},
+ toolCallId: "call-1",
+ toolName: "linear_whoami",
+ } as never,
+ tools: rebuilt,
+ toolsContext: {} as never,
+ }),
+ ),
+ ).resolves.toBe("not-applicable");
});
});
diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.ts
index c924cc377..f4d13c237 100644
--- a/packages/eve/src/harness/tool-loop.test.ts
+++ b/packages/eve/src/harness/tool-loop.test.ts
@@ -10,6 +10,7 @@ import {
LiveStepToolsKey,
ParentSessionKey,
SandboxKey,
+ SessionKey,
SessionDynamicInstructionsKey,
} from "#context/keys.js";
import { SCHEDULE_APP_AUTH } from "#channel/schedule-auth.js";
@@ -617,15 +618,28 @@ describe("createToolLoopHarness", () => {
toolResults: [],
});
- const needsApproval = vi.fn(() => true);
+ const approval = vi.fn(() => "user-approval" as const);
const ctx = new ContextContainer();
+ ctx.set(SessionKey, {
+ auth: {
+ current: {
+ attributes: { tenant: "tenant_test" },
+ authenticator: "jwt",
+ principalId: "caller_test",
+ principalType: "user",
+ },
+ initiator: null,
+ },
+ sessionId: "test-session",
+ turn: { id: "turn-test", sequence: 0 },
+ });
ctx.setVirtualContext(LiveStepToolsKey, [
{
description: "Get TfL line status.",
execute: vi.fn().mockResolvedValue({ ok: true }),
inputSchema: jsonSchema({ type: "object" }),
name: "tfl__getLineStatus",
- needsApproval,
+ approval,
},
]);
@@ -634,17 +648,38 @@ describe("createToolLoopHarness", () => {
await contextStorage.run(ctx, () => runStep(createTestSession(), { message: "Hi" }));
const agentCall = vi.mocked(ToolLoopAgent).mock.calls[0]?.[0] as
- | { tools: Record<string, { needsApproval?: (toolInput: unknown) => Promise<boolean> }> }
+ | {
+ toolApproval?: (options: {
+ toolCall: { input: unknown; toolCallId: string; toolName: string };
+ }) => Promise<unknown>;
+ }
| undefined;
expect(agentCall).toBeDefined();
- const dynamicTool = agentCall!.tools.tfl__getLineStatus!;
-
- await expect(dynamicTool.needsApproval?.({ line: "victoria" })).resolves.toBe(true);
- expect(needsApproval).toHaveBeenCalledExactlyOnceWith({
- approvedTools: new Set(),
- toolInput: { line: "victoria" },
- toolName: "tfl__getLineStatus",
- });
+ await expect(
+ contextStorage.run(ctx, () =>
+ agentCall!.toolApproval?.({
+ toolCall: {
+ input: { line: "victoria" },
+ toolCallId: "call_1",
+ toolName: "tfl__getLineStatus",
+ },
+ }),
+ ),
+ ).resolves.toBe("user-approval");
+ expect(approval).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({
+ approvedTools: new Set(),
+ session: expect.objectContaining({
+ auth: expect.objectContaining({
+ current: expect.objectContaining({ principalId: "caller_test" }),
+ }),
+ id: "test-session",
+ turn: { id: "turn-test", sequence: 0 },
+ }),
+ toolInput: { line: "victoria" },
+ toolName: "tfl__getLineStatus",
+ }),
+ );
});
it("preserves a user-authored web_search tool instead of replacing it with the provider tool", async () => {
@@ -4746,6 +4781,117 @@ describe("createToolLoopHarness", () => {
});
});
+ it.each([
+ { approved: true, label: "approval", reason: undefined },
+ { approved: false, label: "denial", reason: "Blocked by policy." },
+ ])("does not park on automatic $label records", async ({ approved, reason }) => {
+ const toolCall = {
+ input: { command: "rm -rf /tmp/demo" },
+ toolCallId: "call-1",
+ toolName: "bash",
+ type: "tool-call" as const,
+ };
+ const approvalRequest = {
+ approvalId: "approval-1",
+ isAutomatic: true,
+ toolCall,
+ type: "tool-approval-request" as const,
+ };
+ const approvalResponse = {
+ approvalId: "approval-1",
+ approved,
+ reason,
+ toolCall,
+ type: "tool-approval-response" as const,
+ };
+ const toolResult = {
+ input: toolCall.input,
+ output: { ok: true },
+ toolCallId: toolCall.toolCallId,
+ toolName: toolCall.toolName,
+ type: "tool-result" as const,
+ };
+ const responseMessages = [
+ {
+ content: [
+ toolCall,
+ {
+ approvalId: approvalRequest.approvalId,
+ isAutomatic: true,
+ toolCallId: toolCall.toolCallId,
+ type: "tool-approval-request" as const,
+ },
+ ],
+ role: "assistant" as const,
+ },
+ {
+ content: [
+ {
+ approvalId: approvalResponse.approvalId,
+ approved,
+ reason,
+ type: "tool-approval-response" as const,
+ },
+ {
+ output: approved
+ ? { type: "json" as const, value: toolResult.output }
+ : { type: "execution-denied" as const, reason },
+ toolCallId: toolCall.toolCallId,
+ toolName: toolCall.toolName,
+ type: "tool-result" as const,
+ },
+ ],
+ role: "tool" as const,
+ },
+ ];
+
+ setupMockAgent({
+ content: [toolCall, approvalRequest, approvalResponse, ...(approved ? [toolResult] : [])],
+ finishReason: "tool-calls",
+ response: { messages: responseMessages },
+ text: "",
+ toolCalls: [toolCall],
+ toolResults: approved ? [toolResult] : [],
+ });
+
+ const { emit, events } = createEventCollector();
+ const runStep = createToolLoopHarness(
+ createTestConfig("conversation", emit, {
+ tools: new Map([
+ [
+ "bash",
+ {
+ description: "Run shell commands",
+ execute: vi.fn().mockResolvedValue({ ok: true }),
+ inputSchema: jsonSchema({ type: "object" }),
+ name: "bash",
+ },
+ ],
+ ]),
+ }),
+ );
+ const session = createTestSession({
+ agent: {
+ modelReference: { id: "test-model" },
+ system: "You are a test assistant.",
+ tools: [
+ { description: "Run shell commands", name: "bash", inputSchema: { type: "object" } },
+ ],
+ },
+ });
+
+ const result = await runStep(session, { message: "Delete the temp directory." });
+
+ expect(typeof result.next).toBe("function");
+ expect(result.session.history).toEqual([
+ { content: "Delete the temp directory.", role: "user" },
+ ...responseMessages,
+ ]);
+ expect(events.filter((event) => event.type === "input.requested")).toEqual([]);
+ expect(events.filter((event) => event.type === "actions.requested")).toHaveLength(1);
+ expect(events.filter((event) => event.type === "action.result")).toHaveLength(1);
+ });
+
it("continues with a follow-up user message after resolving an ignored tool approval", async () => {
const generateCalls: unknown[] = [];
const agentResults = [
diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.ts
index bc350c98b..1c0b8798d 100644
--- a/packages/eve/src/harness/tool-loop.ts
+++ b/packages/eve/src/harness/tool-loop.ts
@@ -135,7 +135,11 @@ import {
type HarnessStepResult,
isInvalidToolCall,
} from "#harness/step-hooks.js";
-import { buildToolSetFromDefinitions, buildToolSetWithProviderTools } from "#harness/tools.js";
+import {
+ buildToolApproval,
+ buildToolSetFromDefinitions,
+ buildToolSetWithProviderTools,
+} from "#harness/tools.js";
import {
continueWorkflowSandboxInterrupt,
getWorkflowSandboxInterrupt,
@@ -685,6 +689,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
runtimeContext: telemetryRuntimeContext,
stopWhen: isStepCount(1),
telemetry: enrichTelemetry(telemetryConfig, agentName, telemetryRuntimeContext),
+ toolApproval: buildToolApproval(modelTools),
tools: effectiveTools,
};
const agent = new ToolLoopAgent(agentSettings);
diff --git a/packages/eve/src/harness/tools.test.ts b/packages/eve/src/harness/tools.test.ts
index 061e09c69..2c8b50a1e 100644
--- a/packages/eve/src/harness/tools.test.ts
+++ b/packages/eve/src/harness/tools.test.ts
@@ -1,6 +1,8 @@
import { type JSONSchema7, jsonSchema } from "ai";
import { describe, expect, it } from "vitest";
+import { ContextContainer, contextStorage } from "#context/container.js";
+import { SessionKey, type Session } from "#context/keys.js";
import { always, never, once } from "#public/tools/approval/approval-helpers.js";
import type { RuntimeModelReference } from "#runtime/agent/bootstrap.js";
import {
@@ -11,7 +13,7 @@ import {
} from "#runtime/framework-tools/web-search.js";
import type { JsonObject } from "#shared/json.js";
import type { HarnessToolDefinition } from "#harness/execute-tool.js";
-import { buildToolSet, buildToolSetWithProviderTools } from "#harness/tools.js";
+import { buildToolApproval, buildToolSet, buildToolSetWithProviderTools } from "#harness/tools.js";
import type { HarnessToolMap } from "#harness/types.js";
function getJsonSchema(tool: unknown): unknown {
@@ -22,6 +24,31 @@ function getOutputJsonSchema(tool: unknown): unknown {
return (tool as { outputSchema: { jsonSchema: unknown } }).outputSchema.jsonSchema;
}
+async function resolveApproval(
+ tools: ReturnType<typeof buildToolSet>,
+ toolName: string,
+ input: unknown,
+ session: Session = {
+ auth: { current: null, initiator: null },
+ sessionId: "session-1",
+ turn: { id: "turn-1", sequence: 0 },
+ },
+): Promise<unknown> {
+ const approval = buildToolApproval(tools);
+ if (typeof approval !== "function") throw new TypeError("Expected generic approval function.");
+ const ctx = new ContextContainer();
+ ctx.set(SessionKey, session);
+ return contextStorage.run(ctx, () =>
+ approval({
+ messages: [],
+ runtimeContext: {},
+ toolCall: { input, toolCallId: "call_1", toolName } as never,
+ tools,
+ toolsContext: {} as never,
+ }),
+ );
+}
+
async function executeSdkTool(input: {
readonly tool: unknown;
readonly toolCallId?: string;
@@ -277,7 +304,7 @@ describe("buildToolSet", () => {
expect(withCapability.ask_question).toBeDefined();
});
- it("defaults to no approval when no needsApproval function is set", async () => {
+ it("defaults to no approval when no approval function is set", async () => {
const tools: HarnessToolMap = new Map<string, HarnessToolDefinition>([
[
"dangerous_tool",
@@ -294,14 +321,7 @@ describe("buildToolSet", () => {
tools,
});
- const needsApproval = (
- result.dangerous_tool as {
- needsApproval?: (input: unknown, context: unknown) => Promise<boolean> | boolean;
- }
- ).needsApproval;
-
- expect(needsApproval).toBeTypeOf("function");
- await expect(needsApproval?.({}, {})).resolves.toBe(false);
+ await expect(resolveApproval(result, "dangerous_tool", {})).resolves.toBeUndefined();
});
it("forwards toModelOutput to the SDK tool", () => {
@@ -499,8 +519,56 @@ describe("buildToolSet", () => {
});
});
- describe("tool-level needsApproval override", () => {
- type NeedsApprovalFn = (input: unknown, context: unknown) => Promise<boolean> | boolean;
+ describe("tool-level approval override", () => {
+ it("normalizes boolean approval results", async () => {
+ const tools: HarnessToolMap = new Map<string, HarnessToolDefinition>([
+ [
+ "dangerous",
+ {
+ approval: () => true,
+ description: "Perform a dangerous action.",
+ execute: async () => "ok",
+ inputSchema: jsonSchema({}),
+ name: "dangerous",
+ },
+ ],
+ [
+ "safe",
+ {
+ approval: async () => false,
+ description: "Perform a safe action.",
+ execute: async () => "ok",
+ inputSchema: jsonSchema({}),
+ name: "safe",
+ },
+ ],
+ ]);
+
+ const result = buildToolSet({ tools });
+ await expect(resolveApproval(result, "dangerous", {})).resolves.toBe("user-approval");
+ await expect(resolveApproval(result, "safe", {})).resolves.toBe("not-applicable");
+ });
+
+ it("preserves async AI SDK 7 approval statuses", async () => {
+ const tools: HarnessToolMap = new Map<string, HarnessToolDefinition>([
+ [
+ "delete_account",
+ {
+ approval: async () => ({ type: "denied", reason: "Account is protected." }),
+ description: "Delete an account.",
+ execute: async () => "ok",
+ inputSchema: jsonSchema({}),
+ name: "delete_account",
+ },
+ ],
+ ]);
+
+ const result = buildToolSet({ tools });
+ await expect(resolveApproval(result, "delete_account", {})).resolves.toEqual({
+ type: "denied",
+ reason: "Account is protected.",
+ });
+ });
it("always() requires approval", async () => {
const tools: HarnessToolMap = new Map<string, HarnessToolDefinition>([
@@ -511,7 +579,7 @@ describe("buildToolSet", () => {
execute: async () => "ok",
inputSchema: jsonSchema({}),
name: "bash",
- needsApproval: always(),
+ approval: always(),
},
],
]);
@@ -519,8 +587,7 @@ describe("buildToolSet", () => {
const result = buildToolSet({
tools,
});
- const needsApproval = (result.bash as { needsApproval?: NeedsApprovalFn }).needsApproval;
- await expect(needsApproval?.({}, {})).resolves.toBe(true);
+ await expect(resolveApproval(result, "bash", {})).resolves.toBe("user-approval");
});
it("never() skips approval", async () => {
@@ -532,7 +599,7 @@ describe("buildToolSet", () => {
execute: async () => "ok",
inputSchema: jsonSchema({}),
name: "bash",
- needsApproval: never(),
+ approval: never(),
},
],
]);
@@ -540,8 +607,7 @@ describe("buildToolSet", () => {
const result = buildToolSet({
tools,
});
- const needsApproval = (result.bash as { needsApproval?: NeedsApprovalFn }).needsApproval;
- await expect(needsApproval?.({}, {})).resolves.toBe(false);
+ await expect(resolveApproval(result, "bash", {})).resolves.toBe("not-applicable");
});
it("once() requires approval when tool not yet approved", async () => {
@@ -553,7 +619,7 @@ describe("buildToolSet", () => {
execute: async () => "ok",
inputSchema: jsonSchema({}),
name: "bash",
- needsApproval: once(),
+ approval: once(),
},
],
]);
@@ -561,8 +627,7 @@ describe("buildToolSet", () => {
const result = buildToolSet({
tools,
});
- const needsApproval = (result.bash as { needsApproval?: NeedsApprovalFn }).needsApproval;
- await expect(needsApproval?.({}, {})).resolves.toBe(true);
+ await expect(resolveApproval(result, "bash", {})).resolves.toBe("user-approval");
});
it("once() skips approval when tool already approved", async () => {
@@ -574,7 +639,7 @@ describe("buildToolSet", () => {
execute: async () => "ok",
inputSchema: jsonSchema({}),
name: "bash",
- needsApproval: once(),
+ approval: once(),
},
],
]);
@@ -583,11 +648,10 @@ describe("buildToolSet", () => {
approvedTools: new Set(["bash"]),
tools,
});
- const needsApproval = (result.bash as { needsApproval?: NeedsApprovalFn }).needsApproval;
- await expect(needsApproval?.({}, {})).resolves.toBe(false);
+ await expect(resolveApproval(result, "bash", {})).resolves.toBe("not-applicable");
});
- it("tool without needsApproval defaults to false when another tool has an override", async () => {
+ it("tool without approval defaults to false when another tool has an override", async () => {
const tools: HarnessToolMap = new Map<string, HarnessToolDefinition>([
[
"bash",
@@ -596,7 +660,7 @@ describe("buildToolSet", () => {
execute: async () => "ok",
inputSchema: jsonSchema({}),
name: "bash",
- needsApproval: always(),
+ approval: always(),
},
],
[
@@ -613,14 +677,11 @@ describe("buildToolSet", () => {
const result = buildToolSet({
tools,
});
- const bashNeedsApproval = (result.bash as { needsApproval?: NeedsApprovalFn }).needsApproval;
- const writeNeedsApproval = (result.write_file as { needsApproval?: NeedsApprovalFn })
- .needsApproval;
- await expect(bashNeedsApproval?.({}, {})).resolves.toBe(true);
- await expect(writeNeedsApproval?.({}, {})).resolves.toBe(false);
+ await expect(resolveApproval(result, "bash", {})).resolves.toBe("user-approval");
+ await expect(resolveApproval(result, "write_file", {})).resolves.toBeUndefined();
});
- it("passes toolInput from the AI SDK into needsApproval", async () => {
+ it("passes toolInput from the AI SDK into approval", async () => {
let capturedInput: unknown;
const tools: HarnessToolMap = new Map<string, HarnessToolDefinition>([
[
@@ -630,24 +691,81 @@ describe("buildToolSet", () => {
execute: async () => "ok",
inputSchema: jsonSchema({}),
name: "vercel__list_projects",
- needsApproval: (ctx) => {
+ approval: (ctx) => {
capturedInput = ctx.toolInput;
- return true;
+ return "user-approval";
},
},
],
]);
const result = buildToolSet({ tools });
- const needsApproval = (result.vercel__list_projects as { needsApproval?: NeedsApprovalFn })
- .needsApproval;
-
const toolInput = { teamId: "team_abc", limit: 20 };
- await needsApproval?.(toolInput, {});
+ await resolveApproval(result, "vercel__list_projects", toolInput);
expect(capturedInput).toEqual(toolInput);
});
+ it("passes the active caller and session context into approval", async () => {
+ let capturedCtx: Parameters<NonNullable<HarnessToolDefinition["approval"]>>[0] | undefined;
+ const tools: HarnessToolMap = new Map<string, HarnessToolDefinition>([
+ [
+ "delete_project",
+ {
+ approval: (ctx) => {
+ capturedCtx = ctx;
+ return ctx.session.auth.current?.attributes.tenant === "tenant_abc"
+ ? "user-approval"
+ : "denied";
+ },
+ description: "Delete a project.",
+ execute: async () => "ok",
+ inputSchema: jsonSchema({}),
+ name: "delete_project",
+ },
+ ],
+ ]);
+ const session: Session = {
+ auth: {
+ current: {
+ attributes: { tenant: "tenant_abc" },
+ authenticator: "jwt",
+ principalId: "user_current",
+ principalType: "user",
+ },
+ initiator: {
+ attributes: { tenant: "tenant_abc" },
+ authenticator: "jwt",
+ principalId: "user_initiator",
+ principalType: "user",
+ },
+ },
+ parent: {
+ callId: "call_parent",
+ rootSessionId: "session_root",
+ sessionId: "session_parent",
+ turn: { id: "turn_parent", sequence: 1 },
+ },
+ sessionId: "session_current",
+ turn: { id: "turn_current", sequence: 2 },
+ };
+
+ const result = buildToolSet({ tools });
+ await expect(resolveApproval(result, "delete_project", {}, session)).resolves.toBe(
+ "user-approval",
+ );
+
+ expect(capturedCtx?.session).toEqual({
+ auth: session.auth,
+ id: "session_current",
+ parent: session.parent,
+ turn: session.turn,
+ });
+ expect(capturedCtx?.session.auth.current?.principalId).toBe("user_current");
+ expect(capturedCtx?.getSandbox).toBeTypeOf("function");
+ expect(capturedCtx?.getSkill).toBeTypeOf("function");
+ });
+
it("input-aware approval skips when compound key is in approvedTools", async () => {
const tools: HarnessToolMap = new Map<string, HarnessToolDefinition>([
[
@@ -657,11 +775,11 @@ describe("buildToolSet", () => {
execute: async () => "ok",
inputSchema: jsonSchema({}),
name: "vercel__list_projects",
- needsApproval: ({ approvedTools, toolName, toolInput }) => {
- if (approvedTools.has(toolName)) return false;
+ approval: ({ approvedTools, toolName, toolInput }) => {
+ if (approvedTools.has(toolName)) return "not-applicable";
const team = (toolInput as { teamId?: string } | undefined)?.teamId;
- if (team === undefined) return true;
- return !approvedTools.has(`${toolName}:${team}`);
+ if (team === undefined) return "user-approval";
+ return approvedTools.has(`${toolName}:${team}`) ? "not-applicable" : "user-approval";
},
},
],
@@ -671,13 +789,19 @@ describe("buildToolSet", () => {
approvedTools: new Set(["vercel__list_projects:team_abc"]),
tools,
});
- const needsApproval = (
- withCompoundKey.vercel__list_projects as { needsApproval?: NeedsApprovalFn }
- ).needsApproval;
-
- await expect(needsApproval?.({ teamId: "team_abc", limit: 10 }, {})).resolves.toBe(false);
-
- await expect(needsApproval?.({ teamId: "team_xyz", limit: 10 }, {})).resolves.toBe(true);
+ await expect(
+ resolveApproval(withCompoundKey, "vercel__list_projects", {
+ teamId: "team_abc",
+ limit: 10,
+ }),
+ ).resolves.toBe("not-applicable");
+
+ await expect(
+ resolveApproval(withCompoundKey, "vercel__list_projects", {
+ teamId: "team_xyz",
+ limit: 10,
+ }),
+ ).resolves.toBe("user-approval");
});
});
});
diff --git a/packages/eve/src/harness/tools.ts b/packages/eve/src/harness/tools.ts
index 49bfd49fd..722510c1b 100644
--- a/packages/eve/src/harness/tools.ts
+++ b/packages/eve/src/harness/tools.ts
@@ -1,4 +1,10 @@
-import { type JSONValue, type ToolSet, tool } from "ai";
+import {
+ type JSONValue,
+ type ToolApprovalConfiguration,
+ type ToolApprovalStatus,
+ type ToolSet,
+ tool,
+} from "ai";
import type { SessionCapabilities } from "#channel/types.js";
import type { RuntimeModelReference } from "#runtime/agent/bootstrap.js";
@@ -7,8 +13,10 @@ import { WEB_SEARCH_TOOL_DEFINITION } from "#runtime/framework-tools/web-search.
import { isObject } from "#shared/guards.js";
import { parseJsonValue, type JsonValue } from "#shared/json.js";
import type { HarnessToolDefinition } from "#harness/execute-tool.js";
+import type { ApprovalStatus } from "#public/definitions/approval.js";
import { resolveWebSearchBackend, resolveWebSearchProviderTool } from "#harness/provider-tools.js";
import type { HarnessToolMap } from "#harness/types.js";
+import { buildCallbackContext } from "#context/build-callback-context.js";
import { loadContext } from "#context/container.js";
import {
authorizationPendingModelText,
@@ -23,6 +31,10 @@ type ToolModelOutputValue =
| { readonly type: "json"; readonly value: JSONValue }
| { readonly type: "text"; readonly value: string };
+type NativeApprovalStatus = Exclude<ApprovalStatus, boolean>;
+
+const toolApprovals = new WeakMap<object, (toolInput: unknown) => Promise<NativeApprovalStatus>>();
+
/**
* Builds an AI SDK `ToolSet` from unified harness tool definitions.
*
@@ -59,11 +71,11 @@ export function buildToolSet(input: {
}
const authorToModelOutput = definition.toModelOutput;
- tools[definition.name] = tool({
+ const approval = buildApprovalFn(definition, input);
+ const aiTool = tool({
description: definition.description,
execute: wrapToolExecute(definition),
inputSchema: definition.inputSchema,
- needsApproval: buildNeedsApprovalFn(definition, input),
outputSchema: definition.outputSchema,
...(definition.execute !== undefined
? {
@@ -114,6 +126,10 @@ export function buildToolSet(input: {
}
: {}),
});
+ tools[definition.name] = aiTool;
+ if (definition.approval !== undefined) {
+ toolApprovals.set(aiTool, approval);
+ }
}
return tools as ToolSet;
@@ -282,19 +298,34 @@ export async function buildToolSetWithProviderTools(input: {
return tools;
}
-function buildNeedsApprovalFn(
+function buildApprovalFn(
definition: HarnessToolDefinition,
input: { readonly approvedTools?: ReadonlySet<string> },
-): (toolInput: unknown) => Promise<boolean> {
+): (toolInput: unknown) => Promise<NativeApprovalStatus> {
return async (toolInput: unknown) => {
- if (definition.needsApproval === undefined) return false;
+ if (definition.approval === undefined) return undefined;
const toolInputRecord = isObject(toolInput) ? toolInput : undefined;
- return definition.needsApproval({
+ const status = await definition.approval({
+ ...buildCallbackContext(),
approvedTools: input.approvedTools ?? new Set(),
toolInput: toolInputRecord,
toolName: definition.name,
});
+ return typeof status === "boolean" ? (status ? "user-approval" : "not-applicable") : status;
+ };
+}
+
+/** Builds the AI SDK 7 call-level approval policy for an assembled tool set. */
+export function buildToolApproval(
+ tools: ToolSet,
+): ToolApprovalConfiguration<ToolSet, Record<string, unknown>> {
+ return async ({ toolCall }) => {
+ const toolDefinition = tools[toolCall.toolName];
+ if (toolDefinition === undefined) return undefined;
+
+ const approval = toolApprovals.get(toolDefinition);
+ return (await approval?.(toolCall.input)) as ToolApprovalStatus;
};
}
diff --git a/packages/eve/src/internal/authored-definition/core.test.ts b/packages/eve/src/internal/authored-definition/core.test.ts
index 52e020870..bb75270e5 100644
--- a/packages/eve/src/internal/authored-definition/core.test.ts
+++ b/packages/eve/src/internal/authored-definition/core.test.ts
@@ -1,6 +1,9 @@
import { describe, expect, it } from "vitest";
-import { normalizeAgentDefinition } from "#internal/authored-definition/core.js";
+import {
+ normalizeAgentDefinition,
+ normalizeScheduleDefinition,
+} from "#internal/authored-definition/core.js";
const FAILURE_MESSAGE = "Expected the agent config to match the public eve shape.";
@@ -79,3 +82,18 @@ describe("normalizeAgentDefinition", () => {
).toThrow('"experimental.workflow.world" must be a non-empty package name');
});
});
+
+describe("normalizeScheduleDefinition", () => {
+ it.each(["approval", "needsApproval"])("rejects the removed %s field", (field) => {
+ expect(() =>
+ normalizeScheduleDefinition(
+ {
+ cron: "0 9 * * *",
+ markdown: "Send a digest.",
+ [field]: () => "user-approval",
+ },
+ "Expected the schedule config to match the public eve shape.",
+ ),
+ ).toThrow(`Unknown key "${field}"`);
+ });
+});
diff --git a/packages/eve/src/internal/authored-definition/schema-backed.test.ts b/packages/eve/src/internal/authored-definition/schema-backed.test.ts
index 64dc436a4..eb0669184 100644
--- a/packages/eve/src/internal/authored-definition/schema-backed.test.ts
+++ b/packages/eve/src/internal/authored-definition/schema-backed.test.ts
@@ -116,12 +116,16 @@ describe("normalizeToolDefinition", () => {
execute(input) {
return input.city;
},
- needsApproval(ctx) {
+ approval(ctx) {
const city: string | undefined = ctx.toolInput?.city;
+ const callerId: string | undefined = ctx.session.auth.current?.principalId;
+ const turnId: string = ctx.session.turn.id;
// @ts-expect-error approval input is schema-typed, not an open record.
const missing = ctx.toolInput?.missing;
+ void callerId;
+ void turnId;
void missing;
- return city !== undefined;
+ return city !== undefined ? "user-approval" : "not-applicable";
},
});
@@ -135,12 +139,28 @@ describe("normalizeToolDefinition", () => {
execute(input) {
return input.city;
},
- needsApproval: once(),
+ approval: once(),
});
expect(normalizeToolDefinition(tool, FAILURE_MESSAGE).kind).toBe("tool");
});
+ it("rejects the removed needsApproval field", () => {
+ expect(() =>
+ normalizeToolDefinition(
+ {
+ description: "Uses the removed approval key.",
+ execute() {
+ return null;
+ },
+ inputSchema: { type: "object" },
+ needsApproval: () => true,
+ },
+ FAILURE_MESSAGE,
+ ),
+ ).toThrow('Unknown key "needsApproval"');
+ });
+
it("rejects authored tools whose `toModelOutput` is not a function", () => {
expect(() =>
normalizeToolDefinition(
diff --git a/packages/eve/src/internal/authored-definition/schema-backed.ts b/packages/eve/src/internal/authored-definition/schema-backed.ts
index c82d7eb08..869f5b0de 100644
--- a/packages/eve/src/internal/authored-definition/schema-backed.ts
+++ b/packages/eve/src/internal/authored-definition/schema-backed.ts
@@ -60,15 +60,7 @@ export function normalizeToolDefinition(value: unknown, message: string): Normal
const record = expectObjectRecord(value, message);
expectOnlyKnownKeys(
record,
- [
- "auth",
- "description",
- "execute",
- "inputSchema",
- "needsApproval",
- "outputSchema",
- "toModelOutput",
- ],
+ ["auth", "description", "execute", "inputSchema", "approval", "outputSchema", "toModelOutput"],
message,
);
const inputSchema =
@@ -88,12 +80,12 @@ export function normalizeToolDefinition(value: unknown, message: string): Normal
/*
* The compiler runs at build time and only validates that optional hooks
- * (`needsApproval`), when present, have the expected shape. The live
+ * (`approval`), when present, have the expected shape. The live
* references are captured later by `resolve-agent.ts` when it materializes
* the module export and attaches them to the ResolvedToolDefinition.
*/
- if (record.needsApproval !== undefined) {
- expectFunction(record.needsApproval, message);
+ if (record.approval !== undefined) {
+ expectFunction(record.approval, message);
}
if (record.toModelOutput !== undefined) {
diff --git a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts
index a071d953c..6ffd5f2b9 100644
--- a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts
+++ b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts
@@ -441,7 +441,7 @@ export function renderTool(
origin: input.origin,
outputSchema: tool.outputSchema,
replacesFrameworkTool: input.replacesFrameworkTool,
- requiresApproval: tool.needsApproval !== undefined,
+ requiresApproval: tool.approval !== undefined,
};
}
diff --git a/packages/eve/src/internal/testing/scenario-apps/tool-overrides.ts b/packages/eve/src/internal/testing/scenario-apps/tool-overrides.ts
index 3e688fd7d..03689ee6b 100644
--- a/packages/eve/src/internal/testing/scenario-apps/tool-overrides.ts
+++ b/packages/eve/src/internal/testing/scenario-apps/tool-overrides.ts
@@ -30,7 +30,7 @@ import { bash } from "eve/tools/defaults";
export default defineTool({
...bash,
description: "Run a vetted shell command in the project sandbox.",
- needsApproval: always(),
+ approval: always(),
async execute(input) {
return bash.execute(input);
},
diff --git a/packages/eve/src/public/definitions/approval.ts b/packages/eve/src/public/definitions/approval.ts
new file mode 100644
index 000000000..ba35d258d
--- /dev/null
+++ b/packages/eve/src/public/definitions/approval.ts
@@ -0,0 +1,43 @@
+import type { SessionContext } from "#public/definitions/callback-context.js";
+
+type ApprovalToolInput<TInput> = TInput extends object ? Readonly<TInput> : TInput;
+
+/**
+ * Context passed to an {@link Approval} function.
+ *
+ * Extends {@link SessionContext} so approval policies can make decisions from
+ * the active session, current caller, and turn.
+ *
+ * `approvedTools` is the set of tool names (or compound approval keys)
+ * already approved at least once in the current session. `toolName` is the
+ * runtime name of the tool being evaluated. `toolInput` is the raw input the
+ * model passed, available for input-aware decisions.
+ */
+export interface ApprovalContext<TInput = Record<string, unknown>> extends SessionContext {
+ readonly approvedTools: ReadonlySet<string>;
+ readonly toolInput?: ApprovalToolInput<TInput>;
+ readonly toolName: string;
+}
+
+/**
+ * Approval decision returned by an {@link Approval} function.
+ *
+ * AI SDK 7 statuses are accepted directly. For compatibility, `true` maps to
+ * `"user-approval"` and `false` maps to `"not-applicable"`.
+ */
+export type ApprovalStatus =
+ | undefined
+ | boolean
+ | "not-applicable"
+ | "approved"
+ | "denied"
+ | "user-approval"
+ | { readonly type: "not-applicable"; readonly reason?: never }
+ | { readonly type: "approved"; readonly reason?: string }
+ | { readonly type: "denied"; readonly reason?: string }
+ | { readonly type: "user-approval"; readonly reason?: never };
+
+/** Shared approval policy used by authored tools and connections. */
+export type Approval<TInput = Record<string, unknown>> = (
+ ctx: ApprovalContext<TInput>,
+) => ApprovalStatus | Promise<ApprovalStatus>;
diff --git a/packages/eve/src/public/definitions/connections/mcp.ts b/packages/eve/src/public/definitions/connections/mcp.ts
index 78c701a54..e4e586c8b 100644
--- a/packages/eve/src/public/definitions/connections/mcp.ts
+++ b/packages/eve/src/public/definitions/connections/mcp.ts
@@ -5,7 +5,7 @@ import type {
} from "#runtime/connections/types.js";
import { normalizeAuthorizationSpec } from "#runtime/connections/validate-authorization.js";
import { stampConnectionProtocol } from "#public/definitions/connections/protocol.js";
-import type { NeedsApprovalContext } from "#public/definitions/tool.js";
+import type { Approval } from "#public/definitions/approval.js";
import { stampDefinitionKey } from "#public/tool-result-narrowing.js";
/**
@@ -62,7 +62,7 @@ export interface McpClientConnectionDefinition {
* When omitted, tool calls execute without approval, consistent
* with authored tools.
*/
- approval?: (ctx: NeedsApprovalContext) => boolean;
+ approval?: Approval;
/**
* Arbitrary HTTP headers sent with every request to the MCP server.
*
diff --git a/packages/eve/src/public/definitions/connections/openapi.ts b/packages/eve/src/public/definitions/connections/openapi.ts
index 4850429ca..a090ac695 100644
--- a/packages/eve/src/public/definitions/connections/openapi.ts
+++ b/packages/eve/src/public/definitions/connections/openapi.ts
@@ -5,7 +5,7 @@ import type {
} from "#runtime/connections/types.js";
import { normalizeAuthorizationSpec } from "#runtime/connections/validate-authorization.js";
import { stampConnectionProtocol } from "#public/definitions/connections/protocol.js";
-import type { NeedsApprovalContext } from "#public/definitions/tool.js";
+import type { Approval } from "#public/definitions/approval.js";
import { stampDefinitionKey } from "#public/tool-result-narrowing.js";
/**
@@ -82,7 +82,7 @@ export interface OpenAPIConnectionDefinition {
* - `once()`: require approval only the first time per session
* - `always()`: require approval for every tool call
*/
- approval?: (ctx: NeedsApprovalContext) => boolean;
+ approval?: Approval;
/**
* Arbitrary HTTP headers sent with every request to the API.
*
diff --git a/packages/eve/src/public/definitions/exact.test.ts b/packages/eve/src/public/definitions/exact.test.ts
index 5472c0f1b..77359ee4e 100644
--- a/packages/eve/src/public/definitions/exact.test.ts
+++ b/packages/eve/src/public/definitions/exact.test.ts
@@ -105,6 +105,20 @@ function typeOnlyFixtures(): void {
run() {},
});
+ defineSchedule({
+ cron: "0 9 * * *",
+ markdown: "Send a digest.",
+ // @ts-expect-error Schedules do not support approval policies.
+ approval: () => "user-approval",
+ });
+
+ defineSchedule({
+ cron: "0 9 * * *",
+ markdown: "Send a digest.",
+ // @ts-expect-error Schedules do not support tool approval policies.
+ needsApproval: () => true,
+ });
+
const skillWithName = {
description: "Use source docs.",
markdown: "Prefer primary sources.",
@@ -209,6 +223,16 @@ function typeOnlyFixtures(): void {
return null;
},
});
+
+ defineTool({
+ description: "Removed tool approval key.",
+ inputSchema: { type: "object" },
+ // @ts-expect-error Authored tools use `approval`, not `needsApproval`.
+ needsApproval: () => true,
+ execute() {
+ return null;
+ },
+ });
}
void typeOnlyFixtures;
diff --git a/packages/eve/src/public/definitions/tool.ts b/packages/eve/src/public/definitions/tool.ts
index e68d1eb8a..277899989 100644
--- a/packages/eve/src/public/definitions/tool.ts
+++ b/packages/eve/src/public/definitions/tool.ts
@@ -3,6 +3,7 @@ import type { StandardJSONSchemaV1 } from "#compiled/@standard-schema/spec/index
import { stampDefinitionKey } from "#public/tool-result-narrowing.js";
import type { PublicToolDefinition, ToolModelOutput } from "#shared/tool-definition.js";
import type { SessionContext } from "#public/definitions/callback-context.js";
+import type { Approval } from "#public/definitions/approval.js";
import type { JsonObject } from "#shared/json.js";
import type {
AuthorizationDefinition,
@@ -17,23 +18,8 @@ import {
type DynamicSentinel,
} from "#shared/dynamic-tool-definition.js";
-type ApprovalToolInput<TInput> = TInput extends object ? Readonly<TInput> : TInput;
type ApprovalContextInput<TInput> = unknown extends TInput ? Record<string, unknown> : TInput;
-/**
- * Context passed to a tool's {@link ToolDefinition.needsApproval} function.
- *
- * `approvedTools` is the set of tool names (or compound approval keys)
- * already approved at least once in the current session. `toolName` is the
- * runtime name of the tool being evaluated. `toolInput` is the raw input the
- * model passed, available for input-aware decisions (e.g. per-connection scoping).
- */
-export interface NeedsApprovalContext<TInput = Record<string, unknown>> {
- readonly approvedTools: ReadonlySet<string>;
- readonly toolInput?: ApprovalToolInput<TInput>;
- readonly toolName: string;
-}
-
export type { ToolModelOutput } from "#shared/tool-definition.js";
/**
@@ -121,7 +107,7 @@ export type ToolDefinition<TInput = unknown, TOutput = unknown> = PublicToolDefi
* - {@link never}: never require approval
* - {@link once}: require approval only the first time per session
*/
- needsApproval?: (ctx: NeedsApprovalContext<ApprovalContextInput<TInput>>) => boolean;
+ approval?: Approval<ApprovalContextInput<TInput>>;
/**
* Optional projection controlling what the model sees as the tool result.
* Receives the full `TOutput` from {@link execute} and returns the
@@ -155,10 +141,7 @@ export function defineTool<
):
| Promise<StandardJSONSchemaV1.InferOutput<TOutputSchema>>
| StandardJSONSchemaV1.InferOutput<TOutputSchema>;
- needsApproval?: ToolDefinition<
- StandardJSONSchemaV1.InferOutput<TInputSchema>,
- unknown
- >["needsApproval"];
+ approval?: ToolDefinition<StandardJSONSchemaV1.InferOutput<TInputSchema>, unknown>["approval"];
toModelOutput?: ToolDefinition<
unknown,
StandardJSONSchemaV1.InferOutput<TOutputSchema>
@@ -178,10 +161,7 @@ export function defineTool<
input: StandardJSONSchemaV1.InferOutput<TSchema>,
ctx: ToolContext,
): Promise<TOutput> | TOutput;
- needsApproval?: ToolDefinition<
- StandardJSONSchemaV1.InferOutput<TSchema>,
- unknown
- >["needsApproval"];
+ approval?: ToolDefinition<StandardJSONSchemaV1.InferOutput<TSchema>, unknown>["approval"];
toModelOutput?: ToolDefinition<unknown, TOutput>["toModelOutput"];
}): ToolDefinition<StandardJSONSchemaV1.InferOutput<TSchema>, TOutput>;
export function defineTool<
@@ -196,7 +176,7 @@ export function defineTool<
):
| Promise<StandardJSONSchemaV1.InferOutput<TOutputSchema>>
| StandardJSONSchemaV1.InferOutput<TOutputSchema>;
- needsApproval?: ToolDefinition<Record<string, unknown>, unknown>["needsApproval"];
+ approval?: ToolDefinition<Record<string, unknown>, unknown>["approval"];
toModelOutput?: ToolDefinition<
unknown,
StandardJSONSchemaV1.InferOutput<TOutputSchema>
@@ -207,7 +187,7 @@ export function defineTool<TOutput>(definition: {
inputSchema: JsonObject;
outputSchema?: JsonObject;
execute(input: Record<string, unknown>, ctx: ToolContext): Promise<TOutput> | TOutput;
- needsApproval?: ToolDefinition<Record<string, unknown>, unknown>["needsApproval"];
+ approval?: ToolDefinition<Record<string, unknown>, unknown>["approval"];
toModelOutput?: ToolDefinition<unknown, TOutput>["toModelOutput"];
}): ToolDefinition<Record<string, unknown>, TOutput>;
export function defineTool<TInput = unknown, TOutput = unknown>(
diff --git a/packages/eve/src/public/tools/approval/approval-helpers.ts b/packages/eve/src/public/tools/approval/approval-helpers.ts
index f0d363d83..1d2906654 100644
--- a/packages/eve/src/public/tools/approval/approval-helpers.ts
+++ b/packages/eve/src/public/tools/approval/approval-helpers.ts
@@ -1,28 +1,29 @@
-import type { NeedsApprovalContext } from "#public/definitions/tool.js";
+import type { Approval } from "#public/definitions/approval.js";
/**
- * Returns a `needsApproval` callback that always requires user approval before
+ * Returns an `approval` callback that always requires user approval before
* the tool executes.
*/
-export function always<TInput = unknown>(): (ctx: NeedsApprovalContext<TInput>) => boolean {
- return () => true;
+export function always<TInput = unknown>(): Approval<TInput> {
+ return () => "user-approval";
}
/**
- * Returns a `needsApproval` callback that never requires user approval before
+ * Returns an `approval` callback that never requires user approval before
* the tool executes.
*/
-export function never<TInput = unknown>(): (ctx: NeedsApprovalContext<TInput>) => boolean {
- return () => false;
+export function never<TInput = unknown>(): Approval<TInput> {
+ return () => "not-applicable";
}
/**
- * Returns a `needsApproval` callback that requires approval until the user
+ * Returns an `approval` callback that requires approval until the user
* approves this tool once in the current session. A tool is recorded as
* approved only on an explicit approval; a denial (or continuing without
* responding) leaves it unrecorded, so the next call prompts again. Keys off
* the bare tool name, so it ignores compound approval keys.
*/
-export function once<TInput = unknown>(): (ctx: NeedsApprovalContext<TInput>) => boolean {
- return ({ approvedTools, toolName }) => !approvedTools.has(toolName);
+export function once<TInput = unknown>(): Approval<TInput> {
+ return ({ approvedTools, toolName }) =>
+ approvedTools.has(toolName) ? "not-applicable" : "user-approval";
}
diff --git a/packages/eve/src/public/tools/approval/index.ts b/packages/eve/src/public/tools/approval/index.ts
index ab12dd92b..88153a742 100644
--- a/packages/eve/src/public/tools/approval/index.ts
+++ b/packages/eve/src/public/tools/approval/index.ts
@@ -2,5 +2,5 @@
* Per-tool approval helpers used inside `agent/tools/*.ts` files.
*/
-export type { NeedsApprovalContext } from "#public/definitions/tool.js";
+export type { Approval, ApprovalContext, ApprovalStatus } from "#public/definitions/approval.js";
export { always, never, once } from "#public/tools/approval/approval-helpers.js";
diff --git a/packages/eve/src/public/tools/index.ts b/packages/eve/src/public/tools/index.ts
index 7c9a964b1..9dff3822c 100644
--- a/packages/eve/src/public/tools/index.ts
+++ b/packages/eve/src/public/tools/index.ts
@@ -10,7 +10,6 @@ export {
disableTool,
isDisabledToolSentinel,
isEnableWorkflowToolSentinel,
- type NeedsApprovalContext,
type ToolAuthOptions,
type ToolAuthProvider,
type ToolDefinition,
@@ -18,6 +17,7 @@ export {
type ToolModelOutput,
ExperimentalWorkflow,
} from "#public/definitions/tool.js";
+export type { Approval, ApprovalContext, ApprovalStatus } from "#public/definitions/approval.js";
export type {
DynamicToolEntry,
DynamicEvents,
diff --git a/packages/eve/src/public/tools/internal.ts b/packages/eve/src/public/tools/internal.ts
index ddb0aeeac..6867ccf49 100644
--- a/packages/eve/src/public/tools/internal.ts
+++ b/packages/eve/src/public/tools/internal.ts
@@ -26,8 +26,8 @@ export function toPublicToolDefinition(definition: ResolvedToolDefinition): Tool
outputSchema: definition.outputSchema,
};
- if (definition.needsApproval !== undefined) {
- publicDefinition.needsApproval = definition.needsApproval;
+ if (definition.approval !== undefined) {
+ publicDefinition.approval = definition.approval;
}
return publicDefinition;
diff --git a/packages/eve/src/runtime/connections/registry.ts b/packages/eve/src/runtime/connections/registry.ts
index 689472356..71637fd8d 100644
--- a/packages/eve/src/runtime/connections/registry.ts
+++ b/packages/eve/src/runtime/connections/registry.ts
@@ -1,4 +1,4 @@
-import type { NeedsApprovalContext } from "#public/definitions/tool.js";
+import type { Approval } from "#public/definitions/approval.js";
import type { ResolvedConnectionDefinition } from "#runtime/types.js";
import { McpConnectionClient } from "#runtime/connections/mcp-client.js";
import { OpenApiConnectionClient } from "#runtime/connections/openapi-client.js";
@@ -46,9 +46,7 @@ export class ConnectionRegistryImpl implements ConnectionRegistry {
* Returns the authored approval function for the named connection,
* or `undefined` if the connection did not specify one.
*/
- getConnectionApproval(
- connectionName: string,
- ): ((ctx: NeedsApprovalContext) => boolean) | undefined {
+ getConnectionApproval(connectionName: string): Approval | undefined {
const connection = this.#connections.find((c) => c.connectionName === connectionName);
return connection?.approval;
}
diff --git a/packages/eve/src/runtime/connections/types.ts b/packages/eve/src/runtime/connections/types.ts
index c634abadc..8a281ecb9 100644
--- a/packages/eve/src/runtime/connections/types.ts
+++ b/packages/eve/src/runtime/connections/types.ts
@@ -9,8 +9,8 @@
import type { ToolSet } from "ai";
import type { ConnectionAuthorizationChallenge } from "#public/connections/errors.js";
+import type { Approval } from "#public/definitions/approval.js";
import type { SessionContext } from "#public/definitions/callback-context.js";
-import type { NeedsApprovalContext } from "#public/definitions/tool.js";
import type { JsonValue } from "#public/types/json.js";
import type { ResolvedConnectionDefinition } from "#runtime/types.js";
@@ -441,9 +441,7 @@ export interface ConnectionClient {
export interface ConnectionRegistry {
dispose(): Promise<void>;
getClient(connectionName: string): ConnectionClient;
- getConnectionApproval(
- connectionName: string,
- ): ((ctx: NeedsApprovalContext) => boolean) | undefined;
+ getConnectionApproval(connectionName: string): Approval | undefined;
getConnectionNames(): readonly string[];
getConnections(): readonly ResolvedConnectionDefinition[];
}
diff --git a/packages/eve/src/runtime/framework-tools/connection-search-dynamic.ts b/packages/eve/src/runtime/framework-tools/connection-search-dynamic.ts
index 75cc41f83..de80884a0 100644
--- a/packages/eve/src/runtime/framework-tools/connection-search-dynamic.ts
+++ b/packages/eve/src/runtime/framework-tools/connection-search-dynamic.ts
@@ -424,7 +424,7 @@ export function createConnectionSearchEvents(): DynamicToolEvents {
inputSchema: (result.inputSchema ?? {
type: "object",
}) as JsonObject,
- needsApproval: approval,
+ approval,
outputSchema: result.outputSchema as JsonObject | undefined,
async execute(input: Record<string, unknown>) {
const reg = loadContext().get(ConnectionRegistryKey)!;
diff --git a/packages/eve/src/runtime/resolve-tool.ts b/packages/eve/src/runtime/resolve-tool.ts
index c25e5e698..93e8b69c0 100644
--- a/packages/eve/src/runtime/resolve-tool.ts
+++ b/packages/eve/src/runtime/resolve-tool.ts
@@ -12,7 +12,7 @@ import type { ResolvedToolDefinition } from "#runtime/types.js";
* Resolves one compiled authored tool into a runtime-owned definition
* with live callbacks reattached from the authored module.
*
- * Optional hooks (`needsApproval`, plus an optional Standard Schema
+ * Optional hooks (`approval`, plus an optional Standard Schema
* `inputSchema`) are extracted when
* declared and validated to have the expected shape; any type mismatch
* raises a {@link ResolveAgentError} so typos surface at resolve time
@@ -85,7 +85,7 @@ export async function resolveToolDefinition(
*/
type OptionalResolvedFields = {
-readonly [K in
- | "needsApproval"
+ | "approval"
| "toModelOutput"
| "inputStandardSchema"
| "outputStandardSchema"]?: ResolvedToolDefinition[K];
@@ -102,11 +102,11 @@ function extractOptionalHooks(
): OptionalResolvedFields {
const optional: OptionalResolvedFields = {};
- if (record.needsApproval !== undefined) {
- optional.needsApproval = expectFunction(
- record.needsApproval,
- describe(definition, "to provide a needsApproval function"),
- ) as ResolvedToolDefinition["needsApproval"];
+ if (record.approval !== undefined) {
+ optional.approval = expectFunction(
+ record.approval,
+ describe(definition, "to provide an approval function"),
+ ) as ResolvedToolDefinition["approval"];
}
if (record.toModelOutput !== undefined) {
diff --git a/packages/eve/src/runtime/types.ts b/packages/eve/src/runtime/types.ts
index b90d5b2b5..4ec16f788 100644
--- a/packages/eve/src/runtime/types.ts
+++ b/packages/eve/src/runtime/types.ts
@@ -8,7 +8,8 @@ import type { ChannelRouteMethod, RouteContext } from "#public/definitions/chann
import type { RouteHandler, WebSocketRouteHandler } from "#channel/routes.js";
import type { OutboundAuthFn } from "#public/agents/auth.js";
import type { StreamEventHook } from "#public/definitions/hook.js";
-import type { NeedsApprovalContext, ToolModelOutput } from "#public/definitions/tool.js";
+import type { Approval } from "#public/definitions/approval.js";
+import type { ToolModelOutput } from "#public/definitions/tool.js";
import type {
AuthorizationDefinition,
ConnectionAuthResolver,
@@ -92,7 +93,7 @@ export type ResolvedSchedule = Readonly<
* server that requires no authentication (e.g. localhost) may omit both.
*/
export interface ResolvedConnectionDefinition extends ResolvedModuleSourceRef {
- readonly approval?: (ctx: NeedsApprovalContext) => boolean;
+ readonly approval?: Approval;
readonly authorization?: Readonly<AuthorizationDefinition> | ConnectionAuthResolver;
readonly connectionName: string;
readonly description: string;
@@ -163,9 +164,9 @@ export type ResolvedToolDefinition = Readonly<
/**
* Optional per-tool approval gate. When set, determines whether user
* approval is required before executing this tool. See
- * {@link NeedsApprovalContext} for the available context.
+ * {@link Approval} for the shared callback contract.
*/
- readonly needsApproval?: (ctx: NeedsApprovalContext) => boolean;
+ readonly approval?: Approval;
/**
* Optional function that derives a compound approval key from the tool
* input. When present, the runtime records this key (instead of just
diff --git a/packages/eve/src/shared/dynamic-tool-definition.ts b/packages/eve/src/shared/dynamic-tool-definition.ts
index 1ccd13b30..cfe3fc0ec 100644
--- a/packages/eve/src/shared/dynamic-tool-definition.ts
+++ b/packages/eve/src/shared/dynamic-tool-definition.ts
@@ -6,7 +6,7 @@ import type {
ToolModelOutput,
} from "#shared/tool-definition.js";
import type { SessionContext } from "#public/definitions/callback-context.js";
-import type { NeedsApprovalContext } from "#public/definitions/tool.js";
+import type { Approval } from "#public/definitions/approval.js";
import type { SessionAuth } from "#context/keys.js";
import type { HandleMessageStreamEvent } from "#protocol/message.js";
@@ -88,13 +88,13 @@ export interface DynamicToolEntry<TInput = Record<string, unknown>, TOutput = an
readonly toModelOutput?: (output: TOutput) => ToolModelOutput | Promise<ToolModelOutput>;
/**
* Optional per-call approval gate, mirroring the authored-tool
- * `needsApproval` contract: return `true` to require user approval
+ * `approval` contract: return `"user-approval"` to require user approval
* before the call executes. Only honored for step-scoped dynamic
* tools, whose live `execute` closures survive into the harness;
* session/turn-scoped tools replay from durable metadata and cannot
* carry a function across replay.
*/
- readonly needsApproval?: (ctx: NeedsApprovalContext) => boolean;
+ readonly approval?: Approval;
}
/**