The Open Framework for Building Agents
feat(eve): tools - consolidate source layout (#2531)
Andrew Barba6252784b1058
diff --git a/.changeset/clean-tool-entrypoints.md b/.changeset/clean-tool-entrypoints.mdnew file mode 100644index 000000000..9b9af55ff--- /dev/null+++ b/.changeset/clean-tool-entrypoints.md@@ -0,0 +1,5 @@+---+"eve": minor+---++Move provided tool definitions and capability-specific helpers to dedicated `eve/tools/*` entrypoints. Replace the removed `defineBashTool`, `defineReadFileTool`, `defineWriteFileTool`, `defineGlobTool`, and `defineGrepTool` factories with the corresponding reusable definitions.diff --git a/docs/concepts/built-in-tools.md b/docs/concepts/built-in-tools.mdindex f24132b1b..3c3360163 100644--- a/docs/concepts/built-in-tools.md+++ b/docs/concepts/built-in-tools.md@@ -40,28 +40,24 @@ Review these default tools before production use. Disable, wrap, restrict, or reSome framework-provided tools stay out of the default set. Add the corresponding file when your agent needs one:-| Tool | Definition to export | Purpose |-| ---------- | ------------------------------------------ | -------------------------------------------------- |-| `glob` | `defineGlobTool()` from `eve/tools` | Find sandbox files by glob pattern. |-| `grep` | `defineGrepTool()` from `eve/tools` | Search sandbox file contents by regex. |-| `Workflow` | `experimental_workflow()` from `eve/tools` | Orchestrate root-agent copies from generated code. |-| `sleep` | `sleep()` from `eve/tools/sleep` | Pause and durably resume the current turn. |+| Tool | Definition to export | Purpose |+| ---------- | --------------------------------------------------- | -------------------------------------------------- |+| `glob` | `glob` from `eve/tools/glob` | Find sandbox files by glob pattern. |+| `grep` | `grep` from `eve/tools/grep` | Search sandbox file contents by regex. |+| `Workflow` | `experimental_workflow()` from `eve/tools/workflow` | Orchestrate root-agent copies from generated code. |+| `sleep` | `sleep()` from `eve/tools/sleep` | Pause and durably resume the current turn. |For example, add file discovery and content search with two files:```ts title="agent/tools/glob.ts"-import { defineGlobTool } from "eve/tools";--export default defineGlobTool();+export { glob as default } from "eve/tools/glob";``````ts title="agent/tools/grep.ts"-import { defineGrepTool } from "eve/tools";--export default defineGrepTool();+export { grep as default } from "eve/tools/grep";```-The filename supplies the model-facing tool name. You can pass a custom `description` to either helper. The tools run against the agent's sandbox and use the same schemas, results, and error behavior as eve's framework implementations.+The filename supplies the model-facing tool name. The tools run against the agent's sandbox and use the same schemas, results, and error behavior as eve's framework implementations. Wrap either definition with `defineTool({ ...glob, description: "..." })` or `defineTool({ ...grep, description: "..." })` when you need to change its description or approval policy.The sections below cover `Workflow` and `sleep` in more detail.@@ -100,7 +96,7 @@ Importing a definition does not add it to an agent; export it from the corresponProvider-managed web search has a dedicated configuration helper instead of an executable default:```ts title="agent/tools/web_search.ts"-import { webSearch } from "eve/tools";+import { webSearch } from "eve/tools/web_search";export default webSearch({ provider: "parallel" });```@@ -142,7 +138,7 @@ A single turn can already call several subagents, and parallel tool calls dispatExport the experimental Workflow definition from `agent/tools/workflow.ts`. The helper name carries the "experimental" warning, but the tool the model actually sees is named `Workflow`.```ts title="agent/tools/workflow.ts"-import { experimental_workflow } from "eve/tools";+import { experimental_workflow } from "eve/tools/workflow";export default experimental_workflow();```@@ -190,7 +186,7 @@ Workflow orchestration is capped in two independent ways.**Per-program call budget.** One Workflow program may dispatch at most `maxSubagents` subagent calls in total, counted across the whole program — sequential and parallel calls alike. Configure it on `experimental_workflow`; the default is 100. Calls beyond the budget do not start a child session; they resolve inside the program with a `WORKFLOW_SUBAGENT_LIMIT_REACHED` error result, and the budget is stated in the tool's description so the model sizes its fan-out to fit.```ts title="agent/tools/workflow.ts"-import { experimental_workflow } from "eve/tools";+import { experimental_workflow } from "eve/tools/workflow";export default experimental_workflow({ maxSubagents: 4 });```diff --git a/docs/patterns/multi-tenant-approvals.md b/docs/patterns/multi-tenant-approvals.mdindex b91ceebc3..caa29cac6 100644--- a/docs/patterns/multi-tenant-approvals.md+++ b/docs/patterns/multi-tenant-approvals.md@@ -21,7 +21,7 @@ Tenant policy storage remains yours. It might be a few columns in PostgreSQL, aThe current caller and initiating caller are both available on the session. This example requires them to belong to the same tenant before consulting policy:```ts title="agent/lib/tenant-approval.ts"-import type { ApprovalContext, ApprovalStatus } from "eve/tools";+import type { ApprovalContext, ApprovalStatus } from "eve/tools/approval";import { approvalPolicies } from "./approval-policies";type Surface = "connection" | "tool";diff --git a/docs/reference/typescript-api.md b/docs/reference/typescript-api.mdindex b9546aec8..9e2c07070 100644--- a/docs/reference/typescript-api.md+++ b/docs/reference/typescript-api.md@@ -3,7 +3,7 @@ title: "TypeScript API Reference"description: "The define* helpers, the runtime ctx, and where each one is imported from."----This is the public surface of the `eve` package: the `define*` helpers you author with, the `ctx` they receive at runtime, and the import path for each. The full contract lives in `packages/eve/src/public/index.ts`; anything not exported there is a framework internal.+This is the public surface of the `eve` package: the `define*` helpers you author with, the `ctx` they receive at runtime, and the import path for each. The package's export map defines the full contract; source files that are not reachable through an exported package subpath are framework internals.Identity comes from the filesystem, not a field you set. A tool at `agent/tools/get_weather.ts` is `get_weather`, and a connection at `agent/connections/linear.ts` is `linear`, so no definition carries a `name` or `id`.@@ -52,7 +52,9 @@ export default defineTool({| `mockModel` | `eve/evals` | Deterministic fixture agent models | [Evals](../evals/overview) || `useEveAgent` | `eve/react`, `eve/vue`, `eve/svelte` | frontend | [Frontend](../guides/frontend/overview) |-A few additional helpers round out the set: `defineGlobTool`, `defineGrepTool`, `disableTool`, `experimental_workflow`, and `webSearch` from `eve/tools` (see [Built-in tools](../concepts/built-in-tools)), `sleep` from `eve/tools/sleep`, the route verbs `GET`/`HEAD`/`POST`/`PUT`/`PATCH`/`DELETE`/`OPTIONS`/`WS` plus `disableRoute` 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 provided tool, import its definition from its individual subpath: `eve/tools/bash`, `eve/tools/read_file`, `eve/tools/write_file`, `eve/tools/todo`, `eve/tools/web_fetch`, `eve/tools/load_skill`, `eve/tools/glob`, or `eve/tools/grep`. `AgentReasoningDefinition` is exported from `eve` for the top-level `defineAgent({ reasoning })` setting. `AgentLimitsDefinition` is exported for `defineAgent({ limits })`. `AgentWorkflowDefinition` and `AgentWorkflowWorldDefinition` are exported from `eve` for the `defineAgent({ experimental: { workflow } })` config shape. `ExperimentalWorkflowToolInput`, `WebSearchToolInput`, and `WebSearchProvider` are exported from `eve/tools` for their corresponding tool configuration helpers.+Tool-wide authoring helpers such as `defineTool`, `defineDynamic`, and `disableTool` come from `eve/tools`. Capability-specific definitions and helpers use their own subpaths (see [Built-in tools](../concepts/built-in-tools)): reusable definitions such as `bash` and `glob` come from `eve/tools/<name>`, `webSearch` comes from `eve/tools/web_search`, `experimental_workflow` comes from `eve/tools/workflow`, `sleep` comes from `eve/tools/sleep`, and approval policies and types come from `eve/tools/approval`. The route verbs `GET`/`HEAD`/`POST`/`PUT`/`PATCH`/`DELETE`/`OPTIONS`/`WS` plus `disableRoute` come from `eve/channels`, and the channel auth helpers `localDev`/`vercelOidc`/`placeholderAuth` come from `eve/channels/auth`.++`AgentReasoningDefinition` is exported from `eve` for the top-level `defineAgent({ reasoning })` setting. `AgentLimitsDefinition` is exported for `defineAgent({ limits })`. `AgentWorkflowDefinition` and `AgentWorkflowWorldDefinition` are exported from `eve` for the `defineAgent({ experimental: { workflow } })` config shape. `ExperimentalWorkflowToolInput` is exported from `eve/tools/workflow`; `WebSearchToolInput` and `WebSearchProvider` are exported from `eve/tools/web_search`.`defineInstructions` accepts `{ content: string, role?: "system" | "user" }`; omitted `role` means `"system"`. Its `eve/instructions` version of `defineDynamic` accepts only `session.started` and `turn.started` handlers returning `defineInstructions(...)` or `null`. The legacy `{ markdown: string }` definition remains available as a deprecated system-role form.@@ -70,35 +72,37 @@ A few additional helpers round out the set: `defineGlobTool`, `defineGrepTool`,## Imports at a glance-| Import | Holds |-| --------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |-| `eve` | `defineAgent`, `defineRemoteAgent`, `defineDynamic`, agent config types |-| `eve/tools` | `defineTool`, `defineDynamic`, `defineGlobTool`, `defineGrepTool`, `disableTool`, `experimental_workflow` |-| `eve/tools/{bash,read_file,write_file,todo,web_fetch,load_skill,glob,grep}` | individual reusable tool definitions |-| `eve/tools/approval` | `always`, `once`, `never` |-| `eve/tools/sleep` | opt-in durable `sleep` tool |-| `eve/connections` | `defineMcpClientConnection`, `defineOpenAPIConnection` |-| `eve/channels` | `defineChannel`, `disableRoute`, route verbs |-| `eve/channels/eve` | `eveChannel` |-| `eve/channels/auth` | `localDev`, `vercelOidc`, `placeholderAuth` |-| `eve/channels/{slack,discord,teams,telegram,twilio,github}` | platform channel factories |-| `eve/hooks` | `defineHook` |-| `eve/schedules` | `defineSchedule` |-| `eve/skills` | `defineSkill`, `defineDynamic` |-| `eve/instructions` | `defineInstructions`, `defineDynamic` |-| `eve/context` | `defineState`, session and state types |-| `eve/sandbox` | `defineSandbox`, backends |-| `eve/instrumentation` | `defineInstrumentation`, `isChannel` |-| `eve/models/openai` | `chatgpt`, deprecated `experimental_chatgpt` |-| `eve/evals` | `defineEval`, `defineEvalConfig`, `mockModel`, eval types |-| `eve/evals/expect` | `includes`, `equals`, `matches`, `similarity` |-| `eve/evals/reporters` | `Braintrust`, `JUnit`, `EvalReporter` |-| `eve/evals/loaders` | `loadJson`, `loadYaml` |-| `eve/react`, `eve/vue`, `eve/svelte` | `useEveAgent` |-| `eve/next`, `eve/nuxt`, `eve/sveltekit` | framework bundler plugins |-| [`eve/client`](../guides/client/overview) | `Client`, `ClientSession`, health and agent-info schemas, response errors |--Exported types ship from the same entrypoint as the helper they describe (for example `ToolDefinition` and `ToolContext` from `eve/tools`). For the exhaustive list, read `packages/eve/src/public/index.ts`.+| Import | Holds |+| --------------------------------------------------------------------------- | ------------------------------------------------------------------------- |+| `eve` | `defineAgent`, `defineRemoteAgent`, `defineDynamic`, agent config types |+| `eve/tools` | `defineTool`, `defineDynamic`, `disableTool`, generic tool types |+| `eve/tools/{bash,read_file,write_file,todo,web_fetch,load_skill,glob,grep}` | Individual reusable tool definitions |+| `eve/tools/approval` | Approval types and `always`, `once`, `never` |+| `eve/tools/web_search` | Provider-managed `webSearch` configuration |+| `eve/tools/workflow` | Experimental `Workflow` tool definition |+| `eve/tools/sleep` | Opt-in durable `sleep` tool |+| `eve/connections` | `defineMcpClientConnection`, `defineOpenAPIConnection` |+| `eve/channels` | `defineChannel`, `disableRoute`, route verbs |+| `eve/channels/eve` | `eveChannel` |+| `eve/channels/auth` | `localDev`, `vercelOidc`, `placeholderAuth` |+| `eve/channels/{slack,discord,teams,telegram,twilio,github}` | platform channel factories |+| `eve/hooks` | `defineHook` |+| `eve/schedules` | `defineSchedule` |+| `eve/skills` | `defineSkill`, `defineDynamic` |+| `eve/instructions` | `defineInstructions`, `defineDynamic` |+| `eve/context` | `defineState`, session and state types |+| `eve/sandbox` | `defineSandbox`, backends |+| `eve/instrumentation` | `defineInstrumentation`, `isChannel` |+| `eve/models/openai` | `chatgpt`, deprecated `experimental_chatgpt` |+| `eve/evals` | `defineEval`, `defineEvalConfig`, `mockModel`, eval types |+| `eve/evals/expect` | `includes`, `equals`, `matches`, `similarity` |+| `eve/evals/reporters` | `Braintrust`, `JUnit`, `EvalReporter` |+| `eve/evals/loaders` | `loadJson`, `loadYaml` |+| `eve/react`, `eve/vue`, `eve/svelte` | `useEveAgent` |+| `eve/next`, `eve/nuxt`, `eve/sveltekit` | framework bundler plugins |+| [`eve/client`](../guides/client/overview) | `Client`, `ClientSession`, health and agent-info schemas, response errors |++Exported types ship from the same entrypoint as the helper they describe (for example `ToolDefinition` and `ToolContext` from `eve/tools`). The `exports` field in `packages/eve/package.json` lists every public entrypoint.## ChatGPT subscription modelsdiff --git a/docs/tools/human-in-the-loop.md b/docs/tools/human-in-the-loop.mdindex aff02be0a..c2876b4a5 100644--- a/docs/tools/human-in-the-loop.md+++ b/docs/tools/human-in-the-loop.md@@ -52,7 +52,7 @@ approval: ({ session, toolInput }) => {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`.+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 `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.diff --git a/e2e/fixtures/agent-subagents/agent/tools/workflow.ts b/e2e/fixtures/agent-subagents/agent/tools/workflow.tsindex d6af27e60..2dc9657d0 100644--- a/e2e/fixtures/agent-subagents/agent/tools/workflow.ts+++ b/e2e/fixtures/agent-subagents/agent/tools/workflow.ts@@ -1,3 +1,3 @@-import { experimental_workflow } from "eve/tools";+import { experimental_workflow } from "eve/tools/workflow";export default experimental_workflow({ maxSubagents: 2 });diff --git a/e2e/fixtures/agent-tools-sandbox/agent/tools/bash.ts b/e2e/fixtures/agent-tools-sandbox/agent/tools/bash.tsindex 7822464cf..f4b438707 100644--- a/e2e/fixtures/agent-tools-sandbox/agent/tools/bash.ts+++ b/e2e/fixtures/agent-tools-sandbox/agent/tools/bash.ts@@ -1,5 +1,6 @@-import { defineTool, defineBashTool } from "eve/tools";+import { defineTool } from "eve/tools";import { never } from "eve/tools/approval";+import { bash } from "eve/tools/bash";/*** Bash tool exposed to the model for the sandbox-bootstrap smoke@@ -7,12 +8,12 @@ import { never } from "eve/tools/approval";* and avoids tripping the HITL machinery already exercised by* `tool-approval.ts` / `tool-denial.ts`.*- * Wrapping the framework's `defineBashTool()` in `defineTool({...})`+ * Wrapping the framework's `bash` definition in `defineTool({...})`* gives the inferred default a named return type so tsc does not* trip the TS2883 "inferred type cannot be named" portability* check.*/export default defineTool({- ...defineBashTool(),+ ...bash,approval: never(),});diff --git a/e2e/fixtures/agent-tools-sandbox/agent/tools/grep.ts b/e2e/fixtures/agent-tools-sandbox/agent/tools/grep.tsindex eeae71499..db3167e55 100644--- a/e2e/fixtures/agent-tools-sandbox/agent/tools/grep.ts+++ b/e2e/fixtures/agent-tools-sandbox/agent/tools/grep.ts@@ -1,3 +1 @@-import { defineGrepTool } from "eve/tools";--export default defineGrepTool();+export { grep as default } from "eve/tools/grep";diff --git a/e2e/fixtures/agent-tools/agent/tools/web_search.ts b/e2e/fixtures/agent-tools/agent/tools/web_search.tsindex 718bb98ea..918e5269b 100644--- a/e2e/fixtures/agent-tools/agent/tools/web_search.ts+++ b/e2e/fixtures/agent-tools/agent/tools/web_search.ts@@ -1,3 +1,3 @@-import { webSearch } from "eve/tools";+import { webSearch } from "eve/tools/web_search";export default webSearch({ provider: "exa" });diff --git a/packages/eve/README.md b/packages/eve/README.mdindex d04beb7fd..bd52a93c6 100644--- a/packages/eve/README.md+++ b/packages/eve/README.md@@ -55,18 +55,19 @@ my-agent/Every authored directory has a typed helper. Import each from the matching subpath:-| Helper | Subpath | Authored Location |-| ------------------------------------------------------------------------------------------------------------------- | ------------------------------------- | ------------------------------------------------ |-| `defineAgent(...)` | `eve` | `agent.ts`, `subagents/<id>/agent.ts` |-| `defineInstructions(...)` | `eve/instructions` | `instructions.ts` (or `instructions.md`) |-| `defineTool(...)`, `defineBashTool(...)`, `defineReadFileTool(...)`, `defineWriteFileTool(...)`, `disableTool(...)` | `eve/tools` | `tools/<name>.ts` |-| `defineSkill(...)`, `getSkill(...)` | `eve/skills` | `skills/<name>.ts` (or `skills/<name>.md`) |-| `defineHook(...)` | `eve/hooks` | `hooks/<slug>.ts` |-| `defineChannel(...)`, `POST`, `GET` | `eve/channels` | `channels/<name>.ts` |-| `eveChannel(...)`, `slackChannel(...)`, `vercelOidc(...)` | `eve/channels/eve`, `/slack`, `/auth` | reused from `channels/<name>.ts` |-| `defineSandbox(...)` | `eve/sandbox` | `sandbox.ts` (or `sandbox/sandbox.ts`) |-| `defineSchedule(...)` | `eve/schedules` | `schedules/<name>.ts` (or `schedules/<name>.md`) |-| `defineEval(...)`, `defineEvalConfig(...)` | `eve/evals` | `evals/<name>.eval.ts`, `evals/evals.config.ts` |+| Helper | Subpath | Authored Location |+| --------------------------------------------------------------- | ------------------------------------- | ------------------------------------------------ |+| `defineAgent(...)` | `eve` | `agent.ts`, `subagents/<id>/agent.ts` |+| `defineInstructions(...)` | `eve/instructions` | `instructions.ts` (or `instructions.md`) |+| `defineTool(...)`, `defineDynamic(...)`, `disableTool(...)` | `eve/tools` | `tools/<name>.ts` |+| `bash`, `readFile`, `writeFile`, and other provided definitions | `eve/tools/<name>` | `tools/<name>.ts` |+| `defineSkill(...)`, `getSkill(...)` | `eve/skills` | `skills/<name>.ts` (or `skills/<name>.md`) |+| `defineHook(...)` | `eve/hooks` | `hooks/<slug>.ts` |+| `defineChannel(...)`, `POST`, `GET` | `eve/channels` | `channels/<name>.ts` |+| `eveChannel(...)`, `slackChannel(...)`, `vercelOidc(...)` | `eve/channels/eve`, `/slack`, `/auth` | reused from `channels/<name>.ts` |+| `defineSandbox(...)` | `eve/sandbox` | `sandbox.ts` (or `sandbox/sandbox.ts`) |+| `defineSchedule(...)` | `eve/schedules` | `schedules/<name>.ts` (or `schedules/<name>.md`) |+| `defineEval(...)`, `defineEvalConfig(...)` | `eve/evals` | `evals/<name>.eval.ts`, `evals/evals.config.ts` |Runtime accessors live on the subpath that owns the concern:diff --git a/packages/eve/extension-contracts/compatibility/connection/v5.ts b/packages/eve/extension-contracts/compatibility/connection/v5.tsnew file mode 100644index 000000000..def585931--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/connection/v5.ts@@ -0,0 +1,11 @@+import { defineMcpClientConnection } from "#public/connections/index.js";++export default defineMcpClientConnection({+ description: "Tenant-aware MCP service",+ toolCall: {+ providedArguments: {+ tenantId: ({ session, toolName }) => `${session.id}:${toolName}`,+ },+ },+ url: "https://example.com/mcp",+});diff --git a/packages/eve/extension-contracts/compatibility/dynamicTool/v18.ts b/packages/eve/extension-contracts/compatibility/dynamicTool/v18.tsnew file mode 100644index 000000000..6252c112c--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/dynamicTool/v18.ts@@ -0,0 +1,19 @@+import { z } from "zod";++import { defineDynamic, defineTool } from "#public/tools/index.js";++export default defineDynamic({+ events: {+ "turn.started": (_event, ctx) =>+ defineTool({+ description: "Echo the tool call identifiers.",+ inputSchema: z.object({ note: z.string() }),+ execute: ({ note }, toolCtx) => ({+ callId: toolCtx.callId,+ note,+ sessionId: ctx.session.id,+ toolName: toolCtx.toolName,+ }),+ }),+ },+});diff --git a/packages/eve/extension-contracts/compatibility/tool/v17.ts b/packages/eve/extension-contracts/compatibility/tool/v17.tsnew file mode 100644index 000000000..79660c5bd--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/tool/v17.ts@@ -0,0 +1,18 @@+import { z } from "zod";++import { defineTool } from "#public/tools/index.js";++export default defineTool({+ description: "Start a report.",+ execution: "background",+ inputSchema: z.object({ reportId: z.string() }),+ execute(input, _ctx, task) {+ void Promise.resolve().then(() =>+ task.send({ data: { reportId: input.reportId }, kind: "complete" }),+ );+ return task.delegated({+ executor: { data: { reportId: input.reportId }, kind: "report" },+ receipt: { reportId: input.reportId },+ });+ },+});diff --git a/packages/eve/extension-contracts/current/tool.ts b/packages/eve/extension-contracts/current/tool.tsnew file mode 100644index 000000000..9630b667b--- /dev/null+++ b/packages/eve/extension-contracts/current/tool.ts@@ -0,0 +1,3 @@+export * from "../../src/public/tools/index.ts";+export * from "../../src/public/tools/workflow.ts";+export * from "../../src/public/tools/web-search.ts";diff --git a/packages/eve/extension-contracts/entrypoints/tool.ts b/packages/eve/extension-contracts/entrypoints/tool.tsindex d14f8edb5..c8f62288e 100644--- a/packages/eve/extension-contracts/entrypoints/tool.ts+++ b/packages/eve/extension-contracts/entrypoints/tool.ts@@ -1,16 +1,17 @@export {- defineBashTool,- defineGlobTool,- defineGrepTool,- defineReadFileTool,defineTool,- defineWriteFileTool,disableTool,- experimental_workflow,isDisabledToolSentinel,- isExperimentalWorkflowToolDefinition,toolOutput,toolOutputPart,toolResultFrom,- webSearch,} from "../../src/public/tools/index.ts";+export {+ experimental_workflow,+ isExperimentalWorkflowToolDefinition,+} from "../../src/public/tools/workflow.ts";+export {+ defaultWebSearch,+ isWebSearchToolDefinition,+ webSearch,+} from "../../src/public/tools/web-search.ts";diff --git a/packages/eve/extension-contracts/reports/connection/v6.json b/packages/eve/extension-contracts/reports/connection/v6.jsonnew file mode 100644index 000000000..ddff73d27--- /dev/null+++ b/packages/eve/extension-contracts/reports/connection/v6.json@@ -0,0 +1,15 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "connection",+ "epoch": 6,+ "sha256": "11791cd290bc67b5948e19d26b5cb6352c16f7f1ae9b96875cedd57adaa8eecf",+ "exports": [+ "ConnectionAuthorizationFailedError",+ "ConnectionAuthorizationRequiredError",+ "defineInteractiveAuthorization",+ "defineMcpClientConnection",+ "defineOpenAPIConnection",+ "isConnectionAuthorizationFailedError",+ "isConnectionAuthorizationRequiredError"+ ]+}diff --git a/packages/eve/extension-contracts/reports/dynamicTool/v19.json b/packages/eve/extension-contracts/reports/dynamicTool/v19.jsonnew file mode 100644index 000000000..769b603d9--- /dev/null+++ b/packages/eve/extension-contracts/reports/dynamicTool/v19.json@@ -0,0 +1,13 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "dynamicTool",+ "epoch": 19,+ "sha256": "bb1fc12b6336cfd33d1822c785b4782eeeefa90c3e7d81e84fd8c68c85cc579d",+ "exports": [+ "DynamicToolEntry",+ "DynamicToolEvents",+ "DynamicToolResult",+ "DynamicToolSet",+ "defineDynamic"+ ]+}diff --git a/packages/eve/extension-contracts/reports/tool/v18.json b/packages/eve/extension-contracts/reports/tool/v18.jsonnew file mode 100644index 000000000..42b67bcb3--- /dev/null+++ b/packages/eve/extension-contracts/reports/tool/v18.json@@ -0,0 +1,19 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "tool",+ "epoch": 18,+ "sha256": "05f5a1823d2df82afb41719e78b34ebb98522025e6e598db2cd93e1e7defe8b7",+ "exports": [+ "defaultWebSearch",+ "defineTool",+ "disableTool",+ "experimental_workflow",+ "isDisabledToolSentinel",+ "isExperimentalWorkflowToolDefinition",+ "isWebSearchToolDefinition",+ "toolOutput",+ "toolOutputPart",+ "toolResultFrom",+ "webSearch"+ ]+}diff --git a/packages/eve/extension-contracts/tsconfig.json b/packages/eve/extension-contracts/tsconfig.jsonindex abfb94000..f05c73164 100644--- a/packages/eve/extension-contracts/tsconfig.json+++ b/packages/eve/extension-contracts/tsconfig.json@@ -2,7 +2,10 @@"$schema": "https://json.schemastore.org/tsconfig","extends": "../tsconfig.build.json","compilerOptions": {- "rootDir": ".."+ "rootDir": "..",+ "paths": {+ "#public/tools/index.js": ["./current/tool.ts"]+ }},"include": ["entrypoints/**/*.ts", "compatibility/**/*.ts"],"exclude": []diff --git a/packages/eve/package.json b/packages/eve/package.jsonindex 85b52baac..922518b3f 100644--- a/packages/eve/package.json+++ b/packages/eve/package.json@@ -102,9 +102,9 @@"default": "./dist/src/public/tools/approval/index.js"},"./tools/sleep": {- "types": "./dist/src/public/tools/sleep/index.d.ts",- "import": "./dist/src/public/tools/sleep/index.js",- "default": "./dist/src/public/tools/sleep/index.js"+ "types": "./dist/src/public/tools/sleep.d.ts",+ "import": "./dist/src/public/tools/sleep.js",+ "default": "./dist/src/public/tools/sleep.js"},"./tools": {"types": "./dist/src/public/tools/index.d.ts",@@ -136,6 +136,11 @@"import": "./dist/src/public/tools/web-fetch.js","default": "./dist/src/public/tools/web-fetch.js"},+ "./tools/web_search": {+ "types": "./dist/src/public/tools/web-search.d.ts",+ "import": "./dist/src/public/tools/web-search.js",+ "default": "./dist/src/public/tools/web-search.js"+ },"./tools/load_skill": {"types": "./dist/src/public/tools/load-skill.d.ts","import": "./dist/src/public/tools/load-skill.js",@@ -151,6 +156,11 @@"import": "./dist/src/public/tools/grep.js","default": "./dist/src/public/tools/grep.js"},+ "./tools/workflow": {+ "types": "./dist/src/public/tools/workflow.d.ts",+ "import": "./dist/src/public/tools/workflow.js",+ "default": "./dist/src/public/tools/workflow.js"+ },"./models/openai": {"types": "./dist/src/public/models/openai/index.d.ts","import": "./dist/src/public/models/openai/index.js",diff --git a/packages/eve/src/public/definitions/approval.test.ts b/packages/eve/src/approval/definition.test.tssimilarity index 97%rename from packages/eve/src/public/definitions/approval.test.tsrename to packages/eve/src/approval/definition.test.tsindex e249d0a04..eaebad1dc 100644--- a/packages/eve/src/public/definitions/approval.test.ts+++ b/packages/eve/src/approval/definition.test.ts@@ -4,7 +4,7 @@ import {resolveApprovalPolicy,type Approval,type ApprovalResponseContext,-} from "#public/definitions/approval.js";+} from "#approval/definition.js";describe("approval definitions", () => {it("preserves request-time function shorthand", async () => {diff --git a/packages/eve/src/approval/definition.ts b/packages/eve/src/approval/definition.tsnew file mode 100644index 000000000..ad551bfb1--- /dev/null+++ b/packages/eve/src/approval/definition.ts@@ -0,0 +1,100 @@+import type { SessionAuthContext } from "#channel/types.js";+import type { SessionParent, SessionTurn } from "#context/keys.js";+import type { ToolAuthOptions, ToolAuthProvider } from "#tools/auth.js";+import type { SessionContext } from "#context/session-context.js";+import type { TokenResult } from "#shared/connection-types.js";++type ApprovalToolInput<TInput> = TInput extends object ? Readonly<TInput> : TInput;++/**+ * Context passed to an {@link ApprovalPolicy} function.+ *+ * Extends {@link SessionContext} so approval policies can make decisions from+ * the active session, current caller, and turn.+ */+export interface ApprovalContext<TInput = Record<string, unknown>> extends SessionContext {+ readonly approvedTools: ReadonlySet<string>;+ readonly callId: string;+ readonly toolInput?: ApprovalToolInput<TInput>;+ readonly toolName: string;+}++/** Request-time approval decision returned by an {@link ApprovalPolicy}. */+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 };++/** Request-time approval policy shared by authored tools and connections. */+export type ApprovalPolicy<TInput = Record<string, unknown>> = (+ ctx: ApprovalContext<TInput>,+) => ApprovalStatus | Promise<ApprovalStatus>;++/** Stable tool request passed to a response authorizer. */+export interface ApprovalRequest<TInput = Record<string, unknown>> {+ readonly callId: string;+ readonly requestId: string;+ readonly toolInput?: ApprovalToolInput<TInput>;+ readonly toolName: string;+}++/** Read-only session identity and lineage available to a response authorizer. */+export interface ApprovalResponseSession {+ readonly id: string;+ readonly initiator: SessionAuthContext | null;+ readonly parent?: SessionParent;+ readonly turn: SessionTurn;+}++/** Narrow authorization capability available while validating a responder. */+export interface ApprovalResponseAuth {+ getToken(provider: ToolAuthProvider, options?: ToolAuthOptions): Promise<TokenResult>;+ requireAuth(provider: ToolAuthProvider, options?: ToolAuthOptions): never;+}++/** Submitted decision passed to an approval response policy. */+export interface ApprovalResponse {+ readonly decision: "approve";+}++/** Context passed to an approval response policy. */+export interface ApprovalResponseContext<TInput = Record<string, unknown>> {+ readonly auth: ApprovalResponseAuth;+ readonly request: ApprovalRequest<TInput>;+ readonly response: ApprovalResponse;+ readonly responder: SessionAuthContext;+ readonly session: ApprovalResponseSession;+}++/** Response policy decision. Rejection keeps the shared request pending. */+export type ApprovalResponseDecision =+ | { readonly status: "allowed" }+ | { readonly reason: string; readonly status: "rejected" };++/** Decides whether an authenticated responder may approve one request. */+export type ApprovalResponsePolicy<TInput = Record<string, unknown>> = (+ ctx: ApprovalResponseContext<TInput>,+) => ApprovalResponseDecision | Promise<ApprovalResponseDecision>;++/** Approval definition with request- and response-time policy. */+export interface ApprovalConfiguration<TInput = Record<string, unknown>> {+ readonly request: ApprovalPolicy<TInput>;+ readonly response?: ApprovalResponsePolicy<TInput>;+}++/** Shared approval definition used by authored tools and connections. */+export type Approval<TInput = Record<string, unknown>> =+ | ApprovalPolicy<TInput>+ | ApprovalConfiguration<TInput>;++/** Returns the request-time policy from either approval authoring shape. */+export function resolveApprovalPolicy<TInput>(approval: Approval<TInput>): ApprovalPolicy<TInput> {+ return typeof approval === "function" ? approval : approval.request;+}diff --git a/packages/eve/src/cli/dev/tui/agent-header.test.ts b/packages/eve/src/cli/dev/tui/agent-header.test.tsindex ea700deb2..85214a4b6 100644--- a/packages/eve/src/cli/dev/tui/agent-header.test.ts+++ b/packages/eve/src/cli/dev/tui/agent-header.test.ts@@ -19,7 +19,7 @@ const FRAMEWORK_TOOL: AgentInfoToolEntry = {owner: { feature: "test", kind: "framework" },outputSchema: { type: "object" },requiresApproval: false,- sourceId: "eve:bash-tool",+ sourceId: "eve:defaults:tools/bash.ts",sourceKind: "module",};diff --git a/packages/eve/src/cli/invoke/result.ts b/packages/eve/src/cli/invoke/result.tsindex fbce831cd..3b31d87f2 100644--- a/packages/eve/src/cli/invoke/result.ts+++ b/packages/eve/src/cli/invoke/result.ts@@ -1,6 +1,6 @@import { z } from "#compiled/zod/index.js";import { inputOptionSchema, inputRequestSchema, type InputRequest } from "#client/index.js";-import type { ConnectionAuthorizationChallenge } from "#public/connections/errors.js";+import type { ConnectionAuthorizationChallenge } from "#connections/errors.js";const sessionCursorSchema = z.object({diff --git a/packages/eve/src/client/session.ts b/packages/eve/src/client/session.tsindex f43df30bc..e1a2b43fc 100644--- a/packages/eve/src/client/session.ts+++ b/packages/eve/src/client/session.ts@@ -10,7 +10,7 @@ import {compactClientSession,resetClientSession,} from "#client/session-controls.js";-import { serializeOutputSchema } from "#shared/tool-schema.js";+import { serializeOutputSchema } from "#tools/schema.js";import { createClientUrl } from "#client/url.js";import type { InputResponse } from "#shared/input.js";import type {diff --git a/packages/eve/src/compiler/compile-from-memory.ts b/packages/eve/src/compiler/compile-from-memory.tsindex 47aa6f89c..39cc8cf2d 100644--- a/packages/eve/src/compiler/compile-from-memory.ts+++ b/packages/eve/src/compiler/compile-from-memory.ts@@ -4,7 +4,7 @@ import type { JsonObject } from "#shared/json.js";import { createAgentSourceManifest } from "#discover/manifest.js";import { defineAgent, type AgentDefinition } from "#public/definitions/agent.js";import { defineSkill } from "#public/definitions/skill.js";-import { defineTool, type ToolDefinition } from "#public/definitions/tool.js";+import { defineTool, type ToolDefinition } from "#tools/definition.js";import type { CompiledAgentManifest } from "#compiler/manifest.js";import {createProgrammaticCompiledModuleMap,diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.tsindex dd7ab7218..d85750b4c 100644--- a/packages/eve/src/compiler/extension-compatibility.ts+++ b/packages/eve/src/compiler/extension-compatibility.ts@@ -22,19 +22,23 @@ interface ExtensionCapabilityContract {const EXTENSION_CAPABILITY_CONTRACTS = {extension: { current: 1, supported: [1], dropped: {} },tool: {- current: 17,- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17],+ current: 18,+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18],dropped: { 15: "TaskExec replaces stageEffect with send" },},dynamicTool: {- current: 18,- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18],+ current: 19,+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19],dropped: {},},channel: { current: 9, supported: [1, 2, 3, 4, 5, 6, 7, 8, 9], dropped: {} },schedule: { current: 3, supported: [1, 2, 3], dropped: {} },subagent: { current: 2, supported: [1, 2], dropped: {} },- connection: { current: 5, supported: [1, 2, 3, 4, 5], dropped: {} },+ connection: {+ current: 6,+ supported: [1, 2, 3, 4, 5, 6],+ dropped: {},+ },hook: {current: 14,supported: [10, 11, 12, 13, 14],diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.tsindex bb3769fe4..0d4be076e 100644--- a/packages/eve/src/compiler/manifest.ts+++ b/packages/eve/src/compiler/manifest.ts@@ -27,7 +27,7 @@ import type {AgentBuildDefinition,ModelRouting,} from "#shared/agent-definition.js";-import type { InternalToolDefinition } from "#shared/tool-definition.js";+import type { InternalToolDefinition } from "#tools/definition.js";import type { WebSearchProvider } from "#shared/web-search.js";import type {AgentModuleBacking,diff --git a/packages/eve/src/compiler/normalize-agent-config.ts b/packages/eve/src/compiler/normalize-agent-config.tsindex c36927924..df496ccb4 100644--- a/packages/eve/src/compiler/normalize-agent-config.ts+++ b/packages/eve/src/compiler/normalize-agent-config.ts@@ -3,7 +3,7 @@ import { isAbsolute, relative, resolve } from "node:path";import type { AgentSourceManifest } from "#discover/manifest.js";import { normalizeLogicalPath } from "#discover/filesystem.js";import { normalizeAgentDefinition } from "#internal/authored-definition/core.js";-import { serializeOutputSchema } from "#shared/tool-schema.js";+import { serializeOutputSchema } from "#tools/schema.js";import { formatLanguageModelGatewayId } from "#internal/runtime-model.js";import { classifyModelRouting } from "#internal/classify-model-routing.js";import { isChatGptModelRouting } from "#shared/chatgpt-model.js";@@ -14,7 +14,7 @@ import {isDynamicModelDefinition,type PublicAgentStaticModelDefinition,} from "#shared/agent-definition.js";-import type { DynamicToolEventName } from "#shared/dynamic-tool-definition.js";+import type { DynamicToolEventName } from "#dynamic/definition.js";import type { CompiledAgentDefinition, CompiledRuntimeModelReference } from "#compiler/manifest.js";import type { CompiledRuntimeModelLimits } from "#compiler/model-catalog.js";import {diff --git a/packages/eve/src/compiler/normalize-instructions.ts b/packages/eve/src/compiler/normalize-instructions.tsindex d900b99c5..d528e72ec 100644--- a/packages/eve/src/compiler/normalize-instructions.ts+++ b/packages/eve/src/compiler/normalize-instructions.ts@@ -15,7 +15,7 @@ import {ALLOWED_DYNAMIC_INSTRUCTION_EVENTS,isDynamicSentinel,type DynamicToolEventName,-} from "#shared/dynamic-tool-definition.js";+} from "#dynamic/definition.js";/*** Compiled instructions entry produced from one authored `instructions/*`diff --git a/packages/eve/src/compiler/normalize-manifest.test.ts b/packages/eve/src/compiler/normalize-manifest.test.tsindex 2e7a3c133..456a7ad89 100644--- a/packages/eve/src/compiler/normalize-manifest.test.ts+++ b/packages/eve/src/compiler/normalize-manifest.test.ts@@ -18,7 +18,7 @@ import { frameworkAgentSourceRegistry } from "#framework/sources/registry.js";import { defineAgent } from "#public/definitions/agent.js";import { defineChannel, GET, POST } from "#public/definitions/channel.js";import { defineHook } from "#public/definitions/hook.js";-import { defineTool, disableTool } from "#public/definitions/tool.js";+import { defineTool, disableTool } from "#tools/definition.js";function manifest() {return createAgentSourceManifest({diff --git a/packages/eve/src/compiler/normalize-skill.ts b/packages/eve/src/compiler/normalize-skill.tsindex fe61173dc..19cdfce99 100644--- a/packages/eve/src/compiler/normalize-skill.ts+++ b/packages/eve/src/compiler/normalize-skill.ts@@ -16,7 +16,7 @@ import {assertResolverOnlyDynamicSentinel,isDynamicSentinel,type DynamicToolEventName,-} from "#shared/dynamic-tool-definition.js";+} from "#dynamic/definition.js";/*** Compiled skill entry produced from one authored `skills/*` file.diff --git a/packages/eve/src/compiler/normalize-subagent.ts b/packages/eve/src/compiler/normalize-subagent.tsindex 2c160b7dd..0a347b26a 100644--- a/packages/eve/src/compiler/normalize-subagent.ts+++ b/packages/eve/src/compiler/normalize-subagent.ts@@ -6,9 +6,9 @@ import {expectString,} from "#internal/authored-module.js";import { EVE_SESSION_ROUTE_PATH } from "#protocol/routes.js";-import { serializeOutputSchema, type ToolSchemaSource } from "#shared/tool-schema.js";+import { serializeOutputSchema, type ToolSchemaSource } from "#tools/schema.js";import type { JsonObject } from "#shared/json.js";-import { isDynamicSentinel, type DynamicToolEventName } from "#shared/dynamic-tool-definition.js";+import { isDynamicSentinel, type DynamicToolEventName } from "#dynamic/definition.js";import type { LocalSubagentSourceRef } from "#discover/manifest.js";const ALLOWED_DYNAMIC_SUBAGENT_EVENTS = new Set<DynamicToolEventName>([diff --git a/packages/eve/src/public/connections/errors.test.ts b/packages/eve/src/connections/errors.test.tssimilarity index 99%rename from packages/eve/src/public/connections/errors.test.tsrename to packages/eve/src/connections/errors.test.tsindex bca4bc71e..d495483a5 100644--- a/packages/eve/src/public/connections/errors.test.ts+++ b/packages/eve/src/connections/errors.test.ts@@ -5,7 +5,7 @@ import {ConnectionAuthorizationRequiredError,isConnectionAuthorizationFailedError,isConnectionAuthorizationRequiredError,-} from "#public/connections/errors.js";+} from "#connections/errors.js";describe("ConnectionAuthorizationRequiredError", () => {it("sets name and connectionName", () => {diff --git a/packages/eve/src/connections/errors.ts b/packages/eve/src/connections/errors.tsnew file mode 100644index 000000000..deaa50331--- /dev/null+++ b/packages/eve/src/connections/errors.ts@@ -0,0 +1,158 @@+/**+ * Typed error classes for the connection authorization lifecycle.+ */++/**+ * User-facing authorization challenge payload.+ */+export interface ConnectionAuthorizationChallenge {+ /**+ * Optional URL the user should visit to complete authorization.+ * Serves as the redirect target, the verification URL in device+ * code flow, or the source for a QR code.+ */+ readonly url?: string;++ /**+ * Optional short code to display alongside `url` (device code flow).+ */+ readonly userCode?: string;++ /**+ * Optional ISO timestamp at which the authorization opportunity+ * expires. When provided, the runtime clamps the authorization deadline to+ * `min(configured_timeout, expiresAt)` so the turn cannot outlive+ * the challenge.+ */+ readonly expiresAt?: string;++ /**+ * Optional human-readable call to action. When no `url` is+ * available (e.g. CIBA, push-to-approve), this is what the channel+ * should show as the primary affordance.+ */+ readonly instructions?: string;++ /**+ * Optional human-readable provider name for sign-in UI (e.g.+ * `"Salesforce"`). Presentation-only: identity (the authorization+ * scope, token cache keys, callback URLs) stays the path-derived+ * name. Channels fall back to title-casing the scope name when+ * absent.+ */+ readonly displayName?: string;+}++/**+ * Options accepted by {@link ConnectionAuthorizationRequiredError}.+ */+export interface ConnectionAuthorizationRequiredErrorOptions {+ /**+ * Override for the default `Error.message`. Defaults to+ * `Connection "{name}" requires authorization.` when omitted.+ */+ readonly message?: string;+}++/**+ * Options accepted by {@link ConnectionAuthorizationFailedError}.+ */+export interface ConnectionAuthorizationFailedErrorOptions {+ /**+ * Override for the default `Error.message`. Defaults to+ * `Connection "{name}" authorization failed.` when omitted.+ */+ readonly message?: string;++ /**+ * Stable machine-readable code describing why authorization failed.+ *+ * The runtime surfaces this code on the `authorization.completed`+ * stream event and on the failed tool result the model sees. Use a+ * short kebab- or snake-cased string (e.g. `"access_denied"`,+ * `"invalid_grant"`).+ *+ * The runtime also emits a few reason codes itself, independently+ * of authored throws:+ *+ * - `"principal_required"`: a `principalType: "user"` connection+ * was invoked without an authenticated user principal. Terminal.+ * - `"app_not_installed"`: an authored `getToken` for a+ * `principalType: "app"` connection signalled the agent's own+ * credentials are missing. Terminal.+ */+ readonly reason?: string;++ /**+ * Controls whether the runtime re-prompts the user after this+ * failure.+ *+ * Defaults to `true`; set `false` for terminal cases such as user+ * denial (`reason: "access_denied"`).+ */+ readonly retryable?: boolean;+}++/**+ * Thrown from a connection's `getToken` when no valid credential is+ * available and authorization must be completed before the connection+ * can be used. Covers both interactive OAuth (the runtime emits+ * `authorization.required` and suspends the turn on a webhook) and+ * non-interactive / out-of-band flows such as static API keys (the+ * runtime emits `authorization.required` without suspending).+ */+export class ConnectionAuthorizationRequiredError extends Error {+ readonly connectionName: string;++ constructor(connectionName: string, options?: ConnectionAuthorizationRequiredErrorOptions) {+ super(options?.message ?? `Connection "${connectionName}" requires authorization.`);+ this.name = "ConnectionAuthorizationRequiredError";+ this.connectionName = connectionName;+ }+}++/**+ * Thrown when a connection's authorization fails.+ *+ * Retryable by default; pass `retryable: false` for terminal failures+ * where starting a fresh authorization flow would be wrong.+ */+export class ConnectionAuthorizationFailedError extends Error {+ readonly connectionName: string;+ readonly reason?: string;+ readonly retryable: boolean;++ constructor(connectionName: string, options?: ConnectionAuthorizationFailedErrorOptions) {+ super(options?.message ?? `Connection "${connectionName}" authorization failed.`);+ this.name = "ConnectionAuthorizationFailedError";+ this.connectionName = connectionName;+ this.reason = options?.reason;+ this.retryable = options?.retryable ?? true;+ }+}++/**+ * Type guard for {@link ConnectionAuthorizationRequiredError}.+ *+ * Uses `err.name` rather than `instanceof` because user code and+ * framework internals can end up with different class identities+ * after bundling (dual-instance hazard in Nitro output).+ */+export function isConnectionAuthorizationRequiredError(+ err: unknown,+): err is ConnectionAuthorizationRequiredError {+ return err instanceof Error && err.name === "ConnectionAuthorizationRequiredError";+}++/**+ * Type guard for {@link ConnectionAuthorizationFailedError}.+ *+ * Uses `err.name` rather than `instanceof` because user code and+ * framework internals can end up with different class identities+ * after bundling (dual-instance hazard in Nitro output).+ */+export function isConnectionAuthorizationFailedError(+ err: unknown,+): err is ConnectionAuthorizationFailedError {+ return err instanceof Error && err.name === "ConnectionAuthorizationFailedError";+}diff --git a/packages/eve/src/context/build-base-tool-context.ts b/packages/eve/src/context/build-base-tool-context.tsindex 14528a12b..fb42b09e4 100644--- a/packages/eve/src/context/build-base-tool-context.ts+++ b/packages/eve/src/context/build-base-tool-context.ts@@ -1,7 +1,7 @@import { buildCallbackContext } from "#context/build-callback-context.js";-import type { SessionContext } from "#public/definitions/callback-context.js";+import type { SessionContext } from "#context/session-context.js";import { bindSandboxAbortSignal } from "#execution/sandbox/abort-bound-session.js";-import type { ToolExecuteOptions } from "#shared/tool-definition.js";+import type { ToolExecuteOptions } from "#tools/definition.js";/** Base context shared by tool executors. */export type BaseToolContext = SessionContext & {diff --git a/packages/eve/src/context/build-callback-context.ts b/packages/eve/src/context/build-callback-context.tsindex ffe97cb4b..abe7bb2ab 100644--- a/packages/eve/src/context/build-callback-context.ts+++ b/packages/eve/src/context/build-callback-context.ts@@ -1,4 +1,4 @@-import type { SessionContext } from "#public/definitions/callback-context.js";+import type { SessionContext } from "#context/session-context.js";import type { SkillHandle } from "#shared/skill-types.js";import type { RuntimeSandboxSession, SandboxSession } from "#shared/sandbox-session.js";import { createSandboxSkillHandle } from "#runtime/skills/sandbox-access.js";diff --git a/packages/eve/src/context/build-dynamic-tools.ts b/packages/eve/src/context/build-dynamic-tools.tsindex ff1f6a956..1f7c01d2d 100644--- a/packages/eve/src/context/build-dynamic-tools.ts+++ b/packages/eve/src/context/build-dynamic-tools.ts@@ -14,13 +14,13 @@ import type {ApprovalResponseContext,ApprovalResponseDecision,ApprovalStatus,-} from "#public/definitions/approval.js";+} from "#approval/definition.js";import {callDurableDynamicCallback,lookupDurableDynamicCallback,type DurableDynamicCallbackPhase,-} from "#shared/durable-dynamic-tool-callbacks.js";-import { toInputSchema, toOutputSchema } from "#shared/tool-schema.js";+} from "#tools/durable-callbacks.js";+import { toInputSchema, toOutputSchema } from "#tools/schema.js";const log = createLogger("dynamic-tools");diff --git a/packages/eve/src/context/dynamic-instruction-lifecycle.test.ts b/packages/eve/src/context/dynamic-instruction-lifecycle.test.tsindex f1df13503..f42e36229 100644--- a/packages/eve/src/context/dynamic-instruction-lifecycle.test.ts+++ b/packages/eve/src/context/dynamic-instruction-lifecycle.test.ts@@ -23,7 +23,7 @@ import {} from "#context/keys.js";import type { ResolvedDynamicInstructionsResolver } from "#runtime/types.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";-import type { DynamicResolveContext } from "#shared/dynamic-tool-definition.js";+import type { DynamicResolveContext } from "#dynamic/definition.js";function createResolver(slug: string,diff --git a/packages/eve/src/context/dynamic-instruction-lifecycle.ts b/packages/eve/src/context/dynamic-instruction-lifecycle.tsindex be5a77803..4eb552a8d 100644--- a/packages/eve/src/context/dynamic-instruction-lifecycle.ts+++ b/packages/eve/src/context/dynamic-instruction-lifecycle.ts@@ -1,9 +1,7 @@import type { ModelMessage, SystemModelMessage } from "ai";-import {- ALLOWED_DYNAMIC_INSTRUCTION_EVENTS,- isBrandedInstructionsEntry,-} from "#shared/dynamic-tool-definition.js";+import { ALLOWED_DYNAMIC_INSTRUCTION_EVENTS } from "#dynamic/definition.js";+import { isBrandedInstructionsEntry } from "#shared/instructions-definition.js";import type { InstructionsDefinition } from "#public/definitions/instructions.js";import { normalizeInstructionsDefinition } from "#internal/authored-definition/core.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";diff --git a/packages/eve/src/context/dynamic-model-lifecycle.test.ts b/packages/eve/src/context/dynamic-model-lifecycle.test.tsindex 990e59539..95dd1060f 100644--- a/packages/eve/src/context/dynamic-model-lifecycle.test.ts+++ b/packages/eve/src/context/dynamic-model-lifecycle.test.ts@@ -13,7 +13,7 @@ import {SessionDynamicModelReferenceKey,TurnDynamicModelReferenceKey,} from "#context/keys.js";-import { defineDynamic } from "#public/definitions/tool.js";+import { defineDynamic } from "#dynamic/definition.js";import {createSessionStartedEvent,createStepStartedEvent,diff --git a/packages/eve/src/context/dynamic-model-lifecycle.ts b/packages/eve/src/context/dynamic-model-lifecycle.tsindex 95578b4a4..813b9d268 100644--- a/packages/eve/src/context/dynamic-model-lifecycle.ts+++ b/packages/eve/src/context/dynamic-model-lifecycle.ts@@ -21,7 +21,7 @@ import {type ResolvedRuntimeModelSelection,type RuntimeModelResolutionScope,} from "#runtime/agent/resolve-model.js";-import type { DynamicToolEventName } from "#shared/dynamic-tool-definition.js";+import type { DynamicToolEventName } from "#dynamic/definition.js";import { toErrorMessage } from "#shared/errors.js";const ALLOWED_DYNAMIC_MODEL_EVENTS = new Set<DynamicToolEventName>([diff --git a/packages/eve/src/context/dynamic-resolve-context.ts b/packages/eve/src/context/dynamic-resolve-context.tsindex f447876a1..732213866 100644--- a/packages/eve/src/context/dynamic-resolve-context.ts+++ b/packages/eve/src/context/dynamic-resolve-context.ts@@ -1,6 +1,6 @@import type { ModelMessage } from "ai";-import type { DynamicResolveContext } from "#shared/dynamic-tool-definition.js";+import type { DynamicResolveContext } from "#dynamic/definition.js";import type { AlsContext } from "#context/container.js";import {AuthKey,diff --git a/packages/eve/src/context/dynamic-skill-lifecycle.ts b/packages/eve/src/context/dynamic-skill-lifecycle.tsindex 1861bb100..d24284f06 100644--- a/packages/eve/src/context/dynamic-skill-lifecycle.ts+++ b/packages/eve/src/context/dynamic-skill-lifecycle.ts@@ -1,10 +1,7 @@import type { ModelMessage } from "ai";-import {- ALLOWED_DYNAMIC_SKILL_EVENTS,- isBrandedSkillEntry,-} from "#shared/dynamic-tool-definition.js";-import type { SkillPackageDefinition } from "#shared/skill-definition.js";+import { ALLOWED_DYNAMIC_SKILL_EVENTS } from "#dynamic/definition.js";+import { isBrandedSkillEntry, type SkillPackageDefinition } from "#shared/skill-definition.js";import {type MaterializableSkillPackage,normalizeSkillPackage,diff --git a/packages/eve/src/context/dynamic-tool-lifecycle.test.ts b/packages/eve/src/context/dynamic-tool-lifecycle.test.tsindex 410ac84f0..a4a4c9a12 100644--- a/packages/eve/src/context/dynamic-tool-lifecycle.test.ts+++ b/packages/eve/src/context/dynamic-tool-lifecycle.test.ts@@ -1,12 +1,12 @@import { asSchema } from "ai";import { describe, expect, it, vi } from "vitest";-import type { DynamicToolEntry } from "#shared/dynamic-tool-definition.js";+import type { DynamicToolEntry } from "#tools/dynamic.js";import type { DurableDynamicToolMetadata } from "#context/keys.js";-import { resolveApprovalPolicy, type ApprovalContext } from "#public/definitions/approval.js";-import { defineTool, type ToolContext } from "#public/definitions/tool.js";+import { resolveApprovalPolicy, type ApprovalContext } from "#approval/definition.js";+import { defineTool, type ToolContext } from "#tools/definition.js";import type { JsonObject } from "#shared/json.js";-import { serializeOutputSchema, type ToolSchema } from "#shared/tool-schema.js";+import { serializeOutputSchema, type ToolSchema } from "#tools/schema.js";vi.mock("#context/build-callback-context.js", () => ({buildCallbackContext: () => ({@@ -37,7 +37,7 @@ import {lookupDurableDynamicCallback,registerDurableDynamicCallback,stampDurableDynamicToolCallbacks,-} from "#shared/durable-dynamic-tool-callbacks.js";+} from "#tools/durable-callbacks.js";import type { ResolvedDynamicToolResolver } from "#runtime/types.js";import { createSessionStartedEvent, type UnstampedMessageStreamEvent } from "#protocol/message.js";diff --git a/packages/eve/src/context/dynamic-tool-lifecycle.ts b/packages/eve/src/context/dynamic-tool-lifecycle.tsindex ccae92af3..bfd11935b 100644--- a/packages/eve/src/context/dynamic-tool-lifecycle.ts+++ b/packages/eve/src/context/dynamic-tool-lifecycle.ts@@ -14,11 +14,8 @@ import { buildResolveContext } from "#context/dynamic-resolve-context.js";import type { HarnessToolDefinition } from "#harness/execute-tool.js";import { createLogger } from "#internal/logging.js";import type { SessionStartedStreamEvent, UnstampedMessageStreamEvent } from "#protocol/message.js";-import type { DynamicToolEntry } from "#shared/dynamic-tool-definition.js";-import {- ALLOWED_DYNAMIC_TOOL_EVENTS,- isBrandedToolEntry,-} from "#shared/dynamic-tool-definition.js";+import { ALLOWED_DYNAMIC_TOOL_EVENTS } from "#dynamic/definition.js";+import { isBrandedToolEntry, type DynamicToolEntry } from "#tools/dynamic.js";import {hasUnregisteredDurableDynamicCallbacks,type DurableDynamicCallbackPhase,@@ -27,10 +24,10 @@ import {type StampedDurableDynamicCallback,readDurableDynamicToolCallbacks,registerDurableDynamicCallback,-} from "#shared/durable-dynamic-tool-callbacks.js";+} from "#tools/durable-callbacks.js";import { toErrorMessage } from "#shared/errors.js";import { parseJsonObject } from "#shared/json.js";-import { serializeInputSchema, serializeOutputSchema } from "#shared/tool-schema.js";+import { serializeInputSchema, serializeOutputSchema } from "#tools/schema.js";import type { ResolvedDynamicToolResolver } from "#runtime/types.js";const log = createLogger("dynamic-tools");diff --git a/packages/eve/src/context/keys.ts b/packages/eve/src/context/keys.tsindex d7f507583..b13918770 100644--- a/packages/eve/src/context/keys.ts+++ b/packages/eve/src/context/keys.ts@@ -21,7 +21,7 @@ import { ContextKey } from "#context/key.js";import { SESSION_CALLBACK_CONTEXT_KEY_NAME } from "#context/key-names.js";import type { InstrumentationChannelDeliveryRef } from "#harness/instrumentation/lifecycle.js";import type { HandleEventFn } from "#harness/types.js";-import type { DurableDynamicToolCallbacks } from "#shared/durable-dynamic-tool-callbacks.js";+import type { DurableDynamicToolCallbacks } from "#tools/durable-callbacks.js";import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";import type { DynamicRemoteAgentConfig } from "#runtime/subagents/dynamic-remote-agent-config.js";import type { SandboxAccess } from "#sandbox/state.js";diff --git a/packages/eve/src/context/session-context.ts b/packages/eve/src/context/session-context.tsnew file mode 100644index 000000000..596ef0a94--- /dev/null+++ b/packages/eve/src/context/session-context.ts@@ -0,0 +1,36 @@+import type { SkillHandle } from "#shared/skill-types.js";+import type { RuntimeSandboxSession } from "#shared/sandbox-session.js";+import type { SessionAuth, SessionParent, SessionTurn } from "#context/keys.js";++export type { SessionAuth, SessionParent, SessionTurn };++/**+ * Shared runtime context available to all authored callbacks that run+ * inside the ALS-scoped harness step (tools, hooks, channel events).+ *+ * Non-ALS callbacks (schedule `run`, sandbox `bootstrap`/`onSession`,+ * instrumentation `setup`) do not receive this context. They get+ * domain-specific arguments instead.+ */+export interface SessionContext {+ /**+ * Active session metadata for the callback's exact durable session.+ */+ readonly session: {+ readonly id: string;+ readonly auth: SessionAuth;+ readonly turn: SessionTurn;+ readonly parent?: SessionParent;+ };++ /**+ * Resolves the session's sandbox. Throws when no sandbox is available+ * in the current authored runtime context.+ */+ getSandbox(): Promise<RuntimeSandboxSession>;++ /**+ * Returns a {@link SkillHandle} for the named authored skill.+ */+ getSkill(identifier: string): SkillHandle;+}diff --git a/packages/eve/src/dynamic/definition.ts b/packages/eve/src/dynamic/definition.tsnew file mode 100644index 000000000..38f7f83fe--- /dev/null+++ b/packages/eve/src/dynamic/definition.ts@@ -0,0 +1,173 @@+import type { ModelMessage } from "ai";++import type { SessionAuth } from "#context/keys.js";+import { stampDefinitionKey } from "#internal/authored-definition/source-identity.js";+import type { UnstampedMessageStreamEvent } from "#protocol/message.js";++/**+ * Stream event types allowed for dynamic tool resolvers. Dispatch+ * supports any event; this extract restricts the public surface until+ * more events are validated.+ */+export type DynamicToolEventName = Extract<+ UnstampedMessageStreamEvent["type"],+ "session.started" | "turn.started" | "step.started"+>;++export const ALLOWED_DYNAMIC_TOOL_EVENTS: ReadonlySet<string> = new Set<DynamicToolEventName>([+ "session.started",+ "turn.started",+ "step.started",+]);++/**+ * Instructions and skills are restricted to session/turn boundaries.+ * Keeping their resolved context stable within a turn avoids changing the+ * model input between tool-loop steps.+ */+export const ALLOWED_DYNAMIC_INSTRUCTION_EVENTS: ReadonlySet<string> =+ new Set<DynamicToolEventName>(["session.started", "turn.started"]);++export const ALLOWED_DYNAMIC_SKILL_EVENTS: ReadonlySet<string> = new Set<DynamicToolEventName>([+ "session.started",+ "turn.started",+]);++/**+ * Context passed to a dynamic resolver's event handler.+ *+ * Exposes read-only session identity, auth, and channel metadata. State+ * is not exposed here; resolvers read it through `defineState` handles or+ * the session context inside tool `execute` functions.+ */+export interface DynamicResolveContext {+ readonly session: {+ readonly id: string;+ readonly auth: SessionAuth;+ };+ /** Channel metadata for the request that triggered this resolve. */+ readonly channel: {+ /** Channel type that produced the request (e.g. `"slack"`, `"http"`), when known. */+ readonly kind?: string;+ /** Channel-owned resume handle for the conversation, when the channel supplies one. */+ readonly continuationToken?: string;+ /** Free-form channel-specific metadata attached to the request. */+ readonly metadata?: Readonly<Record<string, unknown>>;+ };+ /** Conversation history visible at this resolve point, oldest first. */+ readonly messages: readonly ModelMessage[];+}++/**+ * Base event handler map accepted by `defineDynamic`. Intentionally+ * wide so it accepts both tool-returning and skill-returning handlers:+ * the slot directory (tools/ vs skills/) determines the required return,+ * validated at runtime by the respective resolver.+ */+export type DynamicEvents<TResult = unknown> = {+ readonly [K in DynamicToolEventName]?: (+ event: unknown,+ ctx: DynamicResolveContext,+ ) => TResult | Promise<TResult>;+};++type DynamicEventMapHandler<TEvents extends DynamicEvents> = Extract<+ NonNullable<TEvents[keyof TEvents]>,+ (...args: never[]) => unknown+>;+type DynamicEventMapResult<TEvents extends DynamicEvents> = Awaited<+ ReturnType<DynamicEventMapHandler<TEvents>>+>;++/**+ * Marker discriminator for a `defineDynamic({ events })` export.+ */+export const DYNAMIC_SENTINEL_KIND = "eve:dynamic" as const;++/**+ * Return value of `defineDynamic`: the runtime shape of a dynamic export,+ * stamped with a sentinel kind the compiler/normalizer detects.+ */+export type DynamicSentinel<TResult = unknown> = {+ readonly kind: typeof DYNAMIC_SENTINEL_KIND;+ readonly events: DynamicEvents<TResult>;+};++/**+ * Defines a dynamic resolver evaluated at runtime from stream-event+ * handlers. It is shared across tools, skills, and agent definitions;+ * the directory it is authored in (not this function) decides what each+ * handler must return and which events are honored. The file's path-derived+ * slug names the single-entry case; a `Record<string, ...>` return names+ * entries `slug__key`. Return `null` to contribute nothing for that event.+ *+ * Per-slot return shape:+ * - `agent/tools/`: return a single `defineTool(...)`, a+ * `Record<string, defineTool(...)>`, or `null`.+ * - `agent/skills/`: return a single `defineSkill(...)`, a+ * `Record<string, defineSkill(...)>`, or `null`.+ * - `agent/subagents/<name>/agent.ts`: return `defineAgent(...)` to configure+ * and expose the subagent, or `null` to omit it.+ *+ * Per-slot events: tools resolvers run at `session.started`,+ * `turn.started`, and `step.started`. Skills resolvers run only at+ * `session.started` and `turn.started`; the runtime never invokes a+ * handler keyed on `step.started` in that slot. Dynamic subagents run at+ * `session.started` and `turn.started` only.+ *+ * ```ts+ * import { defineDynamic, defineTool } from "eve/tools";+ * import { z } from "zod";+ *+ * export default defineDynamic({+ * events: {+ * "session.started": async (event, ctx) => ({+ * export: defineTool({+ * description: "Export data",+ * inputSchema: z.object({ format: z.string() }),+ * async execute(input) {+ * return doExport(input.format);+ * },+ * }),+ * }),+ * },+ * });+ * ```+ *+ * A single return is named after the file slug. A map names each entry by its+ * bare key — there is no automatic slug prefix, so namespace keys yourself+ * (e.g. `team__playbook`) when a bare name might collide. A dynamic tool/skill+ * whose name matches an authored one overrides it; two dynamic resolvers+ * emitting the same name is an error.+ */+export function defineDynamic<const TEvents extends DynamicEvents>(definition: {+ readonly events: TEvents;+}): DynamicSentinel<DynamicEventMapResult<TEvents>>;+export function defineDynamic<TResult = unknown>(definition: {+ readonly events: DynamicEvents<TResult>;+}): DynamicSentinel<TResult> {+ const sentinel = {+ kind: DYNAMIC_SENTINEL_KIND,+ events: definition.events,+ } as DynamicSentinel<TResult>;+ stampDefinitionKey(sentinel, `dynamic:${Object.keys(definition.events).join(",")}`);+ return sentinel;+}++export function assertResolverOnlyDynamicSentinel(+ sentinel: DynamicSentinel,+ message: string,+): void {+ const unknownKeys = Object.keys(sentinel).filter((key) => key !== "events" && key !== "kind");+ if (unknownKeys.length > 0) {+ throw new Error(`${message} Unknown key(s): ${unknownKeys.join(", ")}.`);+ }+}++export function isDynamicSentinel(value: unknown): value is DynamicSentinel {+ return (+ typeof value === "object" &&+ value !== null &&+ (value as { kind?: unknown }).kind === DYNAMIC_SENTINEL_KIND+ );+}diff --git a/packages/eve/src/evals/autoevals-client.ts b/packages/eve/src/evals/autoevals-client.tsindex 2ed47b724..1d8a558e2 100644--- a/packages/eve/src/evals/autoevals-client.ts+++ b/packages/eve/src/evals/autoevals-client.ts@@ -8,7 +8,7 @@ import {import { Factuality } from "autoevals";import { resolveProviderHeaders } from "#internal/gateway.js";-import { toInputSchema } from "#shared/tool-schema.js";+import { toInputSchema } from "#tools/schema.js";/*** The OpenAI-shaped client surface autoevals expects. Extracted from thediff --git a/packages/eve/src/execution/authorization-callback-match.ts b/packages/eve/src/execution/authorization-callback-match.tsindex d780f3538..78d978a26 100644--- a/packages/eve/src/execution/authorization-callback-match.ts+++ b/packages/eve/src/execution/authorization-callback-match.ts@@ -1,6 +1,6 @@import type { DeliverPayload } from "#channel/types.js";import type { AuthorizationResult, PendingAuthorizationState } from "#harness/authorization.js";-import type { ConnectionAuthorizationChallenge } from "#public/connections/errors.js";+import type { ConnectionAuthorizationChallenge } from "#connections/errors.js";import type { AuthorizationCallback } from "#shared/connection-types.js";export interface MatchedAuthorizationCallback {diff --git a/packages/eve/src/execution/connection-auth-tool-result.ts b/packages/eve/src/execution/connection-auth-tool-result.tsindex 451fffccf..e68c5ddd1 100644--- a/packages/eve/src/execution/connection-auth-tool-result.ts+++ b/packages/eve/src/execution/connection-auth-tool-result.ts@@ -1,4 +1,4 @@-import type { JsonValue } from "#public/types/json.js";+import type { JsonValue } from "#shared/json.js";export function normalizeConnectionAuthToolResult(result: unknown): JsonValue {if (result === undefined) return null;diff --git a/packages/eve/src/execution/create-session-step.test.ts b/packages/eve/src/execution/create-session-step.test.tsindex f06b2fc27..b5c9de415 100644--- a/packages/eve/src/execution/create-session-step.test.ts+++ b/packages/eve/src/execution/create-session-step.test.ts@@ -3,7 +3,7 @@ import { describe, expect, it, vi } from "vitest";import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";import { DEFAULT_ROOT_MAX_INPUT_TOKENS_PER_SESSION } from "#execution/session.js";import { createSessionStep } from "#execution/create-session-step.js";-import { TASK_UPDATE_TOOL_NAME } from "#shared/task-tool.js";+import { TASK_UPDATE_TOOL_NAME } from "#tools/framework/task-contract.js";import type { RuntimeTurnAgent } from "#runtime/agent/bootstrap.js";vi.mock("#runtime/sessions/compiled-agent-cache.js", () => ({diff --git a/packages/eve/src/execution/create-session-step.ts b/packages/eve/src/execution/create-session-step.tsindex 135de2cd4..fe4c3ac95 100644--- a/packages/eve/src/execution/create-session-step.ts+++ b/packages/eve/src/execution/create-session-step.ts@@ -14,7 +14,7 @@ import type { JsonObject } from "#shared/json.js";import { resolveEffectiveAgentRuntimeFromConfig } from "#execution/effective-agent-config.js";import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";import { TASK_UPDATE_SESSION_INSTRUCTION } from "#execution/tasks/child/instructions.js";-import { TASK_UPDATE_TOOL_NAME } from "#shared/task-tool.js";+import { TASK_UPDATE_TOOL_NAME } from "#tools/framework/task-contract.js";/*** Result returned by {@link createSessionStep}.diff --git a/packages/eve/src/execution/delegation-tool.ts b/packages/eve/src/execution/delegation-tool.tsindex 7931ff9f6..61b89f9f1 100644--- a/packages/eve/src/execution/delegation-tool.ts+++ b/packages/eve/src/execution/delegation-tool.ts@@ -8,7 +8,7 @@ import {toInputSchema,toOutputSchema,type ToolSchemaSource,-} from "#shared/tool-schema.js";+} from "#tools/schema.js";type HarnessDelegationTool = Pick<PreparedRuntimeDelegationTool,diff --git a/packages/eve/src/execution/node-step.test.ts b/packages/eve/src/execution/node-step.test.tsindex 8a666e0c0..ea9976154 100644--- a/packages/eve/src/execution/node-step.test.ts+++ b/packages/eve/src/execution/node-step.test.ts@@ -16,7 +16,7 @@ import { createExecutionNodeStep, createNodeHarnessTools } from "#execution/nodeimport { countLocalSubagentCalls } from "#execution/tools/subagent/local.js";import { createSession } from "#execution/session.js";import { createStubSandboxRegistry } from "#internal/testing/stub-sandbox-registry.js";-import { toInputSchema } from "#shared/tool-schema.js";+import { toInputSchema } from "#tools/schema.js";vi.mock("ai", () => ({ToolLoopAgent: vi.fn(),diff --git a/packages/eve/src/execution/node-step.ts b/packages/eve/src/execution/node-step.tsindex be77d32fb..31a717225 100644--- a/packages/eve/src/execution/node-step.ts+++ b/packages/eve/src/execution/node-step.ts@@ -14,21 +14,21 @@ import { resolveInstalledPackageInfo } from "#internal/application/package.js";import { getInstrumentationRuntime } from "#harness/instrumentation/runtime.js";import { createLogger } from "#internal/logging.js";import type { RuntimeIdentity } from "#protocol/message.js";-import { UNSPECIFIED_INPUT_SCHEMA } from "#shared/tool-schema.js";+import { UNSPECIFIED_INPUT_SCHEMA } from "#tools/schema.js";import type { RunMode } from "#shared/run-mode.js";import {resolveRuntimeModelReference,type RuntimeModelResolutionScope,} from "#runtime/agent/resolve-model.js";import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";-import { AGENT_TOOL_DESCRIPTION, AGENT_TOOL_NAME } from "#shared/agent-tool.js";+import { AGENT_TOOL_DESCRIPTION, AGENT_TOOL_NAME } from "#tools/framework/agent-contract.js";import { createTaskToolHarnessDefinitions } from "#execution/tools/tasks.js";import type { ResolvedRuntimeAgentNode } from "#runtime/graph.js";import type { HistoryViewProjector, PreparedHistoryView } from "#shared/history-view.js";import {PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA,SUBAGENT_TOOL_INPUT_SCHEMA,-} from "#shared/agent-tool.js";+} from "#tools/framework/agent-contract.js";import type { PreparedRuntimeTool } from "#runtime/sessions/turn.js";import { findRegisteredRuntimeTool } from "#runtime/tools/registry.js";diff --git a/packages/eve/src/execution/sandbox/bash-tool.test.ts b/packages/eve/src/execution/sandbox/bash.test.tssimilarity index 97%rename from packages/eve/src/execution/sandbox/bash-tool.test.tsrename to packages/eve/src/execution/sandbox/bash.test.tsindex 643d177ad..3febee27b 100644--- a/packages/eve/src/execution/sandbox/bash-tool.test.ts+++ b/packages/eve/src/execution/sandbox/bash.test.ts@@ -3,7 +3,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";import { EVE_DEV_ENV_FLAG } from "#internal/application/optional-package-install.js";import type { SandboxCommandResult, SandboxSession } from "#shared/sandbox-session.js";-import { executeBashOnSandbox } from "./bash-tool.js";+import { executeBashOnSandbox } from "./bash.js";describe("executeBashOnSandbox", () => {const previousDevFlag = process.env[EVE_DEV_ENV_FLAG];diff --git a/packages/eve/src/execution/sandbox/bash-tool.ts b/packages/eve/src/execution/sandbox/bash.tssimilarity index 96%rename from packages/eve/src/execution/sandbox/bash-tool.tsrename to packages/eve/src/execution/sandbox/bash.tsindex 5212a5e00..4ea926c3c 100644--- a/packages/eve/src/execution/sandbox/bash-tool.ts+++ b/packages/eve/src/execution/sandbox/bash.ts@@ -42,8 +42,8 @@ export interface BashResult {* (where errors and final results typically appear) within the shared* {@link MAX_OUTPUT_LINES} / {@link MAX_OUTPUT_BYTES} limits.*- * Used by the framework `bash` tool and by author tools constructed via- * `defineBashTool`. Centralizing the executor here keeps the error+ * Used by the framework `bash` tool and authored wrappers around its+ * exported definition. Centralizing the executor here keeps the error* messages and result shape identical across all bash-style tools.*/export async function executeBashOnSandbox(diff --git a/packages/eve/src/execution/sandbox/read-file-tool.ts b/packages/eve/src/execution/sandbox/read-file.tssimilarity index 98%rename from packages/eve/src/execution/sandbox/read-file-tool.tsrename to packages/eve/src/execution/sandbox/read-file.tsindex 19ed93ad2..92bcac4c0 100644--- a/packages/eve/src/execution/sandbox/read-file-tool.ts+++ b/packages/eve/src/execution/sandbox/read-file.ts@@ -49,8 +49,8 @@ export interface ReadFileResult {* (offset, limit, line numbering, truncation), and persists a full-file* stamp into durable read-file state for stale-write detection.*- * Used by the framework `read_file` tool and by author tools constructed- * via `defineReadFileTool`.+ * Used by the framework `read_file` tool and authored wrappers around its+ * exported definition.*/export async function executeReadFileOnSandbox(sandbox: SandboxSession,diff --git a/packages/eve/src/execution/sandbox/truncate-output.ts b/packages/eve/src/execution/sandbox/truncate-output.tsindex 6e1cf2606..c6c590808 100644--- a/packages/eve/src/execution/sandbox/truncate-output.ts+++ b/packages/eve/src/execution/sandbox/truncate-output.ts@@ -130,7 +130,7 @@ export function capLineLength(line: string): string {/*** Counts logical lines, treating a trailing empty element from- * `split("\n")` as not a separate line (consistent with read-file-tool).+ * `split("\n")` as not a separate line (consistent with the read-file tool).*/function countLogicalLines(lines: readonly string[]): number {if (lines.length > 0 && lines[lines.length - 1] === "") {diff --git a/packages/eve/src/execution/sandbox/write-file-tool.ts b/packages/eve/src/execution/sandbox/write-file.tssimilarity index 97%rename from packages/eve/src/execution/sandbox/write-file-tool.tsrename to packages/eve/src/execution/sandbox/write-file.tsindex 38632f7f4..c57f4c511 100644--- a/packages/eve/src/execution/sandbox/write-file-tool.ts+++ b/packages/eve/src/execution/sandbox/write-file.ts@@ -38,8 +38,8 @@ export interface WriteFileResult {* Writes one text file to the sandbox with read-before-write* enforcement and stale-read detection for existing files.*- * Used by the framework `write_file` tool and by author tools- * constructed via `defineWriteFileTool`.+ * Used by the framework `write_file` tool and authored wrappers around its+ * exported definition.*/export async function executeWriteFileOnSandbox(sandbox: SandboxSession,diff --git a/packages/eve/src/execution/tasks/parent/delegate.ts b/packages/eve/src/execution/tasks/parent/delegate.tsindex 3ca30f179..312e9d599 100644--- a/packages/eve/src/execution/tasks/parent/delegate.ts+++ b/packages/eve/src/execution/tasks/parent/delegate.ts@@ -17,7 +17,7 @@ import { sessionCommandHookToken } from "#execution/session-command-token.js";import { deriveAgentOperationId } from "#harness/handles/operation-id.js";import type { RuntimeSubagentChildResult } from "#shared/action-types.js";import type { JsonValue } from "#shared/json.js";-import type { TaskExecutorBinding } from "#shared/tool-task.js";+import type { TaskExecutorBinding } from "#tools/task.js";import { recordSessionTask } from "#tasks/session-index.js";import { deriveTaskInboxToken, deriveTaskId } from "#tasks/task-id.js";import {diff --git a/packages/eve/src/execution/tasks/parent/dispatch.ts b/packages/eve/src/execution/tasks/parent/dispatch.tsindex c4290f013..eac5d8d24 100644--- a/packages/eve/src/execution/tasks/parent/dispatch.ts+++ b/packages/eve/src/execution/tasks/parent/dispatch.ts@@ -27,7 +27,7 @@ import {TASK_CANCEL_TOOL_NAME,TASK_TOOL_NAMES,TASK_UPDATE_TOOL_NAME,-} from "#shared/task-tool.js";+} from "#tools/framework/task-contract.js";import type { SessionTaskIndexEntry } from "#tasks/session-index.js";import {isTerminalTaskStatus,diff --git a/packages/eve/src/execution/tasks/parent/tool-execution.test.ts b/packages/eve/src/execution/tasks/parent/tool-execution.test.tsindex 552ce06d6..c68a592f5 100644--- a/packages/eve/src/execution/tasks/parent/tool-execution.test.ts+++ b/packages/eve/src/execution/tasks/parent/tool-execution.test.ts@@ -18,8 +18,8 @@ import {type AgentAddress,type AgentIdentity,} from "#harness/handles/store.js";-import { defineTool, type TaskExec, type ToolContext } from "#public/definitions/tool.js";-import { toInputSchema } from "#shared/tool-schema.js";+import { defineTool, type TaskExec, type ToolContext } from "#tools/definition.js";+import { toInputSchema } from "#tools/schema.js";import { getSessionTaskIndex } from "#tasks/session-index.js";import { createSubagentExecutorBinding } from "#tasks/types.js";diff --git a/packages/eve/src/execution/tasks/parent/tool-execution.ts b/packages/eve/src/execution/tasks/parent/tool-execution.tsindex ad0528b4f..3b13afd0d 100644--- a/packages/eve/src/execution/tasks/parent/tool-execution.ts+++ b/packages/eve/src/execution/tasks/parent/tool-execution.ts@@ -17,13 +17,13 @@ import {import { createEveCallbackRoutePath } from "#protocol/routes.js";import { isAsyncIterable } from "#shared/async-iterable.js";import { parseJsonValue } from "#shared/json.js";-import type { ToolExecuteOptions } from "#shared/tool-definition.js";+import type { ToolExecuteOptions } from "#tools/definition.js";import {createTaskDelegated,isTaskDelegated,type TaskExec,type TaskSendCommand,-} from "#shared/tool-task.js";+} from "#tools/task.js";import { recordTaskAgentAddress } from "#harness/handles/transitions.js";import { BundleKey, type CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";import { recordSessionTask } from "#tasks/session-index.js";diff --git a/packages/eve/src/execution/tool-auth.integration.test.ts b/packages/eve/src/execution/tool-auth.integration.test.tsindex 66a229976..4b5a6ea0c 100644--- a/packages/eve/src/execution/tool-auth.integration.test.ts+++ b/packages/eve/src/execution/tool-auth.integration.test.ts@@ -9,9 +9,9 @@ import {PendingAuthorizationResultKey,isAuthorizationSignal,} from "#harness/authorization.js";-import { isConnectionAuthorizationFailedError } from "#public/connections/errors.js";+import { isConnectionAuthorizationFailedError } from "#connections/errors.js";import { createTestRuntime } from "#internal/testing/app-harness.js";-import type { ToolContext } from "#public/definitions/tool.js";+import type { ToolContext } from "#tools/definition.js";import type {AuthorizationDefinition,ConnectionPrincipal,diff --git a/packages/eve/src/execution/tool-auth.ts b/packages/eve/src/execution/tool-auth.tsindex b4ecfde25..feeea49fd 100644--- a/packages/eve/src/execution/tool-auth.ts+++ b/packages/eve/src/execution/tool-auth.ts@@ -18,9 +18,9 @@ import {ConnectionAuthorizationFailedError,ConnectionAuthorizationRequiredError,isConnectionAuthorizationRequiredError,-} from "#public/connections/errors.js";-import type { ApprovalResponseAuth } from "#public/definitions/approval.js";-import type { ToolAuthOptions, ToolAuthProvider, ToolContext } from "#public/definitions/tool.js";+} from "#connections/errors.js";+import type { ApprovalResponseAuth } from "#approval/definition.js";+import type { ToolAuthOptions, ToolAuthProvider, ToolContext } from "#tools/definition.js";import { type AuthorizationChallenge, requestAuthorization } from "#harness/authorization.js";import {type AuthorizationDefinition,@@ -35,8 +35,8 @@ import {startScopedAuthorization,type ScopedAuthorization,} from "#runtime/connections/scoped-authorization.js";-import type { ToolExecuteOptions } from "#shared/tool-definition.js";-import type { TaskExec } from "#shared/tool-task.js";+import type { ToolExecuteOptions } from "#tools/definition.js";+import type { TaskExec } from "#tools/task.js";import { isAsyncIterable } from "#shared/async-iterable.js";/**diff --git a/packages/eve/src/execution/tools/connection-search.test.ts b/packages/eve/src/execution/tools/connection-search.test.tsindex a13c95c6b..ac2558c62 100644--- a/packages/eve/src/execution/tools/connection-search.test.ts+++ b/packages/eve/src/execution/tools/connection-search.test.ts@@ -8,18 +8,15 @@ import {isAuthorizationSignal,PendingAuthorizationResultKey,} from "#harness/authorization.js";-import { ConnectionAuthorizationRequiredError } from "#public/connections/errors.js";-import type { ToolContext } from "#public/definitions/tool.js";+import { ConnectionAuthorizationRequiredError } from "#connections/errors.js";+import type { ToolContext } from "#tools/definition.js";import type { ConnectionToolMetadata } from "#shared/connection-types.js";import type { ConnectionRegistry } from "#runtime/connections/registry-types.js";-import connectionSearch from "#public/tools/connection-search.js";+import connectionSearch from "#tools/framework/connection-search.js";import type { ResolvedConnectionDefinition } from "#runtime/types.js";-import {- isBrandedToolEntry,- type DynamicResolveContext,- type DynamicToolSet,-} from "#shared/dynamic-tool-definition.js";-import { readDurableDynamicToolCallbacks } from "#shared/durable-dynamic-tool-callbacks.js";+import { isBrandedToolEntry, type DynamicToolSet } from "#tools/dynamic.js";+import type { DynamicResolveContext } from "#dynamic/definition.js";+import { readDurableDynamicToolCallbacks } from "#tools/durable-callbacks.js";function connection(name: string): ResolvedConnectionDefinition {return {diff --git a/packages/eve/src/execution/tools/connection-search.ts b/packages/eve/src/execution/tools/connection-search.tsindex 61802ba6f..e7ebfcddc 100644--- a/packages/eve/src/execution/tools/connection-search.ts+++ b/packages/eve/src/execution/tools/connection-search.ts@@ -13,17 +13,17 @@ import {ConnectionAuthorizationFailedError,isConnectionAuthorizationFailedError,isConnectionAuthorizationRequiredError,-} from "#public/connections/errors.js";-import { defineTool } from "#public/definitions/tool.js";-import type { ToolContext } from "#public/definitions/tool.js";+} from "#connections/errors.js";+import { defineTool } from "#tools/definition.js";+import type { ToolContext } from "#tools/definition.js";import {resolveApprovalPolicy,type ApprovalContext,type ApprovalResponseContext,-} from "#public/definitions/approval.js";-import type { JsonValue } from "#public/types/json.js";+} from "#approval/definition.js";+import type { JsonValue } from "#shared/json.js";import type { JsonObject } from "#shared/json.js";-import { stampDurableDynamicToolCallbacks } from "#shared/durable-dynamic-tool-callbacks.js";+import { stampDurableDynamicToolCallbacks } from "#tools/durable-callbacks.js";import { writeCachedToken } from "#runtime/connections/authorization-tokens.js";import { principalKey, resolveConnectionPrincipal } from "#runtime/connections/principal.js";import { resolveConnectionAuthorization } from "#runtime/connections/resolve-authorization.js";diff --git a/packages/eve/src/execution/tools/file-state.ts b/packages/eve/src/execution/tools/file-state.tsindex c79086686..ac656e5a9 100644--- a/packages/eve/src/execution/tools/file-state.ts+++ b/packages/eve/src/execution/tools/file-state.ts@@ -78,8 +78,8 @@ export function createReadFileStamp(input: { content: string; filePath: string }/*** Persists one read-file stamp into the durable context state.*- * Centralizes the context read-update-write so callers in `read-file-tool`- * and `write-file-tool` do not duplicate the state mutation pattern.+ * Centralizes the context read-update-write so the read and write file tools+ * do not duplicate the state mutation pattern.*/export function setReadFileStamp(ctx: AlsContext, targetKey: string, stamp: ReadFileStamp): void {const state = ctx.ensure(ReadFileStateKey, () => ({ byTarget: {} }));diff --git a/packages/eve/src/execution/tools/load-skill.test.ts b/packages/eve/src/execution/tools/load-skill.test.tsindex ea94eb384..0607d1095 100644--- a/packages/eve/src/execution/tools/load-skill.test.ts+++ b/packages/eve/src/execution/tools/load-skill.test.ts@@ -5,7 +5,7 @@ import { DynamicSkillManifestKey, SandboxKey } from "#context/keys.js";import { ConnectionRegistryKey } from "#context/providers/connection-key.js";import { mockSandbox } from "#internal/testing/mocks/mock-sandbox.js";import type { ConnectionRegistry } from "#runtime/connections/registry-types.js";-import { loadSkill } from "#public/tools/load-skill.js";+import { loadSkill } from "#tools/provided/load-skill.js";import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";import { createSandboxSkillHandle } from "#runtime/skills/sandbox-access.js";import type { ResolvedSkillDefinition } from "#runtime/types.js";diff --git a/packages/eve/src/execution/tools/subagent/local.ts b/packages/eve/src/execution/tools/subagent/local.tsindex 1c799f528..920370289 100644--- a/packages/eve/src/execution/tools/subagent/local.ts+++ b/packages/eve/src/execution/tools/subagent/local.ts@@ -21,13 +21,13 @@ import { findTaskAgentAddress } from "#execution/tasks/parent/control-shared.js"import type { BackgroundTask } from "#execution/tasks/parent/delegate.js";import { CallbackBaseUrlKey } from "#harness/authorization.js";import { getHarnessEmissionState } from "#harness/emission.js";-import { defineTool, type TaskExec, type ToolContext } from "#public/definitions/tool.js";+import { defineTool, type TaskExec, type ToolContext } from "#tools/definition.js";import type {RuntimeRemoteAgentCallActionRequest,RuntimeSubagentCallActionRequest,} from "#shared/action-types.js";-import { SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA } from "#shared/task-tool.js";-import { PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA } from "#shared/agent-tool.js";+import { SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA } from "#tools/framework/task-contract.js";+import { PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA } from "#tools/framework/agent-contract.js";import { parseJsonObject } from "#shared/json.js";import { createSubagentExecutorBinding } from "#tasks/types.js";import { activeTurnId } from "#harness/active-turn-id.js";diff --git a/packages/eve/src/execution/tools/subagent/remote.ts b/packages/eve/src/execution/tools/subagent/remote.tsindex 6c761e43b..6759d6e75 100644--- a/packages/eve/src/execution/tools/subagent/remote.ts+++ b/packages/eve/src/execution/tools/subagent/remote.ts@@ -1,6 +1,6 @@-import { defineTool } from "#public/definitions/tool.js";-import { SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA } from "#shared/task-tool.js";-import { PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA } from "#shared/agent-tool.js";+import { defineTool } from "#tools/definition.js";+import { SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA } from "#tools/framework/task-contract.js";+import { PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA } from "#tools/framework/agent-contract.js";import { executeSubagentTool } from "#execution/tools/subagent/local.js";export function defineRemoteSubagent(input: {diff --git a/packages/eve/src/execution/tools/tasks.ts b/packages/eve/src/execution/tools/tasks.tsindex 1fc7e24d4..2e573dee2 100644--- a/packages/eve/src/execution/tools/tasks.ts+++ b/packages/eve/src/execution/tools/tasks.ts@@ -5,7 +5,7 @@ import {TASK_UPDATE_INPUT_SCHEMA,TASK_UPDATE_TOOL_NAME,TASK_VIEWS_OUTPUT_SCHEMA,-} from "#shared/task-tool.js";+} from "#tools/framework/task-contract.js";/*** Framework task tools for `experimental.tasks`.diff --git a/packages/eve/src/execution/turn-cancellation.integration.test.ts b/packages/eve/src/execution/turn-cancellation.integration.test.tsindex 11c09cae3..65a503eeb 100644--- a/packages/eve/src/execution/turn-cancellation.integration.test.ts+++ b/packages/eve/src/execution/turn-cancellation.integration.test.ts@@ -22,9 +22,9 @@ import type { RouteHandlerArgs } from "#channel/routes.js";import { createSession } from "#channel/session.js";import { none } from "#public/channels/auth.js";import { eveChannel } from "#public/channels/eve.js";-import type { ToolContext } from "#public/definitions/tool.js";+import type { ToolContext } from "#tools/definition.js";import type { ResolvedToolDefinition } from "#runtime/types.js";-import { toInputSchema } from "#shared/tool-schema.js";+import { toInputSchema } from "#tools/schema.js";/*** Turn cancellation settles as `turn.cancelled` → `session.waiting` withdiff --git a/packages/eve/src/execution/web-fetch/tool.test.ts b/packages/eve/src/execution/web-fetch/execute.test.tssimilarity index 99%rename from packages/eve/src/execution/web-fetch/tool.test.tsrename to packages/eve/src/execution/web-fetch/execute.test.tsindex b28e92ef6..33b36f0bb 100644--- a/packages/eve/src/execution/web-fetch/tool.test.ts+++ b/packages/eve/src/execution/web-fetch/execute.test.ts@@ -3,7 +3,7 @@ import { EVE_PACKAGE_NAME } from "#internal/package-name.js";import { MAX_OUTPUT_BYTES, MAX_OUTPUT_LINES } from "#execution/sandbox/truncate-output.js";import { convertHtmlToMarkdown, extractTextFromHtml } from "#execution/web-fetch/html.js";import { requestPublicUrl } from "#execution/web-fetch/request.js";-import { executeWebFetchTool } from "#execution/web-fetch/tool.js";+import { executeWebFetchTool } from "#execution/web-fetch/execute.js";vi.mock("#execution/web-fetch/request.js", () => ({requestPublicUrl: vi.fn(),diff --git a/packages/eve/src/execution/web-fetch/tool.ts b/packages/eve/src/execution/web-fetch/execute.tssimilarity index 100%rename from packages/eve/src/execution/web-fetch/tool.tsrename to packages/eve/src/execution/web-fetch/execute.tsdiff --git a/packages/eve/src/execution/workflow-entry.integration.test.ts b/packages/eve/src/execution/workflow-entry.integration.test.tsindex 18adc90a1..7bcf031d8 100644--- a/packages/eve/src/execution/workflow-entry.integration.test.ts+++ b/packages/eve/src/execution/workflow-entry.integration.test.ts@@ -16,17 +16,17 @@ import { createToolExecuteWithAuth } from "#execution/tool-auth.js";import { createWorkflowRuntime } from "#execution/workflow-runtime.js";import { normalizeEveAttributes } from "#runtime/attributes/normalize.js";import { ROOT_COMPILED_AGENT_NODE_ID } from "#compiler/manifest.js";-import { ConnectionAuthorizationRequiredError } from "#public/connections/errors.js";+import { ConnectionAuthorizationRequiredError } from "#connections/errors.js";import type { MessageStreamEvent } from "#protocol/message.js";import { isEventId } from "#protocol/event-id.js";-import type { ToolContext } from "#public/definitions/tool.js";+import type { ToolContext } from "#tools/definition.js";import type {AuthorizationDefinition,ConnectionPrincipal,TokenResult,} from "#shared/connection-types.js";import type { ResolvedToolDefinition } from "#runtime/types.js";-import { toInputSchema } from "#shared/tool-schema.js";+import { toInputSchema } from "#tools/schema.js";function buildSerializedContext(overrides: {audience?: "public" | "private" | "unknown";diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.tsindex 52db413b9..4aae1111a 100644--- a/packages/eve/src/execution/workflow-steps.test.ts+++ b/packages/eve/src/execution/workflow-steps.test.ts@@ -48,8 +48,8 @@ import { createTurnWorkflowInput } from "#execution/durable-session-migrations/timport { dispatchTurnStep } from "#execution/dispatch-turn-step.js";import { projectToDurableSession } from "#execution/session.js";import { buildRuntimeIdentity, createExecutionNodeStep } from "#execution/node-step.js";-import { defineTool } from "#public/definitions/tool.js";-import { stampDurableDynamicCallback } from "#shared/durable-dynamic-tool-callbacks.js";+import { defineTool } from "#tools/definition.js";+import { stampDurableDynamicCallback } from "#tools/durable-callbacks.js";import { dispatchRuntimeActionsStep } from "#execution/dispatch-runtime-actions-step.js";import { runProxySubagentEventStep } from "#execution/subagent-event-proxy-step.js";import { readLatestTaskView, sendTaskInboundPayload } from "#execution/tasks/parent/run-parent.js";diff --git a/packages/eve/src/execution/workflow-steps.ts b/packages/eve/src/execution/workflow-steps.tsindex 24d098af2..609d7fb0b 100644--- a/packages/eve/src/execution/workflow-steps.ts+++ b/packages/eve/src/execution/workflow-steps.ts@@ -103,7 +103,7 @@ import { hydrateDurableSession, refreshSessionFromTurnAgent } from "#execution/simport { createExecutionHistoryView } from "#execution/history-view.js";import { resolveRuntimeCompiledArtifactsVersionedCacheKey } from "#runtime/cache-key.js";import { createWorkflowRuntime } from "#execution/workflow-runtime.js";-import { TASK_UPDATE_TOOL_NAME } from "#shared/task-tool.js";+import { TASK_UPDATE_TOOL_NAME } from "#tools/framework/task-contract.js";import { stageAttachmentsToSandbox } from "#harness/attachment-staging.js";const TASK_DONE_WITH_PENDING_INPUT_ERROR_MESSAGE =diff --git a/packages/eve/src/framework/sources/modules/agent-tool.ts b/packages/eve/src/framework/sources/modules/agent-tool.tsdeleted file mode 100644index 4a252ba93..000000000--- a/packages/eve/src/framework/sources/modules/agent-tool.ts+++ /dev/null@@ -1 +0,0 @@-export { agent as default } from "#public/tools/agent.js";diff --git a/packages/eve/src/framework/sources/modules/ask-question.ts b/packages/eve/src/framework/sources/modules/ask-question.tsdeleted file mode 100644index f9a180e3f..000000000--- a/packages/eve/src/framework/sources/modules/ask-question.ts+++ /dev/null@@ -1 +0,0 @@-export { askQuestion as default } from "#public/tools/ask-question.js";diff --git a/packages/eve/src/framework/sources/modules/bash.ts b/packages/eve/src/framework/sources/modules/bash.tsdeleted file mode 100644index 6912cd201..000000000--- a/packages/eve/src/framework/sources/modules/bash.ts+++ /dev/null@@ -1 +0,0 @@-export { bash as default } from "#tools/bash.js";diff --git a/packages/eve/src/framework/sources/modules/connection-search.ts b/packages/eve/src/framework/sources/modules/connection-search.tsdeleted file mode 100644index 030e2e387..000000000--- a/packages/eve/src/framework/sources/modules/connection-search.ts+++ /dev/null@@ -1 +0,0 @@-export { default } from "#tools/connection-search.js";diff --git a/packages/eve/src/framework/sources/modules/load-skill.ts b/packages/eve/src/framework/sources/modules/load-skill.tsdeleted file mode 100644index 1e4e9af93..000000000--- a/packages/eve/src/framework/sources/modules/load-skill.ts+++ /dev/null@@ -1 +0,0 @@-export { loadSkill as default } from "#tools/load-skill.js";diff --git a/packages/eve/src/framework/sources/modules/read-file.ts b/packages/eve/src/framework/sources/modules/read-file.tsdeleted file mode 100644index 2bd0f20f4..000000000--- a/packages/eve/src/framework/sources/modules/read-file.ts+++ /dev/null@@ -1 +0,0 @@-export { readFile as default } from "#tools/read-file.js";diff --git a/packages/eve/src/framework/sources/modules/task-cancel.ts b/packages/eve/src/framework/sources/modules/task-cancel.tsdeleted file mode 100644index a1843ae9e..000000000--- a/packages/eve/src/framework/sources/modules/task-cancel.ts+++ /dev/null@@ -1 +0,0 @@-export { taskCancel as default } from "#public/tools/task-cancel.js";diff --git a/packages/eve/src/framework/sources/modules/task-update.ts b/packages/eve/src/framework/sources/modules/task-update.tsdeleted file mode 100644index 226d867f3..000000000--- a/packages/eve/src/framework/sources/modules/task-update.ts+++ /dev/null@@ -1 +0,0 @@-export { taskUpdate as default } from "#public/tools/task-update.js";diff --git a/packages/eve/src/framework/sources/modules/todo.ts b/packages/eve/src/framework/sources/modules/todo.tsdeleted file mode 100644index 21ed9197c..000000000--- a/packages/eve/src/framework/sources/modules/todo.ts+++ /dev/null@@ -1 +0,0 @@-export { todo as default } from "#tools/todo.js";diff --git a/packages/eve/src/framework/sources/modules/web-fetch.ts b/packages/eve/src/framework/sources/modules/web-fetch.tsdeleted file mode 100644index 230db01ed..000000000--- a/packages/eve/src/framework/sources/modules/web-fetch.ts+++ /dev/null@@ -1 +0,0 @@-export { webFetch as default } from "#tools/web-fetch.js";diff --git a/packages/eve/src/framework/sources/modules/web-search.ts b/packages/eve/src/framework/sources/modules/web-search.tsdeleted file mode 100644index 13f54d8ae..000000000--- a/packages/eve/src/framework/sources/modules/web-search.ts+++ /dev/null@@ -1,3 +0,0 @@-import { webSearch } from "#public/tools/web-search.js";--export default webSearch({ provider: "exa" });diff --git a/packages/eve/src/framework/sources/modules/write-file.ts b/packages/eve/src/framework/sources/modules/write-file.tsdeleted file mode 100644index bee239578..000000000--- a/packages/eve/src/framework/sources/modules/write-file.ts+++ /dev/null@@ -1 +0,0 @@-export { writeFile as default } from "#tools/write-file.js";diff --git a/packages/eve/src/framework/sources/registry.ts b/packages/eve/src/framework/sources/registry.tsindex 07a52fc08..5e6f02f11 100644--- a/packages/eve/src/framework/sources/registry.ts+++ b/packages/eve/src/framework/sources/registry.ts@@ -22,39 +22,39 @@ const localDefaults = defineProgrammaticAgentSource({},{logicalPath: "tools/bash.ts",- loadNamespace: () => import("#framework/sources/modules/bash.js"),+ loadNamespace: () => import("#tools/provided/bash.js"),},{logicalPath: "tools/read_file.ts",- loadNamespace: () => import("#framework/sources/modules/read-file.js"),+ loadNamespace: () => import("#tools/provided/read-file.js"),},{logicalPath: "tools/write_file.ts",- loadNamespace: () => import("#framework/sources/modules/write-file.js"),+ loadNamespace: () => import("#tools/provided/write-file.js"),},{logicalPath: "tools/todo.ts",- loadNamespace: () => import("#framework/sources/modules/todo.js"),+ loadNamespace: () => import("#tools/provided/todo.js"),},{logicalPath: "tools/web_fetch.ts",- loadNamespace: () => import("#framework/sources/modules/web-fetch.js"),+ loadNamespace: () => import("#tools/provided/web-fetch.js"),},{logicalPath: "tools/load_skill.ts",- loadNamespace: () => import("#framework/sources/modules/load-skill.js"),+ loadNamespace: () => import("#tools/provided/load-skill.js"),},{logicalPath: "tools/connection_search.ts",- loadNamespace: () => import("#framework/sources/modules/connection-search.js"),+ loadNamespace: () => import("#tools/framework/connection-search.js"),},{logicalPath: "tools/ask_question.ts",- loadNamespace: () => import("#framework/sources/modules/ask-question.js"),+ loadNamespace: () => import("#tools/framework/ask-question.js"),},{logicalPath: "tools/web_search.ts",- loadNamespace: () => import("#framework/sources/modules/web-search.js"),+ loadNamespace: () => import("#tools/provided/web-search.js"),},],});@@ -65,15 +65,15 @@ const rootDefaults = defineProgrammaticAgentSource({modules: [{logicalPath: "tools/agent.ts",- loadNamespace: () => import("#framework/sources/modules/agent-tool.js"),+ loadNamespace: () => import("#tools/framework/agent.js"),},{logicalPath: "tools/task_update.ts",- loadNamespace: () => import("#framework/sources/modules/task-update.js"),+ loadNamespace: () => import("#tools/framework/task-update.js"),},{logicalPath: "tools/task_cancel.ts",- loadNamespace: () => import("#framework/sources/modules/task-cancel.js"),+ loadNamespace: () => import("#tools/framework/task-cancel.js"),},{logicalPath: "channels/eve.ts",diff --git a/packages/eve/src/harness/advertised-tools.ts b/packages/eve/src/harness/advertised-tools.tsindex 8b765d888..97fb954d8 100644--- a/packages/eve/src/harness/advertised-tools.ts+++ b/packages/eve/src/harness/advertised-tools.ts@@ -1,8 +1,8 @@import type { ToolSet } from "ai";import type { HarnessToolDefinition } from "#harness/execute-tool.js";import { resolveSubagentDepth } from "#harness/subagent-depth.js";-import { AGENT_TOOL_NAME } from "#shared/agent-tool.js";-import { TASK_TOOL_NAMES, TASK_UPDATE_TOOL_NAME } from "#shared/task-tool.js";+import { AGENT_TOOL_NAME } from "#tools/framework/agent-contract.js";+import { TASK_TOOL_NAMES, TASK_UPDATE_TOOL_NAME } from "#tools/framework/task-contract.js";import { ROOT_RUNTIME_AGENT_NODE_ID } from "#runtime/graph.js";import {ensureWorkflowContinuationSecurity,diff --git a/packages/eve/src/harness/authorization.ts b/packages/eve/src/harness/authorization.tsindex aaa3904d5..a6977675a 100644--- a/packages/eve/src/harness/authorization.ts+++ b/packages/eve/src/harness/authorization.ts@@ -35,9 +35,9 @@ import { loadContext } from "#context/container.js";import { ContextKey } from "#context/key.js";import { SessionIdKey } from "#context/keys.js";import { createWorkflowCallbackUrl } from "#execution/workflow-callback-url.js";-import type { ConnectionAuthorizationChallenge } from "#public/connections/errors.js";+import type { ConnectionAuthorizationChallenge } from "#connections/errors.js";import type { AuthorizationCallback, ConnectionPrincipal } from "#shared/connection-types.js";-import type { JsonValue } from "#public/types/json.js";+import type { JsonValue } from "#shared/json.js";import { createEveConnectionCallbackRoutePath } from "#protocol/routes.js";import { createUlid } from "#shared/ulid.js";diff --git a/packages/eve/src/harness/background-tools.ts b/packages/eve/src/harness/background-tools.tsindex f37c63ba5..ffd0e3e84 100644--- a/packages/eve/src/harness/background-tools.ts+++ b/packages/eve/src/harness/background-tools.ts@@ -1,7 +1,7 @@import { loadContext } from "#context/container.js";import { ContextKey } from "#context/key.js";-import type { ToolExecuteOptions } from "#shared/tool-definition.js";-import type { TaskExec } from "#shared/tool-task.js";+import type { ToolExecuteOptions } from "#tools/definition.js";+import type { TaskExec } from "#tools/task.js";export interface BackgroundExecutableTool {readonly execute: (input: unknown, options: ToolExecuteOptions, task: TaskExec) => unknown;diff --git a/packages/eve/src/harness/execute-tool.ts b/packages/eve/src/harness/execute-tool.tsindex 580109296..de8327f5b 100644--- a/packages/eve/src/harness/execute-tool.ts+++ b/packages/eve/src/harness/execute-tool.ts@@ -1,8 +1,8 @@import type { FlexibleSchema } from "ai";-import type { Approval } from "#public/definitions/approval.js";-import type { ToolExecuteOptions } from "#shared/tool-definition.js";-import type { TaskExec } from "#shared/tool-task.js";+import type { Approval } from "#approval/definition.js";+import type { ToolExecuteOptions } from "#tools/definition.js";+import type { TaskExec } from "#tools/task.js";/*** Runtime-owned action metadata attached to one harness-visible tool.diff --git a/packages/eve/src/harness/final-output.ts b/packages/eve/src/harness/final-output.tsindex 29d24112f..d8cb02ddc 100644--- a/packages/eve/src/harness/final-output.ts+++ b/packages/eve/src/harness/final-output.ts@@ -1,6 +1,6 @@import type { Tool } from "ai";-import { toInputSchema } from "#shared/tool-schema.js";+import { toInputSchema } from "#tools/schema.js";import type { JsonObject } from "#shared/json.js";/**diff --git a/packages/eve/src/harness/input-requests.test.ts b/packages/eve/src/harness/input-requests.test.tsindex ac029c767..a576a6a52 100644--- a/packages/eve/src/harness/input-requests.test.ts+++ b/packages/eve/src/harness/input-requests.test.ts@@ -3,7 +3,7 @@ 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 { once } from "#tools/approval/policies.js";import type { InputRequest } from "#shared/input.js";import type { HarnessToolDefinition } from "#harness/execute-tool.js";import {diff --git a/packages/eve/src/harness/tool-input-validation.integration.test.ts b/packages/eve/src/harness/tool-input-validation.integration.test.tsindex 2284dad36..c9119e930 100644--- a/packages/eve/src/harness/tool-input-validation.integration.test.ts+++ b/packages/eve/src/harness/tool-input-validation.integration.test.ts@@ -5,8 +5,8 @@ import { describe, expect, it } from "vitest";import { getPendingInputRequestIds } from "#harness/input-requests.js";import { createToolLoopHarness } from "#harness/tool-loop.js";import type { HarnessSession, ToolLoopHarnessConfig } from "#harness/types.js";-import { ASK_QUESTION_INPUT_SCHEMA, askQuestion } from "#public/tools/ask-question.js";-import { serializeInputSchema } from "#shared/tool-schema.js";+import { ASK_QUESTION_INPUT_SCHEMA, askQuestion } from "#tools/framework/ask-question.js";+import { serializeInputSchema } from "#tools/schema.js";const usage = {inputTokens: {diff --git a/packages/eve/src/harness/tool-loop-cancellation.integration.test.ts b/packages/eve/src/harness/tool-loop-cancellation.integration.test.tsindex 5f869bd72..dc0051352 100644--- a/packages/eve/src/harness/tool-loop-cancellation.integration.test.ts+++ b/packages/eve/src/harness/tool-loop-cancellation.integration.test.ts@@ -6,7 +6,7 @@ import type { UnstampedMessageStreamEvent } from "#protocol/message.js";import { createToolLoopHarness } from "#harness/tool-loop.js";import { TurnCancelledError } from "#harness/turn-cancellation.js";import type { HarnessEmitFn, HarnessSession, ToolLoopHarnessConfig } from "#harness/types.js";-import type { ToolExecuteOptions } from "#shared/tool-definition.js";+import type { ToolExecuteOptions } from "#tools/definition.js";type StreamResult = Awaited<ReturnType<MockLanguageModelV3["doStream"]>>;type StreamPart = StreamResult["stream"] extends ReadableStream<infer Part> ? Part : never;diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.tsindex 9655f0487..10d184087 100644--- a/packages/eve/src/harness/tool-loop.test.ts+++ b/packages/eve/src/harness/tool-loop.test.ts@@ -37,8 +37,8 @@ import type { UnstampedMessageStreamEvent } from "#protocol/message.js";import type { InstrumentationStepStartedEventInput } from "#public/instrumentation/index.js";import { defineInstructions } from "#public/definitions/instructions.js";import type { ResolvedDynamicInstructionsResolver } from "#runtime/types.js";-import type { DynamicResolveContext } from "#shared/dynamic-tool-definition.js";-import { registerDurableDynamicCallback } from "#shared/durable-dynamic-tool-callbacks.js";+import type { DynamicResolveContext } from "#dynamic/definition.js";+import { registerDurableDynamicCallback } from "#tools/durable-callbacks.js";import type { RunMode } from "#shared/run-mode.js";import { compactMessages, shouldCompact } from "#harness/compaction.js";import { getHarnessEmissionState, isHarnessBetweenTurns } from "#harness/emission.js";diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.tsindex c4e789312..e231e00f2 100644--- a/packages/eve/src/harness/tool-loop.ts+++ b/packages/eve/src/harness/tool-loop.ts@@ -158,7 +158,7 @@ import { attemptIdempotencyKey } from "#harness/instrumentation/lifecycle.js";import { resolveParentLineage } from "#harness/parent-lineage.js";import { prepareTurnTraceContext } from "#harness/prepare-trace-context.js";import { ChannelKey } from "#runtime/sessions/runtime-context-keys.js";-import { TASK_UPDATE_TOOL_NAME } from "#shared/task-tool.js";+import { TASK_UPDATE_TOOL_NAME } from "#tools/framework/task-contract.js";import { readTaskIdFromInboxToken } from "#tasks/task-inbox-token.js";import {consumeDeferredStepInput,diff --git a/packages/eve/src/harness/tool-model-output.test.ts b/packages/eve/src/harness/tool-model-output.test.tsindex e5d2fbe9a..5a4cac48a 100644--- a/packages/eve/src/harness/tool-model-output.test.ts+++ b/packages/eve/src/harness/tool-model-output.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { toolOutput, toolOutputPart } from "#public/tools/output-builders.js";+import { toolOutput, toolOutputPart } from "#tools/model-output.js";import { normalizeToolJsonOutput, normalizeToolModelOutput } from "#harness/tool-model-output.js";function normalize(output: unknown): unknown {diff --git a/packages/eve/src/harness/tool-model-output.ts b/packages/eve/src/harness/tool-model-output.tsindex 9ad4bb66e..1a073d744 100644--- a/packages/eve/src/harness/tool-model-output.ts+++ b/packages/eve/src/harness/tool-model-output.ts@@ -3,7 +3,7 @@ import type { JSONValue } from "ai";import { z } from "#compiled/zod/index.js";import { createLogger } from "#internal/logging.js";import { parseJsonValue, type JsonValue } from "#shared/json.js";-import type { ToolModelOutputPart } from "#shared/tool-definition.js";+import type { ToolModelOutputPart } from "#tools/definition.js";import { formatValidationError } from "#runtime/validation.js";import { withToolOutputSerializationError } from "#harness/tool-output-serialization.js";diff --git a/packages/eve/src/harness/tools.test.ts b/packages/eve/src/harness/tools.test.tsindex 237ea3088..ef4bc6f87 100644--- a/packages/eve/src/harness/tools.test.ts+++ b/packages/eve/src/harness/tools.test.ts@@ -4,7 +4,7 @@ import { describe, expect, it } from "vitest";import { ContextContainer, contextStorage } from "#context/container.js";import { SessionKey, type Session } from "#context/keys.js";import { SCHEDULE_APP_AUTH } from "#channel/schedule-auth.js";-import { always, never, once } from "#public/tools/approval/approval-helpers.js";+import { always, never, once } from "#tools/approval/policies.js";import type { RuntimeModelReference } from "#runtime/agent/bootstrap.js";import {@@ -20,9 +20,9 @@ import type { HarnessToolDefinition } from "#harness/execute-tool.js";import { buildToolApproval, buildToolSet, buildToolSetWithProviderTools } from "#harness/tools.js";import type { HarnessToolMap } from "#harness/types.js";import { createToolExecuteWithAuth } from "#execution/tool-auth.js";-import type { ApprovalContext } from "#public/definitions/approval.js";-import type { ToolContext } from "#public/definitions/tool.js";-import type { ToolExecuteOptions } from "#shared/tool-definition.js";+import type { ApprovalContext } from "#approval/definition.js";+import type { ToolContext } from "#tools/definition.js";+import type { ToolExecuteOptions } from "#tools/definition.js";function getJsonSchema(tool: unknown): unknown {return (tool as { inputSchema: { jsonSchema: unknown } }).inputSchema.jsonSchema;diff --git a/packages/eve/src/harness/tools.ts b/packages/eve/src/harness/tools.tsindex dbc14af04..fb8798733 100644--- a/packages/eve/src/harness/tools.ts+++ b/packages/eve/src/harness/tools.ts@@ -7,7 +7,7 @@ import { ASK_QUESTION_TOOL_NAME } from "#harness/request-input-tool.js";import { WEB_SEARCH_TOOL_NAME } from "#harness/provider-tool-schemas.js";import { isObject } from "#shared/guards.js";import type { HarnessToolDefinition } from "#harness/execute-tool.js";-import { resolveApprovalPolicy, type ApprovalStatus } from "#public/definitions/approval.js";+import { resolveApprovalPolicy, type ApprovalStatus } from "#approval/definition.js";import { resolveWebSearchBackend, resolveWebSearchProviderTool } from "#harness/provider-tools.js";import type { HarnessToolMap } from "#harness/types.js";import { buildCallbackContext } from "#context/build-callback-context.js";@@ -20,7 +20,7 @@ import {} from "#harness/authorization.js";import { stashToolInterrupt } from "#harness/tool-interrupts.js";import { normalizeToolJsonOutput, normalizeToolModelOutput } from "#harness/tool-model-output.js";-import type { ToolExecuteOptions } from "#shared/tool-definition.js";+import type { ToolExecuteOptions } from "#tools/definition.js";import { isAsyncIterable } from "#shared/async-iterable.js";import {createBackgroundToolCallBatch,diff --git a/packages/eve/src/harness/types.ts b/packages/eve/src/harness/types.tsindex 519e57669..aee44aeb2 100644--- a/packages/eve/src/harness/types.ts+++ b/packages/eve/src/harness/types.ts@@ -10,7 +10,7 @@ import type { InputResponse } from "#shared/input.js";import type { SandboxState } from "#sandbox/state.js";import type { JsonObject } from "#shared/json.js";import type { TokenUsage } from "#shared/token-usage.js";-import type { InternalToolDefinition } from "#shared/tool-definition.js";+import type { InternalToolDefinition } from "#tools/definition.js";import type { WebSearchProvider } from "#shared/web-search.js";import type { AgentReasoningDefinition } from "#shared/agent-definition.js";import type { HarnessToolDefinition } from "#harness/execute-tool.js";diff --git a/packages/eve/src/instrumentation/provider.ts b/packages/eve/src/instrumentation/provider.tsindex 3638ffd22..7c9bbd0d0 100644--- a/packages/eve/src/instrumentation/provider.ts+++ b/packages/eve/src/instrumentation/provider.ts@@ -13,9 +13,9 @@ import type {InstrumentationCapture,InstrumentationEvent,} from "#harness/instrumentation/lifecycle.js";-import type { JsonValue } from "#public/types/json.js";+import type { JsonValue } from "#shared/json.js";-export type { JsonValue } from "#public/types/json.js";+export type { JsonValue } from "#shared/json.js";export type {InstrumentationActionCompletedEvent,diff --git a/packages/eve/src/internal/authored-definition/approval.ts b/packages/eve/src/internal/authored-definition/approval.tsindex 45321b281..db73eebd3 100644--- a/packages/eve/src/internal/authored-definition/approval.ts+++ b/packages/eve/src/internal/authored-definition/approval.ts@@ -3,11 +3,7 @@ import {expectObjectRecord,expectOnlyKnownKeys,} from "#internal/authored-module.js";-import type {- Approval,- ApprovalPolicy,- ApprovalResponsePolicy,-} from "#public/definitions/approval.js";+import type { Approval, ApprovalPolicy, ApprovalResponsePolicy } from "#approval/definition.js";/** Validates the function shorthand or explicit request/response approval shape. */export function normalizeApproval(value: unknown, message: string): Approval {diff --git a/packages/eve/src/internal/authored-definition/core.test.ts b/packages/eve/src/internal/authored-definition/core.test.tsindex 734499cba..c74a6a427 100644--- a/packages/eve/src/internal/authored-definition/core.test.ts+++ b/packages/eve/src/internal/authored-definition/core.test.ts@@ -5,7 +5,7 @@ import {normalizeInstructionsDefinition,normalizeScheduleDefinition,} from "#internal/authored-definition/core.js";-import { defineDynamic } from "#public/definitions/tool.js";+import { defineDynamic } from "#dynamic/definition.js";const FAILURE_MESSAGE = "Expected the agent config to match the public eve shape.";diff --git a/packages/eve/src/internal/authored-definition/core.ts b/packages/eve/src/internal/authored-definition/core.tsindex 9f80f99e7..013a5ed9f 100644--- a/packages/eve/src/internal/authored-definition/core.ts+++ b/packages/eve/src/internal/authored-definition/core.ts@@ -19,7 +19,7 @@ import {isDynamicSentinel,type DynamicEvents,type DynamicToolEventName,-} from "#shared/dynamic-tool-definition.js";+} from "#dynamic/definition.js";type Mutable<T> = { -readonly [K in keyof T]: T[K] };type MutableDynamicEvents = {diff --git a/packages/eve/src/internal/authored-definition/schema-backed.test.ts b/packages/eve/src/internal/authored-definition/schema-backed.test.tsindex 36f19d91a..7dd8eabf6 100644--- a/packages/eve/src/internal/authored-definition/schema-backed.test.ts+++ b/packages/eve/src/internal/authored-definition/schema-backed.test.ts@@ -2,14 +2,11 @@ import { describe, expect, it } from "vitest";import { z as z3 } from "zod/v3";import { z } from "#compiled/zod/index.js";-import {- defineTool,- defineDynamic,- disableTool,- experimental_workflow,-} from "#public/definitions/tool.js";-import { once } from "#public/tools/approval/approval-helpers.js";-import { webSearch } from "#public/tools/web-search.js";+import { defineDynamic } from "#dynamic/definition.js";+import { defineTool, disableTool } from "#tools/definition.js";+import { experimental_workflow } from "#tools/workflow.js";+import { once } from "#tools/approval/policies.js";+import { webSearch } from "#tools/provided/web-search.js";import { normalizeToolDefinition } from "#internal/authored-definition/schema-backed.js";const FAILURE_MESSAGE = "Expected the tool export to match the public eve shape.";diff --git a/packages/eve/src/internal/authored-definition/schema-backed.ts b/packages/eve/src/internal/authored-definition/schema-backed.tsindex cd09e2df9..10e5efdda 100644--- a/packages/eve/src/internal/authored-definition/schema-backed.ts+++ b/packages/eve/src/internal/authored-definition/schema-backed.ts@@ -1,8 +1,6 @@-import {- isDisabledToolSentinel,- isExperimentalWorkflowToolDefinition,-} from "#public/definitions/tool.js";-import { isWebSearchToolDefinition } from "#public/tools/web-search.js";+import { isDisabledToolSentinel } from "#tools/definition.js";+import { isExperimentalWorkflowToolDefinition } from "#tools/workflow.js";+import { isWebSearchToolDefinition } from "#tools/provided/web-search.js";import {expectFunction,expectObjectRecord,@@ -10,18 +8,18 @@ import {expectPositiveInteger,expectString,} from "#internal/authored-module.js";-import type { InternalToolDefinitionWithExecuteFn } from "#shared/tool-definition.js";+import type { InternalToolDefinitionWithExecuteFn } from "#tools/definition.js";import {serializeInputSchema,serializeOutputSchema,type ToolSchemaSource,-} from "#shared/tool-schema.js";+} from "#tools/schema.js";import { normalizeApproval } from "#internal/authored-definition/approval.js";import {assertResolverOnlyDynamicSentinel,isDynamicSentinel,type DynamicToolEventName,-} from "#shared/dynamic-tool-definition.js";+} from "#dynamic/definition.js";/*** Canonical normalized shape of one authored tool default export.diff --git a/packages/eve/src/internal/authored-definition/source-identity.ts b/packages/eve/src/internal/authored-definition/source-identity.tsnew file mode 100644index 000000000..02e316ee1--- /dev/null+++ b/packages/eve/src/internal/authored-definition/source-identity.ts@@ -0,0 +1,67 @@+export type DefinitionSourceEntry =+ | { readonly kind: "connection"; readonly logicalPath?: string; readonly name: string }+ | { readonly kind: "tool"; readonly logicalPath?: string; readonly name: string };++type AmbiguousDefinitionSourceEntry = { readonly kind: "ambiguous" };+type RegisteredDefinitionSource = DefinitionSourceEntry | AmbiguousDefinitionSourceEntry;++const DEFINITION_KEY = Symbol.for("eve.definition-source-key");+const REGISTRY_SYMBOL = Symbol.for("eve.definition-source-registry");++type RegistryGlobal = typeof globalThis & {+ [REGISTRY_SYMBOL]?: Map<string, RegisteredDefinitionSource>;+};++const registryContainer = globalThis as RegistryGlobal;+registryContainer[REGISTRY_SYMBOL] ??= new Map();+const definitionSourceRegistry = registryContainer[REGISTRY_SYMBOL];++export function stampDefinitionKey(definition: object, key: string): void {+ Object.defineProperty(definition, DEFINITION_KEY, { configurable: true, value: key });+}++export function registerDefinitionSource(key: string, entry: DefinitionSourceEntry): void {+ const existing = definitionSourceRegistry.get(key);+ if (existing !== undefined && !sameDefinitionSourceEntry(existing, entry)) {+ if (existing.kind !== "ambiguous") {+ console.warn(+ [+ `eve could not assign a unique toolResultFrom identity for ${JSON.stringify(key)}.`,+ `Conflicting definitions: ${formatDefinitionSourceForWarning(existing)} and ${formatDefinitionSourceForWarning(entry)}.`,+ "Multiple authored definitions share that fallback identity, so toolResultFrom will not match through it.",+ "Use the original definition object loaded by eve so source-derived identity can be used instead.",+ ].join(" "),+ );+ }+ definitionSourceRegistry.set(key, { kind: "ambiguous" });+ return;+ }+ definitionSourceRegistry.set(key, entry);+}++export function readDefinitionSource(definition: object): RegisteredDefinitionSource | undefined {+ const key = readDefinitionKey(definition);+ return key === undefined ? undefined : definitionSourceRegistry.get(key);+}++function readDefinitionKey(definition: object): string | undefined {+ if (DEFINITION_KEY in definition) {+ return (definition as Record<symbol, string>)[DEFINITION_KEY];+ }+ return undefined;+}++function sameDefinitionSourceEntry(+ a: RegisteredDefinitionSource,+ b: DefinitionSourceEntry,+): boolean {+ if (a.kind !== b.kind) return false;+ return a.name === b.name;+}++function formatDefinitionSourceForWarning(entry: DefinitionSourceEntry): string {+ if (entry.logicalPath === undefined) {+ return `${entry.kind} "${entry.name}"`;+ }+ return `${entry.kind} "${entry.name}" from "${entry.logicalPath}"`;+}diff --git a/packages/eve/src/internal/invocation/agent-invocation.ts b/packages/eve/src/internal/invocation/agent-invocation.tsindex bc320dcda..a6e999abe 100644--- a/packages/eve/src/internal/invocation/agent-invocation.ts+++ b/packages/eve/src/internal/invocation/agent-invocation.ts@@ -1,4 +1,4 @@-import type { ConnectionAuthorizationChallenge } from "#public/connections/errors.js";+import type { ConnectionAuthorizationChallenge } from "#connections/errors.js";import type { InputRequest } from "#shared/input.js";import type { JsonValue } from "#shared/json.js";diff --git a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.test.ts b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.test.tsindex 426b64111..4ff8e4189 100644--- a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.test.ts+++ b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.test.ts@@ -3,8 +3,8 @@ import { describe, expect, it } from "vitest";import { compileFromMemory } from "#compiler/compile-from-memory.js";import { buildAgentInfoResponse } from "#internal/nitro/routes/agent-info/build-agent-info-response.js";import { defineInstrumentation } from "#public/instrumentation/index.js";-import { experimental_workflow } from "#public/definitions/tool.js";-import { webSearch } from "#public/tools/web-search.js";+import { experimental_workflow } from "#tools/workflow.js";+import { webSearch } from "#tools/provided/web-search.js";describe("buildAgentInfoResponse", () => {it("projects v3 exclusively from the effective compiled graph", async () => {diff --git a/packages/eve/src/internal/testing/app-harness.ts b/packages/eve/src/internal/testing/app-harness.tsindex d85d80481..d2518244b 100644--- a/packages/eve/src/internal/testing/app-harness.ts+++ b/packages/eve/src/internal/testing/app-harness.ts@@ -14,7 +14,7 @@ import {import type { ResolvedToolDefinition } from "#runtime/types.js";import { resolveRuntimeAgentGraph } from "#runtime/resolve-agent-graph.js";import { createNodeHarnessTools } from "#execution/node-step.js";-import { serializeInputSchema, serializeOutputSchema } from "#shared/tool-schema.js";+import { serializeInputSchema, serializeOutputSchema } from "#tools/schema.js";import { defineSandbox } from "#public/definitions/sandbox.js";import type { SandboxBackend } from "#public/definitions/sandbox-backend.js";import {diff --git a/packages/eve/src/internal/testing/mocks/mock-tool.ts b/packages/eve/src/internal/testing/mocks/mock-tool.tsindex 8b2cbadcc..993c600ce 100644--- a/packages/eve/src/internal/testing/mocks/mock-tool.ts+++ b/packages/eve/src/internal/testing/mocks/mock-tool.ts@@ -1,8 +1,8 @@-import type { SessionContext } from "#public/definitions/callback-context.js";+import type { SessionContext } from "#context/session-context.js";import { buildCallbackContext } from "#context/build-callback-context.js";import type { JsonObject } from "#shared/json.js";import type { ResolvedToolDefinition } from "#runtime/types.js";-import { toInputSchema } from "#shared/tool-schema.js";+import { toInputSchema } from "#tools/schema.js";/*** Declarative description of one synthetic authored tool used by thediff --git a/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.test.ts b/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.test.tsindex e3871c315..ad4f19941 100644--- a/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.test.ts+++ b/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.test.ts@@ -5,7 +5,7 @@ import {collectDurableDynamicToolCallbacks,readDurableDynamicCallback,stampDurableDynamicToolCallbacks,-} from "#shared/durable-dynamic-tool-callbacks.js";+} from "#tools/durable-callbacks.js";// ---------------------------------------------------------------------------// Helpers for evaluating transformed codediff --git a/packages/eve/src/protocol/message.ts b/packages/eve/src/protocol/message.tsindex d7913a06b..517ad6bf0 100644--- a/packages/eve/src/protocol/message.ts+++ b/packages/eve/src/protocol/message.ts@@ -11,7 +11,7 @@ import {createEveSessionStreamRoutePath,createEveSubagentStreamRoutePath,} from "#protocol/routes.js";-import type { ConnectionAuthorizationChallenge } from "#public/connections/errors.js";+import type { ConnectionAuthorizationChallenge } from "#connections/errors.js";import type {RuntimeActionRequest,RuntimeActionResult,diff --git a/packages/eve/src/public/connections/errors.ts b/packages/eve/src/public/connections/errors.tsindex deaa50331..5f6c6c2f8 100644--- a/packages/eve/src/public/connections/errors.ts+++ b/packages/eve/src/public/connections/errors.ts@@ -1,158 +1,9 @@-/**- * Typed error classes for the connection authorization lifecycle.- */--/**- * User-facing authorization challenge payload.- */-export interface ConnectionAuthorizationChallenge {- /**- * Optional URL the user should visit to complete authorization.- * Serves as the redirect target, the verification URL in device- * code flow, or the source for a QR code.- */- readonly url?: string;-- /**- * Optional short code to display alongside `url` (device code flow).- */- readonly userCode?: string;-- /**- * Optional ISO timestamp at which the authorization opportunity- * expires. When provided, the runtime clamps the authorization deadline to- * `min(configured_timeout, expiresAt)` so the turn cannot outlive- * the challenge.- */- readonly expiresAt?: string;-- /**- * Optional human-readable call to action. When no `url` is- * available (e.g. CIBA, push-to-approve), this is what the channel- * should show as the primary affordance.- */- readonly instructions?: string;-- /**- * Optional human-readable provider name for sign-in UI (e.g.- * `"Salesforce"`). Presentation-only: identity (the authorization- * scope, token cache keys, callback URLs) stays the path-derived- * name. Channels fall back to title-casing the scope name when- * absent.- */- readonly displayName?: string;-}--/**- * Options accepted by {@link ConnectionAuthorizationRequiredError}.- */-export interface ConnectionAuthorizationRequiredErrorOptions {- /**- * Override for the default `Error.message`. Defaults to- * `Connection "{name}" requires authorization.` when omitted.- */- readonly message?: string;-}--/**- * Options accepted by {@link ConnectionAuthorizationFailedError}.- */-export interface ConnectionAuthorizationFailedErrorOptions {- /**- * Override for the default `Error.message`. Defaults to- * `Connection "{name}" authorization failed.` when omitted.- */- readonly message?: string;-- /**- * Stable machine-readable code describing why authorization failed.- *- * The runtime surfaces this code on the `authorization.completed`- * stream event and on the failed tool result the model sees. Use a- * short kebab- or snake-cased string (e.g. `"access_denied"`,- * `"invalid_grant"`).- *- * The runtime also emits a few reason codes itself, independently- * of authored throws:- *- * - `"principal_required"`: a `principalType: "user"` connection- * was invoked without an authenticated user principal. Terminal.- * - `"app_not_installed"`: an authored `getToken` for a- * `principalType: "app"` connection signalled the agent's own- * credentials are missing. Terminal.- */- readonly reason?: string;-- /**- * Controls whether the runtime re-prompts the user after this- * failure.- *- * Defaults to `true`; set `false` for terminal cases such as user- * denial (`reason: "access_denied"`).- */- readonly retryable?: boolean;-}--/**- * Thrown from a connection's `getToken` when no valid credential is- * available and authorization must be completed before the connection- * can be used. Covers both interactive OAuth (the runtime emits- * `authorization.required` and suspends the turn on a webhook) and- * non-interactive / out-of-band flows such as static API keys (the- * runtime emits `authorization.required` without suspending).- */-export class ConnectionAuthorizationRequiredError extends Error {- readonly connectionName: string;-- constructor(connectionName: string, options?: ConnectionAuthorizationRequiredErrorOptions) {- super(options?.message ?? `Connection "${connectionName}" requires authorization.`);- this.name = "ConnectionAuthorizationRequiredError";- this.connectionName = connectionName;- }-}--/**- * Thrown when a connection's authorization fails.- *- * Retryable by default; pass `retryable: false` for terminal failures- * where starting a fresh authorization flow would be wrong.- */-export class ConnectionAuthorizationFailedError extends Error {- readonly connectionName: string;- readonly reason?: string;- readonly retryable: boolean;-- constructor(connectionName: string, options?: ConnectionAuthorizationFailedErrorOptions) {- super(options?.message ?? `Connection "${connectionName}" authorization failed.`);- this.name = "ConnectionAuthorizationFailedError";- this.connectionName = connectionName;- this.reason = options?.reason;- this.retryable = options?.retryable ?? true;- }-}--/**- * Type guard for {@link ConnectionAuthorizationRequiredError}.- *- * Uses `err.name` rather than `instanceof` because user code and- * framework internals can end up with different class identities- * after bundling (dual-instance hazard in Nitro output).- */-export function isConnectionAuthorizationRequiredError(- err: unknown,-): err is ConnectionAuthorizationRequiredError {- return err instanceof Error && err.name === "ConnectionAuthorizationRequiredError";-}--/**- * Type guard for {@link ConnectionAuthorizationFailedError}.- *- * Uses `err.name` rather than `instanceof` because user code and- * framework internals can end up with different class identities- * after bundling (dual-instance hazard in Nitro output).- */-export function isConnectionAuthorizationFailedError(- err: unknown,-): err is ConnectionAuthorizationFailedError {- return err instanceof Error && err.name === "ConnectionAuthorizationFailedError";-}+export {+ ConnectionAuthorizationFailedError,+ ConnectionAuthorizationRequiredError,+ isConnectionAuthorizationFailedError,+ isConnectionAuthorizationRequiredError,+ type ConnectionAuthorizationChallenge,+ type ConnectionAuthorizationFailedErrorOptions,+ type ConnectionAuthorizationRequiredErrorOptions,+} from "#connections/errors.js";diff --git a/packages/eve/src/public/definitions/agent.ts b/packages/eve/src/public/definitions/agent.tsindex 0290fad44..04fe99066 100644--- a/packages/eve/src/public/definitions/agent.ts+++ b/packages/eve/src/public/definitions/agent.ts@@ -5,8 +5,8 @@ import type {} from "#shared/agent-definition.js";import type { ExactDefinition } from "#public/definitions/exact.js";import type { RemoteAgentDefinition } from "#public/definitions/remote-agent.js";-import { defineDynamic as defineDynamicBase } from "#public/definitions/tool.js";-import type { DynamicEvents, DynamicSentinel } from "#shared/dynamic-tool-definition.js";+import { defineDynamic as defineDynamicBase } from "#dynamic/definition.js";+import type { DynamicEvents, DynamicSentinel } from "#dynamic/definition.js";declare const DEFINED_AGENT: unique symbol;diff --git a/packages/eve/src/public/definitions/approval.ts b/packages/eve/src/public/definitions/approval.tsindex cd672c70f..87bb1711c 100644--- a/packages/eve/src/public/definitions/approval.ts+++ b/packages/eve/src/public/definitions/approval.ts@@ -1,100 +1,15 @@-import type { SessionAuthContext } from "#channel/types.js";-import type { SessionParent, SessionTurn } from "#context/keys.js";-import type { ToolAuthOptions, ToolAuthProvider } from "#public/definitions/tool.js";-import type { SessionContext } from "#public/definitions/callback-context.js";-import type { TokenResult } from "#shared/connection-types.js";--type ApprovalToolInput<TInput> = TInput extends object ? Readonly<TInput> : TInput;--/**- * Context passed to an {@link ApprovalPolicy} function.- *- * Extends {@link SessionContext} so approval policies can make decisions from- * the active session, current caller, and turn.- */-export interface ApprovalContext<TInput = Record<string, unknown>> extends SessionContext {- readonly approvedTools: ReadonlySet<string>;- readonly callId: string;- readonly toolInput?: ApprovalToolInput<TInput>;- readonly toolName: string;-}--/** Request-time approval decision returned by an {@link ApprovalPolicy}. */-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 };--/** Request-time approval policy shared by authored tools and connections. */-export type ApprovalPolicy<TInput = Record<string, unknown>> = (- ctx: ApprovalContext<TInput>,-) => ApprovalStatus | Promise<ApprovalStatus>;--/** Stable tool request passed to a response authorizer. */-export interface ApprovalRequest<TInput = Record<string, unknown>> {- readonly callId: string;- readonly requestId: string;- readonly toolInput?: ApprovalToolInput<TInput>;- readonly toolName: string;-}--/** Read-only session identity and lineage available to a response authorizer. */-export interface ApprovalResponseSession {- readonly id: string;- readonly initiator: SessionAuthContext | null;- readonly parent?: SessionParent;- readonly turn: SessionTurn;-}--/** Narrow authorization capability available while validating a responder. */-export interface ApprovalResponseAuth {- getToken(provider: ToolAuthProvider, options?: ToolAuthOptions): Promise<TokenResult>;- requireAuth(provider: ToolAuthProvider, options?: ToolAuthOptions): never;-}--/** Submitted decision passed to an approval response policy. */-export interface ApprovalResponse {- readonly decision: "approve";-}--/** Context passed to an approval response policy. */-export interface ApprovalResponseContext<TInput = Record<string, unknown>> {- readonly auth: ApprovalResponseAuth;- readonly request: ApprovalRequest<TInput>;- readonly response: ApprovalResponse;- readonly responder: SessionAuthContext;- readonly session: ApprovalResponseSession;-}--/** Response policy decision. Rejection keeps the shared request pending. */-export type ApprovalResponseDecision =- | { readonly status: "allowed" }- | { readonly reason: string; readonly status: "rejected" };--/** Decides whether an authenticated responder may approve one request. */-export type ApprovalResponsePolicy<TInput = Record<string, unknown>> = (- ctx: ApprovalResponseContext<TInput>,-) => ApprovalResponseDecision | Promise<ApprovalResponseDecision>;--/** Approval definition with request- and response-time policy. */-export interface ApprovalConfiguration<TInput = Record<string, unknown>> {- readonly request: ApprovalPolicy<TInput>;- readonly response?: ApprovalResponsePolicy<TInput>;-}--/** Shared approval definition used by authored tools and connections. */-export type Approval<TInput = Record<string, unknown>> =- | ApprovalPolicy<TInput>- | ApprovalConfiguration<TInput>;--/** Returns the request-time policy from either approval authoring shape. */-export function resolveApprovalPolicy<TInput>(approval: Approval<TInput>): ApprovalPolicy<TInput> {- return typeof approval === "function" ? approval : approval.request;-}+export type {+ Approval,+ ApprovalConfiguration,+ ApprovalContext,+ ApprovalPolicy,+ ApprovalRequest,+ ApprovalResponse,+ ApprovalResponseAuth,+ ApprovalResponseContext,+ ApprovalResponseDecision,+ ApprovalResponsePolicy,+ ApprovalResponseSession,+ ApprovalStatus,+} from "#approval/definition.js";+export { resolveApprovalPolicy } from "#approval/definition.js";diff --git a/packages/eve/src/public/definitions/callback-context.ts b/packages/eve/src/public/definitions/callback-context.tsindex 596ef0a94..71ed34a18 100644--- a/packages/eve/src/public/definitions/callback-context.ts+++ b/packages/eve/src/public/definitions/callback-context.ts@@ -1,36 +1,6 @@-import type { SkillHandle } from "#shared/skill-types.js";-import type { RuntimeSandboxSession } from "#shared/sandbox-session.js";-import type { SessionAuth, SessionParent, SessionTurn } from "#context/keys.js";--export type { SessionAuth, SessionParent, SessionTurn };--/**- * Shared runtime context available to all authored callbacks that run- * inside the ALS-scoped harness step (tools, hooks, channel events).- *- * Non-ALS callbacks (schedule `run`, sandbox `bootstrap`/`onSession`,- * instrumentation `setup`) do not receive this context. They get- * domain-specific arguments instead.- */-export interface SessionContext {- /**- * Active session metadata for the callback's exact durable session.- */- readonly session: {- readonly id: string;- readonly auth: SessionAuth;- readonly turn: SessionTurn;- readonly parent?: SessionParent;- };-- /**- * Resolves the session's sandbox. Throws when no sandbox is available- * in the current authored runtime context.- */- getSandbox(): Promise<RuntimeSandboxSession>;-- /**- * Returns a {@link SkillHandle} for the named authored skill.- */- getSkill(identifier: string): SkillHandle;-}+export type {+ SessionAuth,+ SessionContext,+ SessionParent,+ SessionTurn,+} from "#context/session-context.js";diff --git a/packages/eve/src/public/definitions/connections/mcp.ts b/packages/eve/src/public/definitions/connections/mcp.tsindex b6cc27d27..020c8d004 100644--- a/packages/eve/src/public/definitions/connections/mcp.ts+++ b/packages/eve/src/public/definitions/connections/mcp.ts@@ -7,7 +7,7 @@ import type { ConnectionToolCallDefinition } from "#public/definitions/connectioimport { normalizeAuthorizationSpec } from "#shared/validate-authorization.js";import { stampConnectionProtocol } from "#public/definitions/connections/protocol.js";import type { Approval } from "#public/definitions/approval.js";-import { stampDefinitionKey } from "#public/tool-result-narrowing.js";+import { stampDefinitionKey } from "#internal/authored-definition/source-identity.js";/*** Public definition for an MCP client connection authored indiff --git a/packages/eve/src/public/definitions/connections/openapi.ts b/packages/eve/src/public/definitions/connections/openapi.tsindex bcafeab66..defa56101 100644--- a/packages/eve/src/public/definitions/connections/openapi.ts+++ b/packages/eve/src/public/definitions/connections/openapi.ts@@ -6,7 +6,7 @@ import type {import { normalizeAuthorizationSpec } from "#shared/validate-authorization.js";import { stampConnectionProtocol } from "#public/definitions/connections/protocol.js";import type { Approval } from "#public/definitions/approval.js";-import { stampDefinitionKey } from "#public/tool-result-narrowing.js";+import { stampDefinitionKey } from "#internal/authored-definition/source-identity.js";import type { ConnectionToolCallDefinition } from "#public/definitions/connections/tool-call.js";/**diff --git a/packages/eve/src/public/definitions/exact.test.ts b/packages/eve/src/public/definitions/exact.test.tsindex 08e6bd13e..aa43a4e87 100644--- a/packages/eve/src/public/definitions/exact.test.ts+++ b/packages/eve/src/public/definitions/exact.test.ts@@ -24,11 +24,11 @@ import { defineSchedule } from "#public/definitions/schedule.js";import { defineSkill } from "#public/definitions/skill.js";import {defineTool,- experimental_workflow,type TaskReceipt,type TaskExec,type ToolDefinition,-} from "#public/definitions/tool.js";+} from "#public/tools/index.js";+import { experimental_workflow } from "#public/tools/workflow.js";describe("definition helper exact inputs", () => {it("preserves literal inference for valid definitions", () => {diff --git a/packages/eve/src/public/definitions/instructions.ts b/packages/eve/src/public/definitions/instructions.tsindex 916ceda94..100e3f0d0 100644--- a/packages/eve/src/public/definitions/instructions.ts+++ b/packages/eve/src/public/definitions/instructions.ts@@ -1,12 +1,14 @@-import { stampDefinitionKey } from "#public/tool-result-narrowing.js";+import { stampDefinitionKey } from "#internal/authored-definition/source-identity.js";import {DYNAMIC_SENTINEL_KIND,- INSTRUCTIONS_BRAND,type DynamicResolveContext,type DynamicSentinel,-} from "#shared/dynamic-tool-definition.js";+} from "#dynamic/definition.js";import type { ExactDefinition } from "#public/definitions/exact.js";-import type { PublicInstructionsDefinition } from "#shared/instructions-definition.js";+import {+ INSTRUCTIONS_BRAND,+ type PublicInstructionsDefinition,+} from "#shared/instructions-definition.js";export type InstructionsDefinition = Readonly<PublicInstructionsDefinition>;diff --git a/packages/eve/src/public/definitions/skill.ts b/packages/eve/src/public/definitions/skill.tsindex 0a4a057c0..4eabb4f91 100644--- a/packages/eve/src/public/definitions/skill.ts+++ b/packages/eve/src/public/definitions/skill.ts@@ -4,7 +4,7 @@ import type {SkillPackageDefinition,} from "#shared/skill-definition.js";import type { ExactDefinition } from "#public/definitions/exact.js";-import { SKILL_BRAND } from "#shared/dynamic-tool-definition.js";+import { SKILL_BRAND } from "#shared/skill-definition.js";export type { NamedSkillDefinition, SkillFileContent, SkillPackageDefinition };diff --git a/packages/eve/src/public/index.ts b/packages/eve/src/public/index.tsindex 84d8a7500..3e0191e24 100644--- a/packages/eve/src/public/index.ts+++ b/packages/eve/src/public/index.ts@@ -19,7 +19,7 @@ export {defineAgent,defineDynamic,} from "#public/definitions/agent.js";-export type { DynamicResolveContext, DynamicSentinel } from "#shared/dynamic-tool-definition.js";+export type { DynamicResolveContext, DynamicSentinel } from "#dynamic/definition.js";export {type RemoteAgentDefinition,type RemoteAgentDefinitionInput,diff --git a/packages/eve/src/public/instructions/index.ts b/packages/eve/src/public/instructions/index.tsindex c61e6e507..495e96d27 100644--- a/packages/eve/src/public/instructions/index.ts+++ b/packages/eve/src/public/instructions/index.ts@@ -11,4 +11,4 @@ export {type InstructionsDefinition,} from "#public/definitions/instructions.js";-export type { DynamicResolveContext, DynamicSentinel } from "#shared/dynamic-tool-definition.js";+export type { DynamicResolveContext, DynamicSentinel } from "#dynamic/definition.js";diff --git a/packages/eve/src/public/skills/index.ts b/packages/eve/src/public/skills/index.tsindex 4e2224a75..a67cdde89 100644--- a/packages/eve/src/public/skills/index.ts+++ b/packages/eve/src/public/skills/index.ts@@ -10,5 +10,5 @@ export {type SkillFileContent,type SkillPackageDefinition,} from "#public/definitions/skill.js";-export { defineDynamic } from "#public/definitions/tool.js";-export type { DynamicResolveContext, DynamicSentinel } from "#shared/dynamic-tool-definition.js";+export { defineDynamic } from "#dynamic/definition.js";+export type { DynamicResolveContext, DynamicSentinel } from "#dynamic/definition.js";diff --git a/packages/eve/src/public/tool-result-narrowing.ts b/packages/eve/src/public/tool-result-narrowing.tsdeleted file mode 100644index 2f7d41eb6..000000000--- a/packages/eve/src/public/tool-result-narrowing.ts+++ /dev/null@@ -1,201 +0,0 @@-import type { RuntimeActionResult } from "#shared/action-types.js";-import type { McpClientConnectionDefinition } from "#public/definitions/connections/mcp.js";-import type { ToolDefinition } from "#public/definitions/tool.js";--/**- * Narrowed tool result returned by {@link toolResultFrom} when the- * action result matches an authored {@link ToolDefinition}.- *- * `TOutput` is inferred from the tool definition's `execute` return type.- */-export interface MatchedToolResult<TOutput> {- readonly callId: string;- readonly output: TOutput;- readonly toolName: string;-}--/**- * Narrowed tool result returned by {@link toolResultFrom} when the- * action result matches an MCP connection.- *- * `output` stays `unknown` because MCP tool schemas are remote.- * `connectionToolName` is the unqualified MCP tool name (e.g.- * `"list_issues"`) while `toolName` is the full qualified name- * (e.g. `"linear__list_issues"`).- */-export interface MatchedConnectionResult {- readonly callId: string;- readonly connectionToolName: string;- readonly output: unknown;- readonly toolName: string;-}--/**- * Discriminated source entry stamped on authored definitions during- * agent resolution via {@link stampDefinitionSource}.- */-type DefinitionSourceEntry =- | { readonly kind: "connection"; readonly logicalPath?: string; readonly name: string }- | { readonly kind: "tool"; readonly logicalPath?: string; readonly name: string };--type AmbiguousDefinitionSourceEntry = { readonly kind: "ambiguous" };--/**- * Cross-instance symbol for reading the stable definition key stamped- * by `defineTool` / `defineMcpClientConnection`, then replaced with a- * source-derived key by the resolver when source metadata is available.- * `Symbol.for` ensures both the resolution pipeline's module copy and- * the user's import share the same property key.- */-const DEFINITION_KEY = Symbol.for("eve.definition-source-key");--/**- * Global registry mapping definition keys to their resolved runtime- * names. Rooted on `globalThis` via `Symbol.for` so every module- * copy shares one registry — same pattern as `context/key.ts`- * (`KEY_REGISTRY_GLOBAL_KEY`).- */-const REGISTRY_SYMBOL = Symbol.for("eve.definition-source-registry");--type DefinitionSourceRegistry = Map<string, DefinitionSourceEntry | AmbiguousDefinitionSourceEntry>;--type RegistryGlobal = typeof globalThis & {- [REGISTRY_SYMBOL]?: DefinitionSourceRegistry;-};--const registryContainer = globalThis as RegistryGlobal;--if (registryContainer[REGISTRY_SYMBOL] === undefined) {- registryContainer[REGISTRY_SYMBOL] = new Map();-}--const definitionSourceRegistry = registryContainer[REGISTRY_SYMBOL];--/**- * Stamps a stable key on the definition so it can be identified across- * module instances. Definition helpers first stamp an authoring-time- * fallback key; the resolver overwrites it with a source-derived key.- */-export function stampDefinitionKey(definition: object, key: string): void {- Object.defineProperty(definition, DEFINITION_KEY, { configurable: true, value: key });-}--/**- * Reads the stable key from a definition, or `undefined` if unstamped.- */-function readDefinitionKey(definition: object): string | undefined {- if (DEFINITION_KEY in definition) {- return (definition as Record<symbol, string>)[DEFINITION_KEY];- }- return undefined;-}--/**- * Registers a definition key → source entry mapping in the global- * registry. Called by the resolution pipeline after loading the- * authored module.- */-export function registerDefinitionSource(key: string, entry: DefinitionSourceEntry): void {- const existing = definitionSourceRegistry.get(key);- if (existing !== undefined && !sameDefinitionSourceEntry(existing, entry)) {- if (existing.kind !== "ambiguous") {- console.warn(- [- `eve could not assign a unique toolResultFrom identity for ${JSON.stringify(key)}.`,- `Conflicting definitions: ${formatDefinitionSourceForWarning(existing)} and ${formatDefinitionSourceForWarning(entry)}.`,- "Multiple authored definitions share that fallback identity, so toolResultFrom will not match through it.",- "Use the original definition object loaded by eve so source-derived identity can be used instead.",- ].join(" "),- );- }- definitionSourceRegistry.set(key, { kind: "ambiguous" });- return;- }- definitionSourceRegistry.set(key, entry);-}--function sameDefinitionSourceEntry(- a: DefinitionSourceEntry | AmbiguousDefinitionSourceEntry,- b: DefinitionSourceEntry,-): boolean {- if (a.kind !== b.kind) return false;- return a.name === b.name;-}--function formatDefinitionSourceForWarning(entry: DefinitionSourceEntry): string {- if (entry.logicalPath === undefined) {- return `${entry.kind} "${entry.name}"`;- }- return `${entry.kind} "${entry.name}" from "${entry.logicalPath}"`;-}--const CONNECTION_TOOL_SEPARATOR = "__";--/**- * Overloaded signature for {@link toolResultFrom}.- */-export interface ToolResultFromFn {- <TInput, TOutput>(- result: RuntimeActionResult,- tool: ToolDefinition<TInput, TOutput>,- ): MatchedToolResult<TOutput> | undefined;-- (- result: RuntimeActionResult,- connection: McpClientConnectionDefinition,- ): MatchedConnectionResult | undefined;-}--/**- * Narrows a {@link RuntimeActionResult} to a typed tool or connection- * result by matching against an authored definition object.- *- * Pass a `ToolDefinition` to get a typed `output`; pass a- * `McpClientConnectionDefinition` to match any tool from that- * connection (`output` stays `unknown`).- *- * Returns `undefined` when the result doesn't match, or when- * `isError` is `true`.- */-export const toolResultFrom: ToolResultFromFn = toolResultFromImpl;--function toolResultFromImpl<TInput, TOutput>(- result: RuntimeActionResult,- tool: ToolDefinition<TInput, TOutput>,-): MatchedToolResult<TOutput> | undefined;-function toolResultFromImpl(- result: RuntimeActionResult,- connection: McpClientConnectionDefinition,-): MatchedConnectionResult | undefined;-function toolResultFromImpl(- result: RuntimeActionResult,- source: ToolDefinition<unknown, unknown> | McpClientConnectionDefinition,-): MatchedToolResult<unknown> | MatchedConnectionResult | undefined {- if (result.kind !== "tool-result") return undefined;- if (result.isError === true) return undefined;-- const key = readDefinitionKey(source);- if (key === undefined) return undefined;-- const entry = definitionSourceRegistry.get(key);- if (entry === undefined) return undefined;- if (entry.kind === "ambiguous") return undefined;-- if (entry.kind === "tool") {- if (result.toolName !== entry.name) return undefined;- return {- callId: result.callId,- output: result.output,- toolName: result.toolName,- };- }-- const prefix = entry.name + CONNECTION_TOOL_SEPARATOR;- if (!result.toolName.startsWith(prefix)) return undefined;- return {- callId: result.callId,- connectionToolName: result.toolName.slice(prefix.length),- output: result.output,- toolName: result.toolName,- };-}diff --git a/packages/eve/src/public/tools/agent.ts b/packages/eve/src/public/tools/agent.tsdeleted file mode 100644index 17fe8ece0..000000000--- a/packages/eve/src/public/tools/agent.ts+++ /dev/null@@ -1,13 +0,0 @@-import { defineTool } from "#public/definitions/tool.js";-import { AGENT_TOOL_DESCRIPTION, SUBAGENT_TOOL_INPUT_SCHEMA } from "#shared/agent-tool.js";--/** Canonical PR 1 source definition; durable execution remains in the harness. */-export const agent = defineTool({- description: AGENT_TOOL_DESCRIPTION,- inputSchema: SUBAGENT_TOOL_INPUT_SCHEMA,- execute() {- throw new Error("agent is handled by eve's durable dispatch step.");- },-});--export default agent;diff --git a/packages/eve/src/public/tools/approval/index.ts b/packages/eve/src/public/tools/approval/index.tsindex 88153a742..3f2af7e29 100644--- a/packages/eve/src/public/tools/approval/index.ts+++ b/packages/eve/src/public/tools/approval/index.ts@@ -2,5 +2,18 @@* Per-tool approval helpers used inside `agent/tools/*.ts` files.*/-export type { Approval, ApprovalContext, ApprovalStatus } from "#public/definitions/approval.js";-export { always, never, once } from "#public/tools/approval/approval-helpers.js";+export type {+ Approval,+ ApprovalConfiguration,+ ApprovalContext,+ ApprovalPolicy,+ ApprovalRequest,+ ApprovalResponse,+ ApprovalResponseAuth,+ ApprovalResponseContext,+ ApprovalResponseDecision,+ ApprovalResponsePolicy,+ ApprovalResponseSession,+ ApprovalStatus,+} from "#public/definitions/approval.js";+export { always, never, once } from "#tools/approval/policies.js";diff --git a/packages/eve/src/public/tools/bash.ts b/packages/eve/src/public/tools/bash.tsindex 458822281..58fb3939e 100644--- a/packages/eve/src/public/tools/bash.ts+++ b/packages/eve/src/public/tools/bash.ts@@ -1,2 +1,11 @@-export { default } from "#tools/bash.js";-export * from "#tools/bash.js";+import bashDefinition from "#tools/provided/bash.js";++export {+ BASH_INPUT_SCHEMA,+ BASH_OUTPUT_SCHEMA,+ type BashToolInput,+ type BashToolOutput,+ bash,+} from "#tools/provided/bash.js";++export default bashDefinition;diff --git a/packages/eve/src/public/tools/connection-search.ts b/packages/eve/src/public/tools/connection-search.tsdeleted file mode 100644index 51345e200..000000000--- a/packages/eve/src/public/tools/connection-search.ts+++ /dev/null@@ -1,2 +0,0 @@-export { default } from "#tools/connection-search.js";-export * from "#tools/connection-search.js";diff --git a/packages/eve/src/public/tools/define-bash-tool.ts b/packages/eve/src/public/tools/define-bash-tool.tsdeleted file mode 100644index 160f4237f..000000000--- a/packages/eve/src/public/tools/define-bash-tool.ts+++ /dev/null@@ -1 +0,0 @@-export * from "#tools/define-bash-tool.js";diff --git a/packages/eve/src/public/tools/define-glob-tool.ts b/packages/eve/src/public/tools/define-glob-tool.tsdeleted file mode 100644index b7d86a316..000000000--- a/packages/eve/src/public/tools/define-glob-tool.ts+++ /dev/null@@ -1 +0,0 @@-export * from "#tools/define-glob-tool.js";diff --git a/packages/eve/src/public/tools/define-grep-tool.ts b/packages/eve/src/public/tools/define-grep-tool.tsdeleted file mode 100644index b44a6e26b..000000000--- a/packages/eve/src/public/tools/define-grep-tool.ts+++ /dev/null@@ -1 +0,0 @@-export * from "#tools/define-grep-tool.js";diff --git a/packages/eve/src/public/tools/define-read-file-tool.ts b/packages/eve/src/public/tools/define-read-file-tool.tsdeleted file mode 100644index 13de98acb..000000000--- a/packages/eve/src/public/tools/define-read-file-tool.ts+++ /dev/null@@ -1 +0,0 @@-export * from "#tools/define-read-file-tool.js";diff --git a/packages/eve/src/public/tools/define-write-file-tool.ts b/packages/eve/src/public/tools/define-write-file-tool.tsdeleted file mode 100644index f80e01040..000000000--- a/packages/eve/src/public/tools/define-write-file-tool.ts+++ /dev/null@@ -1 +0,0 @@-export * from "#tools/define-write-file-tool.js";diff --git a/packages/eve/src/public/tools/glob.ts b/packages/eve/src/public/tools/glob.tsindex 277304d60..e77cc4691 100644--- a/packages/eve/src/public/tools/glob.ts+++ b/packages/eve/src/public/tools/glob.ts@@ -1,2 +1,11 @@-export { default } from "#tools/glob.js";-export * from "#tools/glob.js";+import globDefinition from "#tools/provided/glob.js";++export {+ GLOB_INPUT_SCHEMA,+ GLOB_OUTPUT_SCHEMA,+ type GlobToolInput,+ type GlobToolOutput,+ glob,+} from "#tools/provided/glob.js";++export default globDefinition;diff --git a/packages/eve/src/public/tools/grep.ts b/packages/eve/src/public/tools/grep.tsindex e4b0743fc..99253f68c 100644--- a/packages/eve/src/public/tools/grep.ts+++ b/packages/eve/src/public/tools/grep.ts@@ -1,2 +1,11 @@-export { default } from "#tools/grep.js";-export * from "#tools/grep.js";+import grepDefinition from "#tools/provided/grep.js";++export {+ GREP_INPUT_SCHEMA,+ GREP_OUTPUT_SCHEMA,+ type GrepToolInput,+ type GrepToolOutput,+ grep,+} from "#tools/provided/grep.js";++export default grepDefinition;diff --git a/packages/eve/src/public/tools/index.ts b/packages/eve/src/public/tools/index.tsindex e2f885be0..fcd6367d0 100644--- a/packages/eve/src/public/tools/index.ts+++ b/packages/eve/src/public/tools/index.ts@@ -5,14 +5,9 @@export {type BackgroundToolDefinition,type DisabledToolSentinel,- type ExperimentalWorkflowToolDefinition,- type ExperimentalWorkflowToolInput,- defineDynamic,defineTool,disableTool,- experimental_workflow,isDisabledToolSentinel,- isExperimentalWorkflowToolDefinition,type TaskBinding,type TaskDelegated,type TaskExec,@@ -24,52 +19,20 @@ export {type ToolContext,type ToolModelOutput,type ToolModelOutputPart,-} from "#public/definitions/tool.js";-export { toolOutput, toolOutputPart } from "#public/tools/output-builders.js";-export type {- Approval,- ApprovalConfiguration,- ApprovalContext,- ApprovalPolicy,- ApprovalRequest,- ApprovalResponse,- ApprovalResponseAuth,- ApprovalResponseContext,- ApprovalResponseDecision,- ApprovalResponsePolicy,- ApprovalResponseSession,- ApprovalStatus,-} from "#public/definitions/approval.js";+} from "#tools/definition.js";+export { defineDynamic } from "#dynamic/definition.js";+export { toolOutput, toolOutputPart } from "#tools/model-output.js";+export type { DynamicEvents, DynamicResolveContext, DynamicSentinel } from "#dynamic/definition.js";export type {DynamicToolEntry,- DynamicEvents,DynamicToolEvents,- DynamicResolveContext,- DynamicSentinel,DynamicToolSet,DynamicToolResult,-} from "#shared/dynamic-tool-definition.js";+} from "#tools/dynamic.js";export { type SessionContext } from "#public/definitions/callback-context.js";export {toolResultFrom,type MatchedConnectionResult,type MatchedToolResult,type ToolResultFromFn,-} from "#public/tool-result-narrowing.js";-export { type DefineBashToolInput, defineBashTool } from "#public/tools/define-bash-tool.js";-export { type DefineGlobToolInput, defineGlobTool } from "#public/tools/define-glob-tool.js";-export { type DefineGrepToolInput, defineGrepTool } from "#public/tools/define-grep-tool.js";-export {- type DefineReadFileToolInput,- defineReadFileTool,-} from "#public/tools/define-read-file-tool.js";-export {- type DefineWriteFileToolInput,- defineWriteFileTool,-} from "#public/tools/define-write-file-tool.js";-export {- type WebSearchProvider,- type WebSearchToolDefinition,- type WebSearchToolInput,- webSearch,-} from "#public/tools/web-search.js";+} from "#public/tools/result.js";diff --git a/packages/eve/src/public/tools/load-skill.ts b/packages/eve/src/public/tools/load-skill.tsindex 9d35f74e9..05caf970b 100644--- a/packages/eve/src/public/tools/load-skill.ts+++ b/packages/eve/src/public/tools/load-skill.ts@@ -1,2 +1,5 @@-export { default } from "#tools/load-skill.js";-export * from "#tools/load-skill.js";+import loadSkillDefinition from "#tools/provided/load-skill.js";++export { loadSkill } from "#tools/provided/load-skill.js";++export default loadSkillDefinition;diff --git a/packages/eve/src/public/tools/read-file.ts b/packages/eve/src/public/tools/read-file.tsindex bd05bdd50..deeda1038 100644--- a/packages/eve/src/public/tools/read-file.ts+++ b/packages/eve/src/public/tools/read-file.ts@@ -1,2 +1,11 @@-export { default } from "#tools/read-file.js";-export * from "#tools/read-file.js";+import readFileDefinition from "#tools/provided/read-file.js";++export {+ READ_FILE_INPUT_SCHEMA,+ READ_FILE_OUTPUT_SCHEMA,+ type ReadFileToolInput,+ type ReadFileToolOutput,+ readFile,+} from "#tools/provided/read-file.js";++export default readFileDefinition;diff --git a/packages/eve/src/public/tool-result-narrowing.test.ts b/packages/eve/src/public/tools/result.test.tssimilarity index 98%rename from packages/eve/src/public/tool-result-narrowing.test.tsrename to packages/eve/src/public/tools/result.test.tsindex dcbf62712..cc810cdc9 100644--- a/packages/eve/src/public/tool-result-narrowing.test.ts+++ b/packages/eve/src/public/tools/result.test.ts@@ -3,14 +3,16 @@ import { z } from "#compiled/zod/index.js";import type { RuntimeActionResult } from "#shared/action-types.js";import { defineMcpClientConnection } from "#public/definitions/connections/mcp.js";-import { defineTool } from "#public/definitions/tool.js";+import { defineTool } from "#tools/definition.js";import {- toolResultFrom,registerDefinitionSource,stampDefinitionKey,+} from "#internal/authored-definition/source-identity.js";+import {+ toolResultFrom,type MatchedConnectionResult,type MatchedToolResult,-} from "#public/tool-result-narrowing.js";+} from "#public/tools/result.js";afterEach(() => {vi.restoreAllMocks();diff --git a/packages/eve/src/public/tools/result.ts b/packages/eve/src/public/tools/result.tsnew file mode 100644index 000000000..4ef28c6a3--- /dev/null+++ b/packages/eve/src/public/tools/result.ts@@ -0,0 +1,100 @@+import type { RuntimeActionResult } from "#shared/action-types.js";+import type { McpClientConnectionDefinition } from "#public/definitions/connections/mcp.js";+import { readDefinitionSource } from "#internal/authored-definition/source-identity.js";+import type { ToolDefinition } from "#tools/definition.js";++/**+ * Narrowed tool result returned by {@link toolResultFrom} when the+ * action result matches an authored {@link ToolDefinition}.+ *+ * `TOutput` is inferred from the tool definition's `execute` return type.+ */+export interface MatchedToolResult<TOutput> {+ readonly callId: string;+ readonly output: TOutput;+ readonly toolName: string;+}++/**+ * Narrowed tool result returned by {@link toolResultFrom} when the+ * action result matches an MCP connection.+ *+ * `output` stays `unknown` because MCP tool schemas are remote.+ * `connectionToolName` is the unqualified MCP tool name (e.g.+ * `"list_issues"`) while `toolName` is the full qualified name+ * (e.g. `"linear__list_issues"`).+ */+export interface MatchedConnectionResult {+ readonly callId: string;+ readonly connectionToolName: string;+ readonly output: unknown;+ readonly toolName: string;+}++const CONNECTION_TOOL_SEPARATOR = "__";++/**+ * Overloaded signature for {@link toolResultFrom}.+ */+export interface ToolResultFromFn {+ <TInput, TOutput>(+ result: RuntimeActionResult,+ tool: ToolDefinition<TInput, TOutput>,+ ): MatchedToolResult<TOutput> | undefined;++ (+ result: RuntimeActionResult,+ connection: McpClientConnectionDefinition,+ ): MatchedConnectionResult | undefined;+}++/**+ * Narrows a {@link RuntimeActionResult} to a typed tool or connection+ * result by matching against an authored definition object.+ *+ * Pass a `ToolDefinition` to get a typed `output`; pass a+ * `McpClientConnectionDefinition` to match any tool from that+ * connection (`output` stays `unknown`).+ *+ * Returns `undefined` when the result doesn't match, or when+ * `isError` is `true`.+ */+export const toolResultFrom: ToolResultFromFn = toolResultFromImpl;++function toolResultFromImpl<TInput, TOutput>(+ result: RuntimeActionResult,+ tool: ToolDefinition<TInput, TOutput>,+): MatchedToolResult<TOutput> | undefined;+function toolResultFromImpl(+ result: RuntimeActionResult,+ connection: McpClientConnectionDefinition,+): MatchedConnectionResult | undefined;+function toolResultFromImpl(+ result: RuntimeActionResult,+ source: ToolDefinition<unknown, unknown> | McpClientConnectionDefinition,+): MatchedToolResult<unknown> | MatchedConnectionResult | undefined {+ if (result.kind !== "tool-result") return undefined;+ if (result.isError === true) return undefined;++ const entry = readDefinitionSource(source);+ if (entry === undefined) return undefined;+ if (entry.kind === "ambiguous") return undefined;++ if (entry.kind === "tool") {+ if (result.toolName !== entry.name) return undefined;+ return {+ callId: result.callId,+ output: result.output,+ toolName: result.toolName,+ };+ }++ const prefix = entry.name + CONNECTION_TOOL_SEPARATOR;+ if (!result.toolName.startsWith(prefix)) return undefined;+ return {+ callId: result.callId,+ connectionToolName: result.toolName.slice(prefix.length),+ output: result.output,+ toolName: result.toolName,+ };+}diff --git a/packages/eve/src/public/tools/sleep.ts b/packages/eve/src/public/tools/sleep.tsnew file mode 100644index 000000000..24e439a35--- /dev/null+++ b/packages/eve/src/public/tools/sleep.ts@@ -0,0 +1 @@+export { type SleepToolInput, type SleepToolOutput, sleep } from "#tools/provided/sleep.js";diff --git a/packages/eve/src/public/tools/sleep/index.ts b/packages/eve/src/public/tools/sleep/index.tsdeleted file mode 100644index 52867824a..000000000--- a/packages/eve/src/public/tools/sleep/index.ts+++ /dev/null@@ -1 +0,0 @@-export * from "#tools/sleep.js";diff --git a/packages/eve/src/public/tools/todo.ts b/packages/eve/src/public/tools/todo.tsindex e526f0206..a4c805d57 100644--- a/packages/eve/src/public/tools/todo.ts+++ b/packages/eve/src/public/tools/todo.ts@@ -1,2 +1,5 @@-export { default } from "#tools/todo.js";-export * from "#tools/todo.js";+import todoDefinition from "#tools/provided/todo.js";++export { todo } from "#tools/provided/todo.js";++export default todoDefinition;diff --git a/packages/eve/src/public/tools/web-fetch.ts b/packages/eve/src/public/tools/web-fetch.tsindex ac44ce55f..816e7870a 100644--- a/packages/eve/src/public/tools/web-fetch.ts+++ b/packages/eve/src/public/tools/web-fetch.ts@@ -1,2 +1,11 @@-export { default } from "#tools/web-fetch.js";-export * from "#tools/web-fetch.js";+import webFetchDefinition from "#tools/provided/web-fetch.js";++export {+ WEB_FETCH_INPUT_SCHEMA,+ WEB_FETCH_OUTPUT_SCHEMA,+ type WebFetchToolInput,+ type WebFetchToolOutput,+ webFetch,+} from "#tools/provided/web-fetch.js";++export default webFetchDefinition;diff --git a/packages/eve/src/public/tools/web-search.ts b/packages/eve/src/public/tools/web-search.tsindex 443b9bb3c..2d68f3114 100644--- a/packages/eve/src/public/tools/web-search.ts+++ b/packages/eve/src/public/tools/web-search.ts@@ -1,53 +1,12 @@-import type { WebSearchProvider } from "#shared/web-search.js";--export type { WebSearchProvider };--const WEB_SEARCH_TOOL_KIND = "eve:web-search-tool";--/** Configuration accepted by {@link webSearch}. */-export interface WebSearchToolInput {- /** Provider to use when the agent model is routed through AI Gateway. */- readonly provider: WebSearchProvider;-}--/**- * Provider-managed web search configuration.- *- * Export this from `agent/tools/web_search.ts` to select the AI Gateway- * search provider for that agent. Direct provider models continue to use- * their native web search implementation.- */-export interface WebSearchToolDefinition {- readonly kind: typeof WEB_SEARCH_TOOL_KIND;- readonly provider: WebSearchProvider;-}--/**- * Configures the framework-provided `web_search` tool.- *- * When no configuration file is present, eve uses Exa for AI Gateway- * models.- *- * @example- * ```ts- * // agent/tools/web_search.ts- * import { webSearch } from "eve/tools";- *- * export default webSearch({ provider: "parallel" });- * ```- */-export function webSearch(input: WebSearchToolInput): WebSearchToolDefinition {- return {- kind: WEB_SEARCH_TOOL_KIND,- provider: input.provider,- };-}--/** Returns whether a value is a provider-managed web search definition. */-export function isWebSearchToolDefinition(value: unknown): value is WebSearchToolDefinition {- return (- typeof value === "object" &&- value !== null &&- (value as { kind?: unknown }).kind === WEB_SEARCH_TOOL_KIND- );-}+import webSearchDefinition from "#tools/provided/web-search.js";++export {+ type WebSearchProvider,+ type WebSearchToolDefinition,+ type WebSearchToolInput,+ defaultWebSearch,+ isWebSearchToolDefinition,+ webSearch,+} from "#tools/provided/web-search.js";++export default webSearchDefinition;diff --git a/packages/eve/src/public/tools/workflow.ts b/packages/eve/src/public/tools/workflow.tsnew file mode 100644index 000000000..dac481cfe--- /dev/null+++ b/packages/eve/src/public/tools/workflow.ts@@ -0,0 +1,10 @@+/**+ * Experimental Workflow tool authoring helpers.+ */++export {+ type ExperimentalWorkflowToolDefinition,+ type ExperimentalWorkflowToolInput,+ experimental_workflow,+ isExperimentalWorkflowToolDefinition,+} from "#tools/workflow.js";diff --git a/packages/eve/src/public/tools/write-file.ts b/packages/eve/src/public/tools/write-file.tsindex f45071009..1be9fcb51 100644--- a/packages/eve/src/public/tools/write-file.ts+++ b/packages/eve/src/public/tools/write-file.ts@@ -1,2 +1,11 @@-export { default } from "#tools/write-file.js";-export * from "#tools/write-file.js";+import writeFileDefinition from "#tools/provided/write-file.js";++export {+ WRITE_FILE_INPUT_SCHEMA,+ WRITE_FILE_OUTPUT_SCHEMA,+ type WriteFileToolInput,+ type WriteFileToolOutput,+ writeFile,+} from "#tools/provided/write-file.js";++export default writeFileDefinition;diff --git a/packages/eve/src/public/types/json.ts b/packages/eve/src/public/types/json.tsindex 9c74ad5dc..f7667e453 100644--- a/packages/eve/src/public/types/json.ts+++ b/packages/eve/src/public/types/json.ts@@ -1,33 +1 @@-/**- * Shared JSON primitive used by public eve APIs that need to declare- * author-supplied values as JSON-serializable.- *- * The canonical use site is {@link AuthorizationDefinition}, whose- * `State` type is constrained to {@link JsonValue} so that state- * journaled by WDK between `startAuthorization` and- * `completeAuthorization` is guaranteed round-trippable through a- * serializer. Kept in a dedicated module so any future public- * interface with the same serialization requirement can reuse it- * without depending on a connection-specific module.- */--/**- * Recursive type describing any JSON-serializable value.- *- * Accepted: `string`, `number`, `boolean`, `null`, arrays of- * {@link JsonValue}, and objects whose string keys map to- * {@link JsonValue}. All containers are marked `readonly` so authored- * code treats the value as immutable at the type level.- *- * Rejected (at compile time): `undefined`, functions, `Date`, class- * instances, `Map`, `Set`, `bigint`, and symbols. These cannot survive- * a `JSON.stringify(...)` / `JSON.parse(...)` round trip and must not- * cross a durable step boundary.- */-export type JsonValue =- | string- | number- | boolean- | null- | readonly JsonValue[]- | { readonly [key: string]: JsonValue };+export type { JsonValue } from "#shared/json.js";diff --git a/packages/eve/src/runtime/agent/bootstrap.test.ts b/packages/eve/src/runtime/agent/bootstrap.test.tsindex 106f4f658..ca6a73a80 100644--- a/packages/eve/src/runtime/agent/bootstrap.test.ts+++ b/packages/eve/src/runtime/agent/bootstrap.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from "vitest";import { createResolvedRuntimeTurnAgent } from "#runtime/agent/bootstrap.js";-import { AGENT_TOOL_NAME } from "#shared/agent-tool.js";+import { AGENT_TOOL_NAME } from "#tools/framework/agent-contract.js";import { ROOT_RUNTIME_AGENT_NODE_ID } from "#runtime/graph.js";import type { ResolvedAgent } from "#runtime/types.js";import type { PreparedRuntimeTool } from "#runtime/sessions/turn.js";diff --git a/packages/eve/src/runtime/agent/bootstrap.ts b/packages/eve/src/runtime/agent/bootstrap.tsindex c9a6c4f94..a6e426c53 100644--- a/packages/eve/src/runtime/agent/bootstrap.ts+++ b/packages/eve/src/runtime/agent/bootstrap.ts@@ -1,6 +1,6 @@import type { ModelMessage } from "ai";-import { AGENT_TOOL_NAME } from "#shared/agent-tool.js";+import { AGENT_TOOL_NAME } from "#tools/framework/agent-contract.js";import { composeRuntimeBasePrompt } from "#runtime/prompt/compose.js";import type { PreparedRuntimeTool } from "#runtime/sessions/turn.js";import type { ResolvedAgent, ResolvedAgentDefinition } from "#runtime/types.js";diff --git a/packages/eve/src/runtime/agent/resolve-model.test.ts b/packages/eve/src/runtime/agent/resolve-model.test.tsindex 32f90992d..19e8eed76 100644--- a/packages/eve/src/runtime/agent/resolve-model.test.ts+++ b/packages/eve/src/runtime/agent/resolve-model.test.ts@@ -6,7 +6,7 @@ import type { CompiledModuleMap } from "#compiler/module-map.js";import { ContextContainer } from "#context/container.js";import { RuntimeModelMetadataCacheKey } from "#context/keys.js";import { deserializeContext, serializeContext } from "#context/serialize.js";-import { defineDynamic } from "#public/definitions/tool.js";+import { defineDynamic } from "#dynamic/definition.js";import type { RuntimeModelCatalog } from "#runtime/agent/model-catalog.js";import {loadDynamicRuntimeModelDefinition,diff --git a/packages/eve/src/runtime/connections/mcp-client.test.ts b/packages/eve/src/runtime/connections/mcp-client.test.tsindex f9539367b..4ebe89520 100644--- a/packages/eve/src/runtime/connections/mcp-client.test.ts+++ b/packages/eve/src/runtime/connections/mcp-client.test.ts@@ -5,8 +5,8 @@ import { AuthKey, SessionKey, type SessionAuthContext } from "#context/keys.js";import {isConnectionAuthorizationFailedError,isConnectionAuthorizationRequiredError,-} from "#public/connections/errors.js";-import type { SessionContext } from "#public/definitions/callback-context.js";+} from "#connections/errors.js";+import type { SessionContext } from "#context/session-context.js";import type { ResolvedConnectionDefinition } from "#runtime/types.js";import { ConnectionAuthorizationTokensKey } from "#runtime/connections/authorization-tokens.js";import {diff --git a/packages/eve/src/runtime/connections/mcp-client.ts b/packages/eve/src/runtime/connections/mcp-client.tsindex f3c616f50..a628e27ec 100644--- a/packages/eve/src/runtime/connections/mcp-client.ts+++ b/packages/eve/src/runtime/connections/mcp-client.ts@@ -2,8 +2,8 @@ import { createMCPClient, type MCPClient } from "#compiled/@ai-sdk/mcp/index.js"import type { ToolSet } from "ai";import { buildCallbackContext } from "#context/build-callback-context.js";-import { ConnectionAuthorizationRequiredError } from "#public/connections/errors.js";-import type { SessionContext } from "#public/definitions/callback-context.js";+import { ConnectionAuthorizationRequiredError } from "#connections/errors.js";+import type { SessionContext } from "#context/session-context.js";import type { ResolvedConnectionDefinition } from "#runtime/types.js";import { evictScopedToken, resolveScopedToken } from "#runtime/connections/scoped-authorization.js";import { resolveConnectionAuthorization } from "#runtime/connections/resolve-authorization.js";diff --git a/packages/eve/src/runtime/connections/openapi-client.test.ts b/packages/eve/src/runtime/connections/openapi-client.test.tsindex 9e9150a0a..475b4874d 100644--- a/packages/eve/src/runtime/connections/openapi-client.test.ts+++ b/packages/eve/src/runtime/connections/openapi-client.test.ts@@ -2,7 +2,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";import { contextStorage, ContextContainer } from "#context/container.js";import { AuthKey, SessionKey, type SessionAuthContext } from "#context/keys.js";-import type { SessionContext } from "#public/definitions/callback-context.js";+import type { SessionContext } from "#context/session-context.js";import type { ResolvedConnectionDefinition } from "#runtime/types.js";import { OpenApiConnectionClient } from "#runtime/connections/openapi-client.js";diff --git a/packages/eve/src/runtime/connections/openapi-client.ts b/packages/eve/src/runtime/connections/openapi-client.tsindex ced4a779e..9226beb8e 100644--- a/packages/eve/src/runtime/connections/openapi-client.ts+++ b/packages/eve/src/runtime/connections/openapi-client.ts@@ -30,7 +30,7 @@ import type {ConnectionToolMetadata,} from "#shared/connection-types.js";import { isObject } from "#shared/guards.js";-import { toInputSchema, type ToolSchema } from "#shared/tool-schema.js";+import { toInputSchema, type ToolSchema } from "#tools/schema.js";import { isLoopbackHostname } from "#shared/network-address.js";const log = createLogger("runtime.connections.openapi-client");diff --git a/packages/eve/src/runtime/connections/principal.test.ts b/packages/eve/src/runtime/connections/principal.test.tsindex d72e47fea..08fd9957a 100644--- a/packages/eve/src/runtime/connections/principal.test.ts+++ b/packages/eve/src/runtime/connections/principal.test.ts@@ -5,7 +5,7 @@ import { AuthKey, type SessionAuthContext } from "#context/keys.js";import {ConnectionAuthorizationFailedError,isConnectionAuthorizationFailedError,-} from "#public/connections/errors.js";+} from "#connections/errors.js";import { principalKey, resolveConnectionPrincipal } from "#runtime/connections/principal.js";import type { AuthorizationDefinition } from "#shared/connection-types.js";diff --git a/packages/eve/src/runtime/connections/principal.ts b/packages/eve/src/runtime/connections/principal.tsindex 0192ab80c..a504ce608 100644--- a/packages/eve/src/runtime/connections/principal.ts+++ b/packages/eve/src/runtime/connections/principal.ts@@ -12,7 +12,7 @@import { type AlsContext, contextStorage } from "#context/container.js";import { AuthKey, type SessionAuthContext } from "#context/keys.js";-import { ConnectionAuthorizationFailedError } from "#public/connections/errors.js";+import { ConnectionAuthorizationFailedError } from "#connections/errors.js";import type { AuthorizationDefinition, ConnectionPrincipal } from "#shared/connection-types.js";import { isVercelOidcIssuer } from "#shared/vercel-project.js";diff --git a/packages/eve/src/runtime/connections/registry-types.ts b/packages/eve/src/runtime/connections/registry-types.tsindex e3f4a29ce..a93d7350b 100644--- a/packages/eve/src/runtime/connections/registry-types.ts+++ b/packages/eve/src/runtime/connections/registry-types.ts@@ -1,4 +1,4 @@-import type { Approval } from "#public/definitions/approval.js";+import type { Approval } from "#approval/definition.js";import type { ConnectionClient } from "#shared/connection-types.js";import type { ResolvedConnectionDefinition } from "#runtime/types.js";diff --git a/packages/eve/src/runtime/connections/registry.ts b/packages/eve/src/runtime/connections/registry.tsindex f19b73b78..a1853b3ab 100644--- a/packages/eve/src/runtime/connections/registry.ts+++ b/packages/eve/src/runtime/connections/registry.ts@@ -1,4 +1,4 @@-import type { Approval } from "#public/definitions/approval.js";+import type { Approval } from "#approval/definition.js";import type { ResolvedConnectionDefinition } from "#runtime/types.js";import { McpConnectionClient } from "#runtime/connections/mcp-client.js";import { OpenApiConnectionClient } from "#runtime/connections/openapi-client.js";diff --git a/packages/eve/src/runtime/connections/resolve-authorization.ts b/packages/eve/src/runtime/connections/resolve-authorization.tsindex bfbe83942..d1e0916b4 100644--- a/packages/eve/src/runtime/connections/resolve-authorization.ts+++ b/packages/eve/src/runtime/connections/resolve-authorization.ts@@ -1,7 +1,7 @@import { buildCallbackContext } from "#context/build-callback-context.js";import { type AlsContext, ContextContainer, contextStorage } from "#context/container.js";import { ContextKey } from "#context/key.js";-import type { SessionContext } from "#public/definitions/callback-context.js";+import type { SessionContext } from "#context/session-context.js";import type { ResolvedConnectionDefinition } from "#runtime/types.js";import type { AuthorizationDefinition } from "#shared/connection-types.js";import { normalizeAuthorizationSpec } from "#shared/validate-authorization.js";diff --git a/packages/eve/src/runtime/connections/scoped-authorization.ts b/packages/eve/src/runtime/connections/scoped-authorization.tsindex a473aaf80..67d1f9b13 100644--- a/packages/eve/src/runtime/connections/scoped-authorization.ts+++ b/packages/eve/src/runtime/connections/scoped-authorization.ts@@ -11,14 +11,14 @@*/import { type AlsContext, contextStorage, loadContext } from "#context/container.js";-import type { ConnectionAuthorizationChallenge } from "#public/connections/errors.js";+import type { ConnectionAuthorizationChallenge } from "#connections/errors.js";import {type AuthorizationSignal,consumeAuthorizationResult,createAuthorizationAttempt,requestAuthorization,} from "#harness/authorization.js";-import type { JsonValue } from "#public/types/json.js";+import type { JsonValue } from "#shared/json.js";import {evictCachedToken,readCachedToken,diff --git a/packages/eve/src/runtime/resolve-connection.ts b/packages/eve/src/runtime/resolve-connection.tsindex ed95ccb7e..423e50a32 100644--- a/packages/eve/src/runtime/resolve-connection.ts+++ b/packages/eve/src/runtime/resolve-connection.ts@@ -2,7 +2,10 @@ import type { CompiledConnectionDefinition } from "#compiler/manifest.js";import type { CompiledModuleMap } from "#compiler/module-map.js";import { expectObjectRecord } from "#internal/authored-module.js";import type { ConnectionToolCallDefinition } from "#public/definitions/connections/tool-call.js";-import { registerDefinitionSource, stampDefinitionKey } from "#public/tool-result-narrowing.js";+import {+ registerDefinitionSource,+ stampDefinitionKey,+} from "#internal/authored-definition/source-identity.js";import { toErrorMessage } from "#shared/errors.js";import type {ConnectionAuthResolver,diff --git a/packages/eve/src/runtime/resolve-dynamic-tool.ts b/packages/eve/src/runtime/resolve-dynamic-tool.tsindex cdc64e99f..cd817e656 100644--- a/packages/eve/src/runtime/resolve-dynamic-tool.ts+++ b/packages/eve/src/runtime/resolve-dynamic-tool.ts@@ -1,8 +1,11 @@import type { CompiledDynamicToolDefinition } from "#compiler/manifest.js";import type { CompiledModuleMap } from "#compiler/module-map.js";import { expectFunction, expectObjectRecord } from "#internal/authored-module.js";-import { registerDefinitionSource, stampDefinitionKey } from "#public/tool-result-narrowing.js";-import { isDynamicSentinel, type DynamicSentinel } from "#shared/dynamic-tool-definition.js";+import {+ registerDefinitionSource,+ stampDefinitionKey,+} from "#internal/authored-definition/source-identity.js";+import { isDynamicSentinel, type DynamicSentinel } from "#dynamic/definition.js";import { toErrorMessage } from "#shared/errors.js";import type { ModuleSourceRef } from "#shared/source-ref.js";import { loadResolvedModuleExport, ResolveAgentError } from "#runtime/resolve-helpers.js";diff --git a/packages/eve/src/runtime/resolve-tool.ts b/packages/eve/src/runtime/resolve-tool.tsindex f88774e5c..33f36c0d4 100644--- a/packages/eve/src/runtime/resolve-tool.ts+++ b/packages/eve/src/runtime/resolve-tool.ts@@ -2,8 +2,11 @@ import type { CompiledToolDefinition } from "#compiler/manifest.js";import type { CompiledModuleMap } from "#compiler/module-map.js";import { expectFunction, expectObjectRecord } from "#internal/authored-module.js";import { normalizeApproval } from "#internal/authored-definition/approval.js";-import { registerDefinitionSource, stampDefinitionKey } from "#public/tool-result-narrowing.js";-import { isToolSchema, toInputSchema, toOutputSchema } from "#shared/tool-schema.js";+import {+ registerDefinitionSource,+ stampDefinitionKey,+} from "#internal/authored-definition/source-identity.js";+import { isToolSchema, toInputSchema, toOutputSchema } from "#tools/schema.js";import { toErrorMessage } from "#shared/errors.js";import { loadResolvedModuleExport, ResolveAgentError } from "#runtime/resolve-helpers.js";import type { ResolvedToolDefinition } from "#runtime/types.js";diff --git a/packages/eve/src/runtime/sessions/turn.ts b/packages/eve/src/runtime/sessions/turn.tsindex f3644111c..31ef5d235 100644--- a/packages/eve/src/runtime/sessions/turn.ts+++ b/packages/eve/src/runtime/sessions/turn.ts@@ -1,6 +1,6 @@import type { Node } from "#shared/node.js";import type { SourceRef } from "#shared/source-ref.js";-import type { InternalToolDefinition } from "#shared/tool-definition.js";+import type { InternalToolDefinition } from "#tools/definition.js";import type { AgentSourceOwner } from "#compiler/source-graph.js";/**diff --git a/packages/eve/src/runtime/subagents/dynamic-agent-config.ts b/packages/eve/src/runtime/subagents/dynamic-agent-config.tsindex 768a5a532..c1229c2c3 100644--- a/packages/eve/src/runtime/subagents/dynamic-agent-config.ts+++ b/packages/eve/src/runtime/subagents/dynamic-agent-config.ts@@ -9,7 +9,7 @@ import {type AgentReasoningDefinition,} from "#shared/agent-definition.js";import type { JsonObject } from "#shared/json.js";-import { serializeOutputSchema } from "#shared/tool-schema.js";+import { serializeOutputSchema } from "#tools/schema.js";export interface DynamicSubagentAgentConfig {readonly compaction?: {diff --git a/packages/eve/src/runtime/subagents/dynamic-remote-agent-config.ts b/packages/eve/src/runtime/subagents/dynamic-remote-agent-config.tsindex a36243ac6..69312c1d8 100644--- a/packages/eve/src/runtime/subagents/dynamic-remote-agent-config.ts+++ b/packages/eve/src/runtime/subagents/dynamic-remote-agent-config.ts@@ -9,7 +9,7 @@ import {import type { OutboundAuthFn } from "#public/agents/auth.js";import { EVE_SESSION_ROUTE_PATH } from "#protocol/routes.js";import type { JsonObject } from "#shared/json.js";-import { serializeOutputSchema, type ToolSchemaSource } from "#shared/tool-schema.js";+import { serializeOutputSchema, type ToolSchemaSource } from "#tools/schema.js";export interface DynamicRemoteAgentConfig {readonly credentialsStepId?: string;diff --git a/packages/eve/src/runtime/subagents/registry.ts b/packages/eve/src/runtime/subagents/registry.tsindex 282c25476..8c9f22e83 100644--- a/packages/eve/src/runtime/subagents/registry.ts+++ b/packages/eve/src/runtime/subagents/registry.ts@@ -5,11 +5,11 @@ import type {ResolvedRuntimeDelegationNode,} from "#runtime/types.js";import type { JsonObject } from "#shared/json.js";-import { serializeInputSchema } from "#shared/tool-schema.js";+import { serializeInputSchema } from "#tools/schema.js";import {PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA,SUBAGENT_TOOL_INPUT_SCHEMA,-} from "#shared/agent-tool.js";+} from "#tools/framework/agent-contract.js";/*** One runtime-owned subagent tracked by the prepared registry.diff --git a/packages/eve/src/runtime/tools/registry.ts b/packages/eve/src/runtime/tools/registry.tsindex 2f038661c..19c845b06 100644--- a/packages/eve/src/runtime/tools/registry.ts+++ b/packages/eve/src/runtime/tools/registry.ts@@ -1,7 +1,7 @@import { RuntimeRegistry } from "#internal/runtime-registry.js";import type { PreparedRuntimeAuthoredTool } from "#runtime/sessions/turn.js";import type { ResolvedToolDefinition } from "#runtime/types.js";-import { serializeInputSchema, serializeOutputSchema } from "#shared/tool-schema.js";+import { serializeInputSchema, serializeOutputSchema } from "#tools/schema.js";/*** One executable authored tool tracked by the runtime-owned registry.diff --git a/packages/eve/src/runtime/types.ts b/packages/eve/src/runtime/types.tsindex 1c9ce0d0b..39bcd52b6 100644--- a/packages/eve/src/runtime/types.ts+++ b/packages/eve/src/runtime/types.ts@@ -8,8 +8,8 @@ import type { ChannelRouteMethod, RouteContext } from "#public/definitions/channimport 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 { Approval } from "#public/definitions/approval.js";-import type { ToolModelOutput } from "#public/definitions/tool.js";+import type { Approval } from "#approval/definition.js";+import type { ToolModelOutput } from "#tools/definition.js";import type { ConnectionToolCallDefinition } from "#public/definitions/connections/tool-call.js";import type {AuthorizationDefinition,@@ -33,11 +33,11 @@ import type {import type { NamedSkillDefinition } from "#shared/skill-definition.js";import type { InternalAgentDefinition } from "#shared/agent-definition.js";import type { RuntimeDynamicModelReference } from "#runtime/agent/bootstrap.js";-import type { InternalToolDefinitionWithExecuteFn } from "#shared/tool-definition.js";+import type { InternalToolDefinitionWithExecuteFn } from "#tools/definition.js";import type { WebSearchProvider } from "#shared/web-search.js";import type { SandboxBackend } from "#shared/sandbox-backend.js";import type { SandboxBootstrapContext, SandboxSessionContext } from "#shared/sandbox-definition.js";-import type { ToolSchema } from "#shared/tool-schema.js";+import type { ToolSchema } from "#tools/schema.js";import type { AgentSourceOwner } from "#compiler/source-graph.js";/**diff --git a/packages/eve/src/shared/agent-definition.ts b/packages/eve/src/shared/agent-definition.tsindex aa9d3fb69..dbeb68760 100644--- a/packages/eve/src/shared/agent-definition.ts+++ b/packages/eve/src/shared/agent-definition.ts@@ -6,7 +6,7 @@ import {isDynamicSentinel,type DynamicResolveContext,type DynamicSentinel,-} from "#shared/dynamic-tool-definition.js";+} from "#dynamic/definition.js";/*** Optional overrides that eve forwards to the AI SDK model runtime call fordiff --git a/packages/eve/src/shared/connection-types.ts b/packages/eve/src/shared/connection-types.tsindex 7c0b55447..061955e3e 100644--- a/packages/eve/src/shared/connection-types.ts+++ b/packages/eve/src/shared/connection-types.ts@@ -8,9 +8,9 @@import type { ToolSet } from "ai";-import type { ConnectionAuthorizationChallenge } from "#public/connections/errors.js";-import type { SessionContext } from "#public/definitions/callback-context.js";-import type { JsonValue } from "#public/types/json.js";+import type { ConnectionAuthorizationChallenge } from "#connections/errors.js";+import type { SessionContext } from "#context/session-context.js";+import type { JsonValue } from "#shared/json.js";/*** Credential returned by a connection's `getToken` ordiff --git a/packages/eve/src/shared/dynamic-tool-definition.ts b/packages/eve/src/shared/dynamic-tool-definition.tsdeleted file mode 100644index 0fdf64eb2..000000000--- a/packages/eve/src/shared/dynamic-tool-definition.ts+++ /dev/null@@ -1,231 +0,0 @@-import type { ModelMessage } from "ai";--import type {- PublicToolInputSchema,- PublicToolOutputSchema,- ToolModelOutput,-} from "#shared/tool-definition.js";-import type { Approval } from "#public/definitions/approval.js";-import type { ToolContext } from "#public/definitions/tool.js";-import type { SessionAuth } from "#context/keys.js";-import type { UnstampedMessageStreamEvent } from "#protocol/message.js";--/**- * Stream event types allowed for dynamic tool resolvers. Dispatch- * supports any event; this extract restricts the public surface until- * more events are validated.- */-export type DynamicToolEventName = Extract<- UnstampedMessageStreamEvent["type"],- "session.started" | "turn.started" | "step.started"->;--export const ALLOWED_DYNAMIC_TOOL_EVENTS: ReadonlySet<string> = new Set<DynamicToolEventName>([- "session.started",- "turn.started",- "step.started",-]);--/**- * Instructions and skills are restricted to session/turn boundaries.- * Keeping their resolved context stable within a turn avoids changing the- * model input between tool-loop steps.- */-export const ALLOWED_DYNAMIC_INSTRUCTION_EVENTS: ReadonlySet<string> =- new Set<DynamicToolEventName>(["session.started", "turn.started"]);--export const ALLOWED_DYNAMIC_SKILL_EVENTS: ReadonlySet<string> = new Set<DynamicToolEventName>([- "session.started",- "turn.started",-]);--/**- * Context passed to a dynamic resolver's event handler.- *- * Exposes read-only session identity, auth, and channel metadata. State- * is not exposed here; resolvers read it through `defineState` handles or- * the session context inside tool `execute` functions.- */-export interface DynamicResolveContext {- readonly session: {- readonly id: string;- readonly auth: SessionAuth;- };- /** Channel metadata for the request that triggered this resolve. */- readonly channel: {- /** Channel type that produced the request (e.g. `"slack"`, `"http"`), when known. */- readonly kind?: string;- /** Channel-owned resume handle for the conversation, when the channel supplies one. */- readonly continuationToken?: string;- /** Free-form channel-specific metadata attached to the request. */- readonly metadata?: Readonly<Record<string, unknown>>;- };- /** Conversation history visible at this resolve point, oldest first. */- readonly messages: readonly ModelMessage[];-}--/**- * A single tool entry within a resolved dynamic tool set.- *- * Identity comes from context: a single returned entry is named after- * the file slug; entries in a returned `Record<string, DynamicToolEntry>`- * are each named `slug__key`.- *- * `TInput` defaults to `Record<string, unknown>` but is inferred when- * `inputSchema` is a Standard Schema (e.g. Zod) via the `defineTool`- * wrapper. `TOutput` defaults to `any`; provide an `outputSchema`- * (Standard Schema) to infer and check the executor return type.- */-// eslint-disable-next-line @typescript-eslint/no-explicit-any-export interface DynamicToolEntry<TInput = Record<string, unknown>, TOutput = any> {- readonly description: string;- readonly inputSchema: PublicToolInputSchema<TInput>;- readonly outputSchema?: PublicToolOutputSchema<TOutput>;- execute(input: TInput, ctx: ToolContext): TOutput | Promise<TOutput>;- readonly toModelOutput?: (output: TOutput) => ToolModelOutput | Promise<ToolModelOutput>;- /**- * Optional per-call approval gate, mirroring the authored-tool- * `approval` contract: return `"user-approval"` to require user approval- * before the call executes. Dynamic approval request and response callbacks- * use the same durable descriptor boundary as `execute` and `toModelOutput`.- */- readonly approval?: Approval;-}--/**- * A resolved tool set: keys are entry identifiers, values are- * {@link DynamicToolEntry} objects created via `defineTool` inside a- * resolver. Entry type params are `any` so entries with differing- * schemas stay assignable to one Record; `defineTool` captures each- * entry's concrete types before this widened container.- */-// eslint-disable-next-line @typescript-eslint/no-explicit-any-export type DynamicToolSet = Readonly<Record<string, DynamicToolEntry<any, any>>>;--/**- * Return type for a `defineDynamic` event handler: a single tool entry- * (named after the file slug), a map of entries (named `slug__key`), or- * `null` for no tools.- */-// eslint-disable-next-line @typescript-eslint/no-explicit-any-export type DynamicToolResult = DynamicToolEntry<any, any> | DynamicToolSet | null;--/**- * Strongly-typed tool-handler map: each key is a supported event name,- * each value a resolver that takes the stream event and resolve context- * and returns a {@link DynamicToolResult}. `defineDynamic` accepts the- * wider {@link DynamicEvents} (handlers return `unknown`) because the- * slot directory (tools/ vs skills/) decides the expected return at- * runtime. Reference `DynamicToolEvents` to check the tool-specific- * return type at authoring time.- */-export type DynamicToolEvents = {- readonly [K in DynamicToolEventName]?: (- event: unknown,- ctx: DynamicResolveContext,- ) => DynamicToolResult | Promise<DynamicToolResult>;-};--/**- * Base event handler map accepted by `defineDynamic`. Intentionally- * wide so it accepts both tool-returning and skill-returning handlers:- * the slot directory (tools/ vs skills/) determines the required return,- * validated at runtime by the respective resolver.- */-export type DynamicEvents<TResult = unknown> = {- readonly [K in DynamicToolEventName]?: (- event: unknown,- ctx: DynamicResolveContext,- ) => TResult | Promise<TResult>;-};--/**- * Marker discriminator for a `defineDynamic({ events })` export.- */-export const DYNAMIC_SENTINEL_KIND = "eve:dynamic" as const;--/**- * Return value of `defineDynamic`: the runtime shape of a dynamic export,- * stamped with a sentinel kind the compiler/normalizer detects.- */-export type DynamicSentinel<TResult = unknown> = {- readonly kind: typeof DYNAMIC_SENTINEL_KIND;- readonly events: DynamicEvents<TResult>;-};--export function assertResolverOnlyDynamicSentinel(- sentinel: DynamicSentinel,- message: string,-): void {- const unknownKeys = Object.keys(sentinel).filter((key) => key !== "events" && key !== "kind");- if (unknownKeys.length > 0) {- throw new Error(`${message} Unknown key(s): ${unknownKeys.join(", ")}.`);- }-}--export function isDynamicSentinel(value: unknown): value is DynamicSentinel {- return (- typeof value === "object" &&- value !== null &&- (value as { kind?: unknown }).kind === DYNAMIC_SENTINEL_KIND- );-}--/**- * Symbol-based brand stamped by `defineTool` on every entry. Invisible- * in IntelliSense, checked at runtime to enforce the wrapper and to- * distinguish a single entry from a map of entries.- */-export const TOOL_BRAND = Symbol.for("eve:tool-brand");--/**- * Returns true if `value` carries the `defineTool` brand symbol. Used- * to detect single entry vs map of entries and to validate that entries- * are properly wrapped.- */-export function isBrandedToolEntry(value: unknown): boolean {- return (- typeof value === "object" &&- value !== null &&- (value as Record<symbol, unknown>)[TOOL_BRAND] === true- );-}--/**- * Symbol-based brand stamped by `defineInstructions` on every entry.- * Invisible in IntelliSense, checked at runtime to validate that dynamic- * instruction resolver returns are properly wrapped.- */-export const INSTRUCTIONS_BRAND = Symbol.for("eve:instructions-brand");--/**- * Returns true if `value` carries the `defineInstructions` brand symbol.- * Used to validate that dynamic instruction entries are properly wrapped.- */-export function isBrandedInstructionsEntry(value: unknown): boolean {- return (- typeof value === "object" &&- value !== null &&- (value as Record<symbol, unknown>)[INSTRUCTIONS_BRAND] === true- );-}--/**- * Symbol-based brand stamped by `defineSkill` on every entry. Invisible- * in IntelliSense, checked at runtime to detect single-entry vs- * map-of-entries return shapes in dynamic skill resolvers.- */-export const SKILL_BRAND = Symbol.for("eve:skill-brand");--/**- * Returns true if `value` carries the `defineSkill` brand symbol. Used- * to detect single entry vs map of entries and to validate that entries- * are properly wrapped.- */-export function isBrandedSkillEntry(value: unknown): boolean {- return (- typeof value === "object" &&- value !== null &&- (value as Record<symbol, unknown>)[SKILL_BRAND] === true- );-}diff --git a/packages/eve/src/shared/instructions-definition.ts b/packages/eve/src/shared/instructions-definition.tsindex 054721ec9..f829c9465 100644--- a/packages/eve/src/shared/instructions-definition.ts+++ b/packages/eve/src/shared/instructions-definition.ts@@ -32,3 +32,13 @@ export interface InternalInstructionsDefinition {readonly name: string;readonly role: InstructionsRole;}++export const INSTRUCTIONS_BRAND = Symbol.for("eve:instructions-brand");++export function isBrandedInstructionsEntry(value: unknown): boolean {+ return (+ typeof value === "object" &&+ value !== null &&+ (value as Record<symbol, unknown>)[INSTRUCTIONS_BRAND] === true+ );+}diff --git a/packages/eve/src/shared/sandbox-definition.ts b/packages/eve/src/shared/sandbox-definition.tsindex 81eb45651..e431db009 100644--- a/packages/eve/src/shared/sandbox-definition.ts+++ b/packages/eve/src/shared/sandbox-definition.ts@@ -1,6 +1,6 @@import type { SandboxSession } from "#shared/sandbox-session.js";import type { SandboxBackend } from "#shared/sandbox-backend.js";-import type { SessionContext } from "#public/definitions/callback-context.js";+import type { SessionContext } from "#context/session-context.js";/*** Opens the template session inside a `bootstrap` hook. Optional `options`diff --git a/packages/eve/src/shared/skill-definition.ts b/packages/eve/src/shared/skill-definition.tsindex 7c8c19bad..09ae9cec6 100644--- a/packages/eve/src/shared/skill-definition.ts+++ b/packages/eve/src/shared/skill-definition.ts@@ -24,3 +24,13 @@ export interface SkillPackageDefinition {export interface NamedSkillDefinition extends SkillPackageDefinition {readonly name: string;}++export const SKILL_BRAND = Symbol.for("eve:skill-brand");++export function isBrandedSkillEntry(value: unknown): boolean {+ return (+ typeof value === "object" &&+ value !== null &&+ (value as Record<symbol, unknown>)[SKILL_BRAND] === true+ );+}diff --git a/packages/eve/src/shared/tool-definition.ts b/packages/eve/src/shared/tool-definition.tsdeleted file mode 100644index caf78e02e..000000000--- a/packages/eve/src/shared/tool-definition.ts+++ /dev/null@@ -1,111 +0,0 @@-import type { ToolExecutionOptions } from "ai";-import type {- StandardJSONSchemaV1,- StandardSchemaV1,-} from "#compiled/@standard-schema/spec/index.js";-import type { JsonObject } from "#shared/json.js";-import type { TaskExec } from "#shared/tool-task.js";--/**- * Options forwarded from the AI SDK to the tool's {@link ToolDefinition.execute}- * function. These are the same options the SDK passes to every tool call.- */-export type ToolExecuteOptions = Omit<ToolExecutionOptions<unknown>, "context">;--export type ToolExecuteFn<TInput = unknown, TOutput = unknown> = (- input: TInput,- options: ToolExecuteOptions,- task?: TaskExec,-) => Promise<TOutput> | TOutput | AsyncIterable<TOutput>;--export type ToolExecution = "background";--interface ToolDefinitionBase {- readonly description: string;- readonly execution?: ToolExecution;-}--/**- * Internal/compiled tool definition shape. Carries `name` because the- * compiler stamps a path-derived identifier onto every tool entry.- *- * Authored public definitions (see {@link PublicToolDefinition}) do not- * carry `name`; identity comes from the file path.- */-export interface InternalToolDefinition extends ToolDefinitionBase {- name: string;- inputSchema: JsonObject | null;- outputSchema?: JsonObject;-}--export type PublicToolInputSchema<TInput = unknown> =- | StandardSchemaV1<unknown, TInput>- | StandardJSONSchemaV1<unknown, TInput>- | JsonObject;--export type PublicToolOutputSchema<TOutput = unknown> =- | StandardJSONSchemaV1<unknown, TOutput>- | JsonObject;--/**- * Authored public tool definition shape. Identity is derived from the- * file path at compile time, so `name` is intentionally absent here.- */-export interface PublicToolDefinition<- TInput = unknown,- TOutput = unknown,-> extends ToolDefinitionBase {- inputSchema: PublicToolInputSchema<TInput>;- /**- * Optional schema describing the value returned by the tool executor.- * The AI SDK can use this for tool result typing.- */- outputSchema?: PublicToolOutputSchema<TOutput>;-}--export interface InternalToolDefinitionWithExecuteFn<- TInput = unknown,- TOutput = unknown,-> extends InternalToolDefinition {- execute: ToolExecuteFn<TInput, TOutput>;-}--export interface PublicToolDefinitionWithExecuteFn<- TInput = unknown,- TOutput = unknown,-> extends PublicToolDefinition<TInput, TOutput> {- execute: ToolExecuteFn<TInput, TOutput>;-}--/**- * eve-owned shape for the model-facing tool result produced by- * `toModelOutput`. Structurally compatible with the AI SDK's- * `ToolResultOutput` so the harness can forward it without conversion.- *- * The `content` variant carries an ordered list of- * {@link ToolModelOutputPart} entries, letting a tool hand the model- * text alongside inline files (e.g. a screenshot as vision input).- */-export type ToolModelOutput =- | { readonly type: "text"; readonly value: string }- | { readonly type: "json"; readonly value: unknown }- | { readonly type: "content"; readonly value: readonly ToolModelOutputPart[] };--/**- * One part of a `content` {@link ToolModelOutput}. Mirrors the AI SDK's- * `ToolResultOutput` content parts narrowed to the JSON-safe subset:- * file data is the SDK's tagged `FileData` union restricted to- * `{ type: "data" }` with a base64 string, so persisted tool results- * survive the durable JSON boundary. Use the `toolOutputPart` builders- * from `eve/tools` to construct parts without hand-writing the nesting.- */-export type ToolModelOutputPart =- | { readonly type: "text"; readonly text: string }- | {- readonly type: "file";- /** Tagged file data; only JSON-safe base64 payloads are accepted. */- readonly data: { readonly type: "data"; readonly data: string };- /** IANA media type, e.g. `image/png`. */- readonly mediaType: string;- readonly filename?: string;- };diff --git a/packages/eve/src/tasks/json.test.ts b/packages/eve/src/tasks/json.test.tsindex 0f3cd8735..801b4b845 100644--- a/packages/eve/src/tasks/json.test.ts+++ b/packages/eve/src/tasks/json.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from "vitest";-import { taskCancel } from "#public/tools/task-cancel.js";-import { TASK_VIEWS_OUTPUT_SCHEMA } from "#shared/task-tool.js";+import { taskCancel } from "#tools/framework/task-cancel.js";+import { TASK_VIEWS_OUTPUT_SCHEMA } from "#tools/framework/task-contract.js";import { taskViewToJson } from "#tasks/json.js";import type { TaskView } from "#tasks/types.js";diff --git a/packages/eve/src/tasks/json.ts b/packages/eve/src/tasks/json.tsindex 2f780420a..a90aeb86c 100644--- a/packages/eve/src/tasks/json.ts+++ b/packages/eve/src/tasks/json.ts@@ -1,7 +1,7 @@import type { z } from "#compiled/zod/index.js";import type { JsonValue } from "#shared/json.js";-import { TASK_VIEW_JSON_SCHEMA } from "#shared/task-tool.js";+import { TASK_VIEW_JSON_SCHEMA } from "#tools/framework/task-contract.js";import type { TaskView } from "#tasks/types.js";import { readSubagentTaskMetadata } from "#tasks/types.js";diff --git a/packages/eve/src/tasks/session-index.ts b/packages/eve/src/tasks/session-index.tsindex 0ab645dd4..206f0a979 100644--- a/packages/eve/src/tasks/session-index.ts+++ b/packages/eve/src/tasks/session-index.ts@@ -2,7 +2,7 @@ import { z } from "#compiled/zod/index.js";import type { HarnessSession, SessionStateMap } from "#harness/types.js";import type { JsonValue } from "#shared/json.js";-import type { TaskExecutorBinding } from "#shared/tool-task.js";+import type { TaskExecutorBinding } from "#tools/task.js";import { sameTaskMetadata, type DurableTaskMetadata, type TaskView } from "#tasks/types.js";/**diff --git a/packages/eve/src/tasks/types.ts b/packages/eve/src/tasks/types.tsindex ab9f2004d..f1573824c 100644--- a/packages/eve/src/tasks/types.ts+++ b/packages/eve/src/tasks/types.ts@@ -1,6 +1,6 @@import type { AgentAddress, AgentIdentity } from "#harness/handles/store.js";import { isJsonObjectValue, type JsonValue } from "#shared/json.js";-import type { TaskExecutorBinding } from "#shared/tool-task.js";+import type { TaskExecutorBinding } from "#tools/task.js";import type { SubagentAuthorizationEvent } from "#channel/types.js";/**diff --git a/packages/eve/src/public/tools/approval/approval-helpers.test.ts b/packages/eve/src/tools/approval/policies.test.tssimilarity index 85%rename from packages/eve/src/public/tools/approval/approval-helpers.test.tsrename to packages/eve/src/tools/approval/policies.test.tsindex b6c637f78..a2356cec1 100644--- a/packages/eve/src/public/tools/approval/approval-helpers.test.ts+++ b/packages/eve/src/tools/approval/policies.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from "vitest";-import { always, never, once } from "#public/tools/approval/approval-helpers.js";-import { readDurableDynamicCallback } from "#shared/durable-dynamic-tool-callbacks.js";+import { always, never, once } from "#tools/approval/policies.js";+import { readDurableDynamicCallback } from "#tools/durable-callbacks.js";describe("dynamic tool approval helpers", () => {it.each([diff --git a/packages/eve/src/public/tools/approval/approval-helpers.ts b/packages/eve/src/tools/approval/policies.tssimilarity index 90%rename from packages/eve/src/public/tools/approval/approval-helpers.tsrename to packages/eve/src/tools/approval/policies.tsindex 0c8de338c..7ef1abe06 100644--- a/packages/eve/src/public/tools/approval/approval-helpers.ts+++ b/packages/eve/src/tools/approval/policies.ts@@ -1,6 +1,6 @@-import type { ApprovalContext, ApprovalPolicy } from "#public/definitions/approval.js";+import type { ApprovalContext, ApprovalPolicy } from "#approval/definition.js";import type { JsonObject } from "#shared/json.js";-import { stampDurableDynamicCallback } from "#shared/durable-dynamic-tool-callbacks.js";+import { stampDurableDynamicCallback } from "#tools/durable-callbacks.js";function alwaysApproval(_closure: JsonObject): "user-approval" {return "user-approval";diff --git a/packages/eve/src/tools/auth.ts b/packages/eve/src/tools/auth.tsnew file mode 100644index 000000000..76947a8fc--- /dev/null+++ b/packages/eve/src/tools/auth.ts@@ -0,0 +1,44 @@+import type {+ AuthorizationDefinition,+ ConnectionAuthorizationContext,+ NonInteractiveAuthorizationDefinition,+} from "#shared/connection-types.js";++/**+ * Authorization provider passed to the tool context's `getToken` or+ * `requireAuth` method. Accepts the same shapes as a connection's `auth`:+ * - a `getToken`-only object (static API keys, pre-provisioned JWTs);+ * `principalType` may be omitted and defaults to `"app"`.+ * - a full interactive OAuth definition (e.g. `connect("okta/myagent")` from+ * `@vercel/connect/eve`, or `defineInteractiveAuthorization`).+ */+export type ToolAuthDefinition =+ | (Omit<NonInteractiveAuthorizationDefinition, "principalType"> & {+ readonly principalType?: NonInteractiveAuthorizationDefinition["principalType"];+ })+ | AuthorizationDefinition;++export type ToolAuthProvider = ToolAuthDefinition;++/** Controls eve runtime behavior for an inline tool auth provider. */+export interface ToolAuthOptions {+ /**+ * Connection metadata passed through to provider callbacks. Tool-only+ * providers usually leave this unset; connection-backed helpers can use it+ * to receive the upstream server URL.+ */+ readonly connection?: ConnectionAuthorizationContext;+ /**+ * Optional human-readable provider name shown in sign-in UI. Presentation+ * only; it does not affect OAuth scopes, token cache keys, or callback URLs.+ */+ readonly displayName?: string;+ /**+ * Optional eve auth-flow key for token caches, callback URLs, pending+ * authorization state, and authorization completion. This is not an OAuth+ * scope. For Vercel Connect OAuth targeting such as `scopes`, `resources`,+ * or `authorizationDetails`, configure the provider with+ * `connect({ connector, tokenParams })`.+ */+ readonly authKey?: string;+}diff --git a/packages/eve/src/tools/define-bash-tool.ts b/packages/eve/src/tools/define-bash-tool.tsdeleted file mode 100644index 71c23a3f5..000000000--- a/packages/eve/src/tools/define-bash-tool.ts+++ /dev/null@@ -1,34 +0,0 @@-import { type BashInput, executeBashOnSandbox } from "#execution/sandbox/bash-tool.js";-import { BASH_INPUT_SCHEMA, BASH_OUTPUT_SCHEMA } from "#tools/bash.js";-import type { ToolDefinition } from "#public/definitions/tool.js";--/**- * Input shape accepted by {@link defineBashTool}.- */-export interface DefineBashToolInput {- /**- * Optional model-facing description. Defaults to a generic- * "Execute a shell command in the workspace sandbox." line.- */- readonly description?: string;-}--/**- * Defines a model-visible shell-runner tool that executes commands- * inside the agent's sandbox. Uses the same executor core as the- * framework `bash` tool, so input schema, error messages, and result- * shape are identical.- *- * The tool's runtime name comes from the authored file's slug (for- * example `agent/tools/run_shell.ts` becomes a tool named `run_shell`).- */-export function defineBashTool(input: DefineBashToolInput = {}): ToolDefinition {- return {- description: input.description ?? "Execute a shell command in the workspace sandbox.",- async execute(args, ctx) {- return executeBashOnSandbox(await ctx.getSandbox(), args as BashInput);- },- inputSchema: BASH_INPUT_SCHEMA,- outputSchema: BASH_OUTPUT_SCHEMA,- };-}diff --git a/packages/eve/src/tools/define-glob-tool.ts b/packages/eve/src/tools/define-glob-tool.tsdeleted file mode 100644index 6c4ba8fc2..000000000--- a/packages/eve/src/tools/define-glob-tool.ts+++ /dev/null@@ -1,35 +0,0 @@-import { executeGlobOnSandbox, type GlobInput } from "#execution/sandbox/glob-tool.js";-import { GLOB_INPUT_SCHEMA, GLOB_OUTPUT_SCHEMA } from "#tools/glob.js";-import type { ToolDefinition } from "#public/definitions/tool.js";--/**- * Input shape accepted by {@link defineGlobTool}.- */-export interface DefineGlobToolInput {- /**- * Optional model-facing description. Defaults to a generic- * "Search for files by glob pattern in the workspace sandbox." line.- */- readonly description?: string;-}--/**- * Defines a model-visible file-search tool that discovers files by- * glob pattern inside the agent's sandbox. Uses the same executor core- * as the framework `glob` tool, so input schema, error messages, and- * result shape are identical.- *- * The tool's runtime name comes from the authored file's slug (for- * example `agent/tools/find_files.ts` becomes a tool named- * `find_files`).- */-export function defineGlobTool(input: DefineGlobToolInput = {}): ToolDefinition {- return {- description: input.description ?? "Search for files by glob pattern in the workspace sandbox.",- async execute(args, ctx) {- return executeGlobOnSandbox(await ctx.getSandbox(), args as GlobInput);- },- inputSchema: GLOB_INPUT_SCHEMA,- outputSchema: GLOB_OUTPUT_SCHEMA,- };-}diff --git a/packages/eve/src/tools/define-grep-tool.ts b/packages/eve/src/tools/define-grep-tool.tsdeleted file mode 100644index 0edf0a015..000000000--- a/packages/eve/src/tools/define-grep-tool.ts+++ /dev/null@@ -1,35 +0,0 @@-import { executeGrepOnSandbox, type GrepInput } from "#execution/sandbox/grep-tool.js";-import { GREP_INPUT_SCHEMA, GREP_OUTPUT_SCHEMA } from "#tools/grep.js";-import type { ToolDefinition } from "#public/definitions/tool.js";--/**- * Input shape accepted by {@link defineGrepTool}.- */-export interface DefineGrepToolInput {- /**- * Optional model-facing description. Defaults to a generic- * "Search file contents by pattern in the workspace sandbox." line.- */- readonly description?: string;-}--/**- * Defines a model-visible content-search tool that searches file- * contents by pattern inside the agent's sandbox. Uses the same- * executor core as the framework `grep` tool, so input schema, error- * messages, and result shape are identical.- *- * The tool's runtime name comes from the authored file's slug (for- * example `agent/tools/search_code.ts` becomes a tool named- * `search_code`).- */-export function defineGrepTool(input: DefineGrepToolInput = {}): ToolDefinition {- return {- description: input.description ?? "Search file contents by pattern in the workspace sandbox.",- async execute(args, ctx) {- return executeGrepOnSandbox(await ctx.getSandbox(), args as GrepInput);- },- inputSchema: GREP_INPUT_SCHEMA,- outputSchema: GREP_OUTPUT_SCHEMA,- };-}diff --git a/packages/eve/src/tools/define-read-file-tool.ts b/packages/eve/src/tools/define-read-file-tool.tsdeleted file mode 100644index 6646d6181..000000000--- a/packages/eve/src/tools/define-read-file-tool.ts+++ /dev/null@@ -1,34 +0,0 @@-import { executeReadFileOnSandbox, type ReadFileInput } from "#execution/sandbox/read-file-tool.js";-import { READ_FILE_INPUT_SCHEMA, READ_FILE_OUTPUT_SCHEMA } from "#tools/read-file.js";-import type { ToolDefinition } from "#public/definitions/tool.js";--/**- * Input shape accepted by {@link defineReadFileTool}.- */-export interface DefineReadFileToolInput {- /**- * Optional model-facing description. Defaults to a generic- * "Read a file from the workspace sandbox." line.- */- readonly description?: string;-}--/**- * Defines a model-visible file-reader tool that reads files from the- * agent's sandbox. Uses the same executor core as the framework- * `read_file` tool, so input schema, error messages, and result shape- * are identical.- *- * The tool's runtime name comes from the authored file's slug (for- * example `agent/tools/read_file.ts` becomes a tool named `read_file`).- */-export function defineReadFileTool(input: DefineReadFileToolInput = {}): ToolDefinition {- return {- description: input.description ?? "Read a file from the workspace sandbox.",- async execute(args, ctx) {- return executeReadFileOnSandbox(await ctx.getSandbox(), args as ReadFileInput);- },- inputSchema: READ_FILE_INPUT_SCHEMA,- outputSchema: READ_FILE_OUTPUT_SCHEMA,- };-}diff --git a/packages/eve/src/tools/define-write-file-tool.ts b/packages/eve/src/tools/define-write-file-tool.tsdeleted file mode 100644index b7d3567fb..000000000--- a/packages/eve/src/tools/define-write-file-tool.ts+++ /dev/null@@ -1,38 +0,0 @@-import {- executeWriteFileOnSandbox,- type WriteFileInput,-} from "#execution/sandbox/write-file-tool.js";-import { WRITE_FILE_INPUT_SCHEMA, WRITE_FILE_OUTPUT_SCHEMA } from "#tools/write-file.js";-import type { ToolDefinition } from "#public/definitions/tool.js";--/**- * Input shape accepted by {@link defineWriteFileTool}.- */-export interface DefineWriteFileToolInput {- /**- * Optional model-facing description. Defaults to a generic- * "Write a file to the workspace sandbox." line.- */- readonly description?: string;-}--/**- * Defines a model-visible file-writer tool that writes files to the- * agent's sandbox. Uses the same executor core as the framework- * `write_file` tool, so input schema, error messages, and result shape- * are identical.- *- * The tool's runtime name comes from the authored file's slug (for- * example `agent/tools/write_file.ts` becomes a tool named- * `write_file`).- */-export function defineWriteFileTool(input: DefineWriteFileToolInput = {}): ToolDefinition {- return {- description: input.description ?? "Write a file to the workspace sandbox.",- async execute(args, ctx) {- return executeWriteFileOnSandbox(await ctx.getSandbox(), args as WriteFileInput);- },- inputSchema: WRITE_FILE_INPUT_SCHEMA,- outputSchema: WRITE_FILE_OUTPUT_SCHEMA,- };-}diff --git a/packages/eve/src/public/definitions/tool-auth.test.ts b/packages/eve/src/tools/definition-auth.test.tssimilarity index 89%rename from packages/eve/src/public/definitions/tool-auth.test.tsrename to packages/eve/src/tools/definition-auth.test.tsindex d1072ad07..a04360a87 100644--- a/packages/eve/src/public/definitions/tool-auth.test.ts+++ b/packages/eve/src/tools/definition-auth.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { defineTool } from "#public/definitions/tool.js";+import { defineTool } from "#tools/definition.js";describe("defineTool auth field", () => {it("rejects top-level auth at runtime", () => {diff --git a/packages/eve/src/public/definitions/tool.ts b/packages/eve/src/tools/definition.tssimilarity index 59%rename from packages/eve/src/public/definitions/tool.tsrename to packages/eve/src/tools/definition.tsindex 5c4a1bcd2..06574309a 100644--- a/packages/eve/src/public/definitions/tool.ts+++ b/packages/eve/src/tools/definition.ts@@ -1,41 +1,27 @@+import type { ToolExecutionOptions } from "ai";import type {StandardJSONSchemaV1,StandardSchemaV1,} from "#compiled/@standard-schema/spec/index.js";-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 { Approval } from "#approval/definition.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";-import type { TaskDelegated, TaskExec, TaskReceipt } from "#shared/tool-task.js";-import type {- AuthorizationDefinition,- ConnectionAuthorizationContext,- NonInteractiveAuthorizationDefinition,- TokenResult,-} from "#shared/connection-types.js";-import {- DYNAMIC_SENTINEL_KIND,- TOOL_BRAND,- type DynamicEvents,- type DynamicSentinel,-} from "#shared/dynamic-tool-definition.js";+import type { TokenResult } from "#shared/connection-types.js";+import type { ToolAuthOptions, ToolAuthProvider } from "#tools/auth.js";import {collectDurableDynamicToolCallbacks,stampDurableDynamicToolCallbacks,-} from "#shared/durable-dynamic-tool-callbacks.js";+} from "#tools/durable-callbacks.js";+import { TOOL_BRAND } from "#tools/dynamic.js";+import type { ToolModelOutput } from "#tools/model-output.js";+import type { TaskDelegated, TaskExec, TaskReceipt } from "#tools/task.js";type ApprovalContextInput<TInput> = unknown extends TInput ? Record<string, unknown> : TInput;-type DynamicEventMapHandler<TEvents extends DynamicEvents> = Extract<- NonNullable<TEvents[keyof TEvents]>,- (...args: never[]) => unknown->;-type DynamicEventMapResult<TEvents extends DynamicEvents> = Awaited<- ReturnType<DynamicEventMapHandler<TEvents>>->;-export type { ToolModelOutput, ToolModelOutputPart } from "#shared/tool-definition.js";+export type { ToolAuthDefinition, ToolAuthOptions, ToolAuthProvider } from "#tools/auth.js";+export type { ToolModelOutput, ToolModelOutputPart } from "#tools/model-output.js";export type {TaskBinding,TaskDelegated,@@ -43,48 +29,73 @@ export type {TaskExecutorBinding,TaskReceipt,TaskSendCommand,-} from "#shared/tool-task.js";+} from "#tools/task.js";++export type ToolExecuteOptions = Omit<ToolExecutionOptions<unknown>, "context">;++export type ToolExecuteFn<TInput = unknown, TOutput = unknown> = (+ input: TInput,+ options: ToolExecuteOptions,+ task?: TaskExec,+) => Promise<TOutput> | TOutput | AsyncIterable<TOutput>;++export type ToolExecution = "background";++interface ToolDefinitionBase {+ readonly description: string;+ readonly execution?: ToolExecution;+}/**- * Authorization provider passed to {@link ToolContext.getToken} or- * {@link ToolContext.requireAuth}. Accepts the same shapes as a connection's- * `auth`:- * - a `getToken`-only object (static API keys, pre-provisioned JWTs);- * `principalType` may be omitted and defaults to `"app"`.- * - a full interactive OAuth definition (e.g. `connect("okta/myagent")` from- * `@vercel/connect/eve`, or {@link defineInteractiveAuthorization}).+ * Internal/compiled tool definition shape. Carries `name` because the+ * compiler stamps a path-derived identifier onto every tool entry.+ *+ * Authored public definitions (see {@link PublicToolDefinition}) do not+ * carry `name`; identity comes from the file path.*/-export type ToolAuthDefinition =- | (Omit<NonInteractiveAuthorizationDefinition, "principalType"> & {- readonly principalType?: NonInteractiveAuthorizationDefinition["principalType"];- })- | AuthorizationDefinition;+export interface InternalToolDefinition extends ToolDefinitionBase {+ name: string;+ inputSchema: JsonObject | null;+ outputSchema?: JsonObject;+}-export type ToolAuthProvider = ToolAuthDefinition;+export type PublicToolInputSchema<TInput = unknown> =+ | StandardSchemaV1<unknown, TInput>+ | StandardJSONSchemaV1<unknown, TInput>+ | JsonObject;++export type PublicToolOutputSchema<TOutput = unknown> =+ | StandardJSONSchemaV1<unknown, TOutput>+ | JsonObject;/**- * Controls Eve runtime behavior for an inline tool auth provider.+ * Authored public tool definition shape. Identity is derived from the+ * file path at compile time, so `name` is intentionally absent here.*/-export interface ToolAuthOptions {- /**- * Connection metadata passed through to provider callbacks. Tool-only- * providers usually leave this unset; connection-backed helpers can use it- * to receive the upstream server URL.- */- readonly connection?: ConnectionAuthorizationContext;- /**- * Optional human-readable provider name shown in sign-in UI. Presentation- * only; it does not affect OAuth scopes, token cache keys, or callback URLs.- */- readonly displayName?: string;+export interface PublicToolDefinition<+ TInput = unknown,+ TOutput = unknown,+> extends ToolDefinitionBase {+ inputSchema: PublicToolInputSchema<TInput>;/**- * Optional Eve auth-flow key for token caches, callback URLs, pending- * authorization state, and authorization completion. This is not an OAuth- * scope. For Vercel Connect OAuth targeting such as `scopes`, `resources`,- * or `authorizationDetails`, configure the provider with- * `connect({ connector, tokenParams })`.+ * Optional schema describing the value returned by the tool executor.+ * The AI SDK can use this for tool result typing.*/- readonly authKey?: string;+ outputSchema?: PublicToolOutputSchema<TOutput>;+}++export interface InternalToolDefinitionWithExecuteFn<+ TInput = unknown,+ TOutput = unknown,+> extends InternalToolDefinition {+ execute: ToolExecuteFn<TInput, TOutput>;+}++export interface PublicToolDefinitionWithExecuteFn<+ TInput = unknown,+ TOutput = unknown,+> extends PublicToolDefinition<TInput, TOutput> {+ execute: ToolExecuteFn<TInput, TOutput>;}/**@@ -326,68 +337,6 @@ export function defineTool<TInput = unknown, TOutput = unknown>(return definition;}-/**- * Defines a dynamic resolver evaluated at runtime from stream-event- * handlers. It is shared across tools, skills, and agent definitions;- * the directory it is- * authored in (not this function) decides what each handler must return- * and which events are honored. The file's path-derived slug names the- * single-entry case; a `Record<string, ...>` return names entries- * `slug__key`. Return `null` to contribute nothing for that event.- *- * Per-slot return shape:- * - `agent/tools/`: return a single `defineTool(...)`, a- * `Record<string, defineTool(...)>`, or `null`.- * - `agent/skills/`: return a single `defineSkill(...)`, a- * `Record<string, defineSkill(...)>`, or `null`.- * - `agent/subagents/<name>/agent.ts`: return `defineAgent(...)` to configure- * and expose the subagent, or `null` to omit it.- *- * Per-slot events: tools resolvers run at `session.started`,- * `turn.started`, and `step.started`. Skills resolvers run only at- * `session.started` and `turn.started`; the runtime never invokes a- * handler keyed on `step.started` in that slot.- * Dynamic subagents run at `session.started` and `turn.started` only.- *- * ```ts- * import { defineDynamic, defineTool } from "eve/tools";- * import { z } from "zod";- *- * export default defineDynamic({- * events: {- * "session.started": async (event, ctx) => ({- * export: defineTool({- * description: "Export data",- * inputSchema: z.object({ format: z.string() }),- * async execute(input) {- * return doExport(input.format);- * },- * }),- * }),- * },- * });- * ```- *- * A single return is named after the file slug. A map names each entry by its- * bare key — there is no automatic slug prefix, so namespace keys yourself- * (e.g. `team__playbook`) when a bare name might collide. A dynamic tool/skill- * whose name matches an authored one overrides it; two dynamic resolvers- * emitting the same name is an error.- */-export function defineDynamic<const TEvents extends DynamicEvents>(definition: {- readonly events: TEvents;-}): DynamicSentinel<DynamicEventMapResult<TEvents>>;-export function defineDynamic<TResult = unknown>(definition: {- readonly events: DynamicEvents<TResult>;-}): DynamicSentinel<TResult> {- const sentinel = {- kind: DYNAMIC_SENTINEL_KIND,- events: definition.events,- } as DynamicSentinel<TResult>;- stampDefinitionKey(sentinel, `dynamic:${Object.keys(definition.events).join(",")}`);- return sentinel;-}-/*** Marker discriminator written into every {@link DisabledToolSentinel}.*/@@ -423,76 +372,3 @@ export function isDisabledToolSentinel(value: unknown): value is DisabledToolSen(value as { kind?: unknown }).kind === DISABLED_TOOL_SENTINEL_KIND);}--/**- * Discriminator written into definitions returned by- * {@link experimental_workflow}.- */-const EXPERIMENTAL_WORKFLOW_TOOL_KIND = "eve:enable-workflow-tool";--/**- * Configuration accepted by {@link experimental_workflow}.- */-export interface ExperimentalWorkflowToolInput {- /**- * Maximum number of subagent or remote-agent calls one `Workflow` program- * may dispatch, counted across sequential and parallel calls alike.- *- * Calls beyond the limit fail with a `WORKFLOW_SUBAGENT_LIMIT_REACHED`- * result instead of starting a child session.- *- * @default 100- */- readonly maxSubagents?: number;-}--/**- * Framework `Workflow` tool definition returned by- * {@link experimental_workflow}.- */-export interface ExperimentalWorkflowToolDefinition extends ExperimentalWorkflowToolInput {- readonly kind: typeof EXPERIMENTAL_WORKFLOW_TOOL_KIND;-}--/**- * Enables and configures the experimental framework `Workflow` tool, an- * isolated JavaScript sandbox whose only callable operations are this agent's- * subagents and remote agents. Export the result from- * `agent/tools/workflow.ts`:- *- * ```ts- * import { experimental_workflow } from "eve/tools";- *- * export default experimental_workflow({ maxSubagents: 25 });- * ```- *- * Only the root session sees the tool. The resulting model-facing tool is- * still called `Workflow`.- */-export function experimental_workflow(- input: ExperimentalWorkflowToolInput = {},-): ExperimentalWorkflowToolDefinition {- const definition: {- kind: typeof EXPERIMENTAL_WORKFLOW_TOOL_KIND;- maxSubagents?: number;- } = {- kind: EXPERIMENTAL_WORKFLOW_TOOL_KIND,- };- if (input.maxSubagents !== undefined) {- definition.maxSubagents = input.maxSubagents;- }- return definition;-}--/**- * Type guard for a definition returned by {@link experimental_workflow}.- */-export function isExperimentalWorkflowToolDefinition(- value: unknown,-): value is ExperimentalWorkflowToolDefinition {- return (- typeof value === "object" &&- value !== null &&- (value as { kind?: unknown }).kind === EXPERIMENTAL_WORKFLOW_TOOL_KIND- );-}diff --git a/packages/eve/src/shared/durable-dynamic-tool-callbacks.ts b/packages/eve/src/tools/durable-callbacks.tssimilarity index 97%rename from packages/eve/src/shared/durable-dynamic-tool-callbacks.tsrename to packages/eve/src/tools/durable-callbacks.tsindex d19e9f3cb..397190e3d 100644--- a/packages/eve/src/shared/durable-dynamic-tool-callbacks.ts+++ b/packages/eve/src/tools/durable-callbacks.ts@@ -1,5 +1,5 @@-import type { Approval } from "#public/definitions/approval.js";-import { resolveApprovalPolicy } from "#public/definitions/approval.js";+import type { Approval } from "#approval/definition.js";+import { resolveApprovalPolicy } from "#approval/definition.js";import type { JsonObject } from "#shared/json.js";export type DurableDynamicCallbackPhase =diff --git a/packages/eve/src/tools/dynamic.ts b/packages/eve/src/tools/dynamic.tsnew file mode 100644index 000000000..4b10bcbce--- /dev/null+++ b/packages/eve/src/tools/dynamic.ts@@ -0,0 +1,90 @@+import type { Approval } from "#approval/definition.js";+import type { DynamicResolveContext, DynamicToolEventName } from "#dynamic/definition.js";+import type {+ PublicToolInputSchema,+ PublicToolOutputSchema,+ ToolContext,+} from "#tools/definition.js";+import type { ToolModelOutput } from "#tools/model-output.js";++/**+ * A single tool entry within a resolved dynamic tool set.+ *+ * Identity comes from context: a single returned entry is named after+ * the file slug; entries in a returned `Record<string, DynamicToolEntry>`+ * are each named `slug__key`.+ *+ * `TInput` defaults to `Record<string, unknown>` but is inferred when+ * `inputSchema` is a Standard Schema (e.g. Zod) via the `defineTool`+ * wrapper. `TOutput` defaults to `any`; provide an `outputSchema`+ * (Standard Schema) to infer and check the executor return type.+ */+// eslint-disable-next-line @typescript-eslint/no-explicit-any+export interface DynamicToolEntry<TInput = Record<string, unknown>, TOutput = any> {+ readonly description: string;+ readonly inputSchema: PublicToolInputSchema<TInput>;+ readonly outputSchema?: PublicToolOutputSchema<TOutput>;+ execute(input: TInput, ctx: ToolContext): TOutput | Promise<TOutput>;+ readonly toModelOutput?: (output: TOutput) => ToolModelOutput | Promise<ToolModelOutput>;+ /**+ * Optional per-call approval gate, mirroring the authored-tool+ * `approval` contract: return `"user-approval"` to require user approval+ * before the call executes. Dynamic approval request and response callbacks+ * use the same durable descriptor boundary as `execute` and `toModelOutput`.+ */+ readonly approval?: Approval;+}++/**+ * A resolved tool set: keys are entry identifiers, values are+ * {@link DynamicToolEntry} objects created via `defineTool` inside a+ * resolver. Entry type params are `any` so entries with differing+ * schemas stay assignable to one Record; `defineTool` captures each+ * entry's concrete types before this widened container.+ */+// eslint-disable-next-line @typescript-eslint/no-explicit-any+export type DynamicToolSet = Readonly<Record<string, DynamicToolEntry<any, any>>>;++/**+ * Return type for a `defineDynamic` event handler: a single tool entry+ * (named after the file slug), a map of entries (named `slug__key`), or+ * `null` for no tools.+ */+// eslint-disable-next-line @typescript-eslint/no-explicit-any+export type DynamicToolResult = DynamicToolEntry<any, any> | DynamicToolSet | null;++/**+ * Strongly-typed tool-handler map: each key is a supported event name,+ * each value a resolver that takes the stream event and resolve context+ * and returns a {@link DynamicToolResult}. `defineDynamic` accepts the+ * wider {@link DynamicEvents} (handlers return `unknown`) because the+ * slot directory (tools/ vs skills/) decides the expected return at+ * runtime. Reference `DynamicToolEvents` to check the tool-specific+ * return type at authoring time.+ */+export type DynamicToolEvents = {+ readonly [K in DynamicToolEventName]?: (+ event: unknown,+ ctx: DynamicResolveContext,+ ) => DynamicToolResult | Promise<DynamicToolResult>;+};++/**+ * Symbol-based brand stamped by `defineTool` on every entry. Invisible+ * in IntelliSense, checked at runtime to enforce the wrapper and to+ * distinguish a single entry from a map of entries.+ */+export const TOOL_BRAND = Symbol.for("eve:tool-brand");++/**+ * Returns true if `value` carries the `defineTool` brand symbol. Used+ * to detect single entry vs map of entries and to validate that entries+ * are properly wrapped.+ */+export function isBrandedToolEntry(value: unknown): boolean {+ return (+ typeof value === "object" &&+ value !== null &&+ (value as Record<symbol, unknown>)[TOOL_BRAND] === true+ );+}diff --git a/packages/eve/src/shared/agent-tool.ts b/packages/eve/src/tools/framework/agent-contract.tssimilarity index 100%rename from packages/eve/src/shared/agent-tool.tsrename to packages/eve/src/tools/framework/agent-contract.tsdiff --git a/packages/eve/src/tools/framework/agent.ts b/packages/eve/src/tools/framework/agent.tsnew file mode 100644index 000000000..23e9328da--- /dev/null+++ b/packages/eve/src/tools/framework/agent.ts@@ -0,0 +1,16 @@+import { defineTool } from "#tools/definition.js";+import {+ AGENT_TOOL_DESCRIPTION,+ SUBAGENT_TOOL_INPUT_SCHEMA,+} from "#tools/framework/agent-contract.js";++/** The harness intercepts this tool before its durable dispatch step executes. */+export const agent = defineTool({+ description: AGENT_TOOL_DESCRIPTION,+ inputSchema: SUBAGENT_TOOL_INPUT_SCHEMA,+ execute() {+ throw new Error("agent is handled by eve's durable dispatch step.");+ },+});++export default agent;diff --git a/packages/eve/src/public/tools/ask-question.test.ts b/packages/eve/src/tools/framework/ask-question.test.tssimilarity index 91%rename from packages/eve/src/public/tools/ask-question.test.tsrename to packages/eve/src/tools/framework/ask-question.test.tsindex 6919c3842..844c865f0 100644--- a/packages/eve/src/public/tools/ask-question.test.ts+++ b/packages/eve/src/tools/framework/ask-question.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from "vitest";-import { ASK_QUESTION_INPUT_SCHEMA, askQuestion } from "#public/tools/ask-question.js";-import { serializeInputSchema } from "#shared/tool-schema.js";+import { ASK_QUESTION_INPUT_SCHEMA, askQuestion } from "#tools/framework/ask-question.js";+import { serializeInputSchema } from "#tools/schema.js";describe("ASK_QUESTION_INPUT_SCHEMA", () => {it("is derived from the input request schema", () => {diff --git a/packages/eve/src/public/tools/ask-question.ts b/packages/eve/src/tools/framework/ask-question.tssimilarity index 85%rename from packages/eve/src/public/tools/ask-question.tsrename to packages/eve/src/tools/framework/ask-question.tsindex 7a5935e5d..f17e54308 100644--- a/packages/eve/src/public/tools/ask-question.ts+++ b/packages/eve/src/tools/framework/ask-question.ts@@ -1,5 +1,5 @@import { z } from "#compiled/zod/index.js";-import { defineTool } from "#public/definitions/tool.js";+import { defineTool } from "#tools/definition.js";import { inputRequestSchema } from "#shared/input.js";export const ASK_QUESTION_INPUT_SCHEMA = inputRequestSchema.omit({@@ -16,7 +16,7 @@ export const ASK_QUESTION_OUTPUT_SCHEMA = z}).strict();-/** Canonical PR 1 source definition; durable execution remains in the harness. */+/** The harness intercepts this tool before its durable input step executes. */export const askQuestion = defineTool({description:"Ask the user a question and wait for their response before continuing. Use this when you need clarification or a choice from the user.",diff --git a/packages/eve/src/tools/connection-search.ts b/packages/eve/src/tools/framework/connection-search.tssimilarity index 84%rename from packages/eve/src/tools/connection-search.tsrename to packages/eve/src/tools/framework/connection-search.tsindex 177e42b10..e29e99aab 100644--- a/packages/eve/src/tools/connection-search.ts+++ b/packages/eve/src/tools/framework/connection-search.ts@@ -1,5 +1,5 @@import { resolveConnectionSearchDynamicTools } from "#execution/tools/connection-search.js";-import { defineDynamic } from "#public/definitions/tool.js";+import { defineDynamic } from "#dynamic/definition.js";/** Canonical definition for dynamic connection tool discovery. */export const connectionSearch = defineDynamic({diff --git a/packages/eve/src/public/tools/task-cancel.ts b/packages/eve/src/tools/framework/task-cancel.tssimilarity index 66%rename from packages/eve/src/public/tools/task-cancel.tsrename to packages/eve/src/tools/framework/task-cancel.tsindex 54f4f6334..dd34e3a3c 100644--- a/packages/eve/src/public/tools/task-cancel.ts+++ b/packages/eve/src/tools/framework/task-cancel.ts@@ -1,7 +1,10 @@-import { defineTool } from "#public/definitions/tool.js";-import { TASK_CANCEL_INPUT_SCHEMA, TASK_VIEWS_OUTPUT_SCHEMA } from "#shared/task-tool.js";+import { defineTool } from "#tools/definition.js";+import {+ TASK_CANCEL_INPUT_SCHEMA,+ TASK_VIEWS_OUTPUT_SCHEMA,+} from "#tools/framework/task-contract.js";-/** Canonical PR 1 source definition; durable execution remains in the harness. */+/** The harness intercepts this tool before its durable dispatch step executes. */export const taskCancel = defineTool({description:"Request cooperative cancellation of one or more background tasks. Cancellation is final: a task that finishes after you cancel it stays cancelled. Cancelling an already-finished task changes nothing.",diff --git a/packages/eve/src/shared/task-tool.ts b/packages/eve/src/tools/framework/task-contract.tssimilarity index 100%rename from packages/eve/src/shared/task-tool.tsrename to packages/eve/src/tools/framework/task-contract.tsdiff --git a/packages/eve/src/public/tools/task-update.ts b/packages/eve/src/tools/framework/task-update.tssimilarity index 63%rename from packages/eve/src/public/tools/task-update.tsrename to packages/eve/src/tools/framework/task-update.tsindex 8ca8d7d33..6aa0adecf 100644--- a/packages/eve/src/public/tools/task-update.ts+++ b/packages/eve/src/tools/framework/task-update.ts@@ -1,7 +1,7 @@-import { defineTool } from "#public/definitions/tool.js";-import { TASK_UPDATE_INPUT_SCHEMA } from "#shared/task-tool.js";+import { defineTool } from "#tools/definition.js";+import { TASK_UPDATE_INPUT_SCHEMA } from "#tools/framework/task-contract.js";-/** Canonical PR 1 source definition; durable execution remains in the harness. */+/** The harness intercepts this tool before its durable dispatch step executes. */export const taskUpdate = defineTool({description:"Briefly tell the parent agent what this background task is currently doing. Report activity, not preliminary findings or results.",diff --git a/packages/eve/src/public/tools/output-builders.ts b/packages/eve/src/tools/model-output.tssimilarity index 61%rename from packages/eve/src/public/tools/output-builders.tsrename to packages/eve/src/tools/model-output.tsindex c15124085..8ae40ee6f 100644--- a/packages/eve/src/public/tools/output-builders.ts+++ b/packages/eve/src/tools/model-output.ts@@ -1,4 +1,35 @@-import type { ToolModelOutput, ToolModelOutputPart } from "#shared/tool-definition.js";+/**+ * eve-owned shape for the model-facing tool result produced by+ * `toModelOutput`. Structurally compatible with the AI SDK's+ * `ToolResultOutput` so the harness can forward it without conversion.+ *+ * The `content` variant carries an ordered list of+ * {@link ToolModelOutputPart} entries, letting a tool hand the model+ * text alongside inline files (e.g. a screenshot as vision input).+ */+export type ToolModelOutput =+ | { readonly type: "text"; readonly value: string }+ | { readonly type: "json"; readonly value: unknown }+ | { readonly type: "content"; readonly value: readonly ToolModelOutputPart[] };++/**+ * One part of a `content` {@link ToolModelOutput}. Mirrors the AI SDK's+ * `ToolResultOutput` content parts narrowed to the JSON-safe subset:+ * file data is the SDK's tagged `FileData` union restricted to+ * `{ type: "data" }` with a base64 string, so persisted tool results+ * survive the durable JSON boundary. Use the `toolOutputPart` builders+ * from `eve/tools` to construct parts without hand-writing the nesting.+ */+export type ToolModelOutputPart =+ | { readonly type: "text"; readonly text: string }+ | {+ readonly type: "file";+ /** Tagged file data; only JSON-safe base64 payloads are accepted. */+ readonly data: { readonly type: "data"; readonly data: string };+ /** IANA media type, e.g. `image/png`. */+ readonly mediaType: string;+ readonly filename?: string;+ };/*** Builders for the model-facing {@link ToolModelOutput} returned bydiff --git a/packages/eve/src/tools/bash.ts b/packages/eve/src/tools/provided/bash.tssimilarity index 66%rename from packages/eve/src/tools/bash.tsrename to packages/eve/src/tools/provided/bash.tsindex 1931d239c..f82251646 100644--- a/packages/eve/src/tools/bash.ts+++ b/packages/eve/src/tools/provided/bash.ts@@ -1,23 +1,17 @@import { z } from "#compiled/zod/index.js";-import { executeBashOnSandbox, type BashInput } from "#execution/sandbox/bash-tool.js";-import { defineTool } from "#public/definitions/tool.js";+import { executeBashOnSandbox, type BashInput } from "#execution/sandbox/bash.js";+import { defineTool, type ToolDefinition } from "#tools/definition.js";/**- * Shared input schema used by the framework `bash` tool and any author tool- * constructed via {@link defineBashTool}.- *- * Exported so the public `defineBashTool` factory and the framework- * `BASH_TOOL_DEFINITION` use the exact same schema object — keeping model- * input contracts in sync without duplication.+ * Input schema for the provided `bash` tool.*/export const BASH_INPUT_SCHEMA = z.strictObject({command: z.string().describe("The shell command to execute."),});/**- * Shared output schema used by the framework `bash` tool and any author tool- * constructed via {@link defineBashTool}.+ * Output schema for the provided `bash` tool.*/export const BASH_OUTPUT_SCHEMA = z.strictObject({exitCode: z.number(),@@ -26,6 +20,9 @@ export const BASH_OUTPUT_SCHEMA = z.strictObject({truncated: z.boolean(),});+export type BashToolInput = z.infer<typeof BASH_INPUT_SCHEMA>;+export type BashToolOutput = z.infer<typeof BASH_OUTPUT_SCHEMA>;+/*** Framework-owned executors stay statically imported so hosted server bundles* can trace and rewrite them into deployable output chunks.@@ -34,7 +31,7 @@ export const BASH_OUTPUT_SCHEMA = z.strictObject({* sandbox dependencies remain lazily loaded inside the execution layer, so the* top-level import here does not force those backends to initialize eagerly.*/-export const bash = defineTool({+export const bash: ToolDefinition<BashToolInput, BashToolOutput> = defineTool({description: "Execute a shell command in the shared workspace environment.",async execute(input, ctx) {return await executeBashOnSandbox(await ctx.getSandbox(), input as BashInput);diff --git a/packages/eve/src/tools/glob.ts b/packages/eve/src/tools/provided/glob.tssimilarity index 73%rename from packages/eve/src/tools/glob.tsrename to packages/eve/src/tools/provided/glob.tsindex 0d1738cf0..864cdbb32 100644--- a/packages/eve/src/tools/glob.ts+++ b/packages/eve/src/tools/provided/glob.ts@@ -1,15 +1,10 @@import { z } from "#compiled/zod/index.js";import { type GlobInput, executeGlobOnSandbox } from "#execution/sandbox/glob-tool.js";-import { defineTool } from "#public/definitions/tool.js";+import { defineTool, type ToolDefinition } from "#tools/definition.js";/**- * Shared input schema used by the framework `glob` tool and any author tool- * constructed via {@link defineGlobTool}.- *- * Exported so the public `defineGlobTool` factory and the framework- * `GLOB_TOOL_DEFINITION` use the exact same schema object — keeping model- * input contracts in sync without duplication.+ * Input schema for the provided `glob` tool.*/export const GLOB_INPUT_SCHEMA = z.strictObject({limit: z@@ -32,8 +27,7 @@ export const GLOB_INPUT_SCHEMA = z.strictObject({});/**- * Shared output schema used by the framework `glob` tool and any author tool- * constructed via {@link defineGlobTool}.+ * Output schema for the provided `glob` tool.*/export const GLOB_OUTPUT_SCHEMA = z.strictObject({content: z.string(),@@ -42,10 +36,13 @@ export const GLOB_OUTPUT_SCHEMA = z.strictObject({truncated: z.boolean(),});+export type GlobToolInput = z.infer<typeof GLOB_INPUT_SCHEMA>;+export type GlobToolOutput = z.infer<typeof GLOB_OUTPUT_SCHEMA>;+/*** Framework-owned executor that delegates to the default sandbox.*/-export const glob = defineTool({+export const glob: ToolDefinition<GlobToolInput, GlobToolOutput> = defineTool({description: ["Fast file pattern matching tool that works with any codebase size.","",diff --git a/packages/eve/src/tools/grep.ts b/packages/eve/src/tools/provided/grep.tssimilarity index 81%rename from packages/eve/src/tools/grep.tsrename to packages/eve/src/tools/provided/grep.tsindex 644d43518..be7a923ff 100644--- a/packages/eve/src/tools/grep.ts+++ b/packages/eve/src/tools/provided/grep.ts@@ -1,15 +1,10 @@import { z } from "#compiled/zod/index.js";import { type GrepInput, executeGrepOnSandbox } from "#execution/sandbox/grep-tool.js";-import { defineTool } from "#public/definitions/tool.js";+import { defineTool, type ToolDefinition } from "#tools/definition.js";/**- * Shared input schema used by the framework `grep` tool and any author tool- * constructed via {@link defineGrepTool}.- *- * Exported so the public `defineGrepTool` factory and the framework- * `GREP_TOOL_DEFINITION` use the exact same schema object — keeping model- * input contracts in sync without duplication.+ * Input schema for the provided `grep` tool.*/export const GREP_INPUT_SCHEMA = z.strictObject({context: z@@ -53,8 +48,7 @@ export const GREP_INPUT_SCHEMA = z.strictObject({});/**- * Shared output schema used by the framework `grep` tool and any author tool- * constructed via {@link defineGrepTool}.+ * Output schema for the provided `grep` tool.*/export const GREP_OUTPUT_SCHEMA = z.strictObject({content: z.string(),@@ -63,10 +57,13 @@ export const GREP_OUTPUT_SCHEMA = z.strictObject({truncated: z.boolean(),});+export type GrepToolInput = z.infer<typeof GREP_INPUT_SCHEMA>;+export type GrepToolOutput = z.infer<typeof GREP_OUTPUT_SCHEMA>;+/*** Framework-owned executor that delegates to the default sandbox.*/-export const grep = defineTool({+export const grep: ToolDefinition<GrepToolInput, GrepToolOutput> = defineTool({description: ["Fast content search tool that works with any codebase size.","",diff --git a/packages/eve/src/tools/load-skill.ts b/packages/eve/src/tools/provided/load-skill.tssimilarity index 91%rename from packages/eve/src/tools/load-skill.tsrename to packages/eve/src/tools/provided/load-skill.tsindex 939ffe823..50a38a9bc 100644--- a/packages/eve/src/tools/load-skill.ts+++ b/packages/eve/src/tools/provided/load-skill.ts@@ -3,7 +3,7 @@ import {SKILL_INPUT_SCHEMA,SKILL_OUTPUT_SCHEMA,} from "#execution/tools/load-skill.js";-import { defineTool } from "#public/definitions/tool.js";+import { defineTool } from "#tools/definition.js";export const loadSkill = defineTool({description: [diff --git a/packages/eve/src/tools/read-file.ts b/packages/eve/src/tools/provided/read-file.tssimilarity index 76%rename from packages/eve/src/tools/read-file.tsrename to packages/eve/src/tools/provided/read-file.tsindex 5e66380c8..4fb624cdb 100644--- a/packages/eve/src/tools/read-file.ts+++ b/packages/eve/src/tools/provided/read-file.ts@@ -1,15 +1,10 @@import { z } from "#compiled/zod/index.js";-import { type ReadFileInput, executeReadFileOnSandbox } from "#execution/sandbox/read-file-tool.js";-import { defineTool } from "#public/definitions/tool.js";+import { type ReadFileInput, executeReadFileOnSandbox } from "#execution/sandbox/read-file.js";+import { defineTool, type ToolDefinition } from "#tools/definition.js";/**- * Shared input schema used by the framework `read_file` tool and any author- * tool constructed via {@link defineReadFileTool}.- *- * Exported so the public `defineReadFileTool` factory and the framework- * `READ_FILE_TOOL_DEFINITION` use the exact same schema object — keeping- * model input contracts in sync without duplication.+ * Input schema for the provided `read_file` tool.*/export const READ_FILE_INPUT_SCHEMA = z.strictObject({filePath: z@@ -30,8 +25,7 @@ export const READ_FILE_INPUT_SCHEMA = z.strictObject({});/**- * Shared output schema used by the framework `read_file` tool and any author- * tool constructed via {@link defineReadFileTool}.+ * Output schema for the provided `read_file` tool.*/export const READ_FILE_OUTPUT_SCHEMA = z.strictObject({content: z.string(),@@ -41,10 +35,13 @@ export const READ_FILE_OUTPUT_SCHEMA = z.strictObject({truncated: z.boolean(),});+export type ReadFileToolInput = z.infer<typeof READ_FILE_INPUT_SCHEMA>;+export type ReadFileToolOutput = z.infer<typeof READ_FILE_OUTPUT_SCHEMA>;+/*** Framework-owned executor that delegates to the default sandbox.*/-export const readFile = defineTool({+export const readFile: ToolDefinition<ReadFileToolInput, ReadFileToolOutput> = defineTool({description: ["Read a file from the local filesystem. If the path does not exist, an error is returned.","",diff --git a/packages/eve/src/public/tools/sleep/index.test.ts b/packages/eve/src/tools/provided/sleep.test.tssimilarity index 95%rename from packages/eve/src/public/tools/sleep/index.test.tsrename to packages/eve/src/tools/provided/sleep.test.tsindex c1737028a..7996f5f68 100644--- a/packages/eve/src/public/tools/sleep/index.test.ts+++ b/packages/eve/src/tools/provided/sleep.test.ts@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";import { ContextContainer, contextStorage } from "#context/container.js";import { readTurnSleepDurationMs } from "#harness/turn-sleep.js";-import { sleep } from "#public/tools/sleep/index.js";+import { sleep } from "#tools/provided/sleep.js";describe("sleep", () => {it("defines a model-facing tool that requests a turn sleep in seconds", async () => {diff --git a/packages/eve/src/tools/sleep.ts b/packages/eve/src/tools/provided/sleep.tssimilarity index 90%rename from packages/eve/src/tools/sleep.tsrename to packages/eve/src/tools/provided/sleep.tsindex 94b8ac5d8..91ffb6f99 100644--- a/packages/eve/src/tools/sleep.ts+++ b/packages/eve/src/tools/provided/sleep.ts@@ -1,4 +1,4 @@-import { defineTool, type ToolDefinition } from "#public/definitions/tool.js";+import { defineTool, type ToolDefinition } from "#tools/definition.js";import {executeSleepTool,SLEEP_INPUT_SCHEMA,diff --git a/packages/eve/src/tools/todo.ts b/packages/eve/src/tools/provided/todo.tssimilarity index 95%rename from packages/eve/src/tools/todo.tsrename to packages/eve/src/tools/provided/todo.tsindex 6ca970dce..180724527 100644--- a/packages/eve/src/tools/todo.ts+++ b/packages/eve/src/tools/provided/todo.ts@@ -4,7 +4,7 @@ import {TODO_OUTPUT_SCHEMA,type TodoToolInput,} from "#execution/tools/todo.js";-import { defineTool } from "#public/definitions/tool.js";+import { defineTool } from "#tools/definition.js";export const todo = defineTool({description: [diff --git a/packages/eve/src/tools/web-fetch.ts b/packages/eve/src/tools/provided/web-fetch.tssimilarity index 83%rename from packages/eve/src/tools/web-fetch.tsrename to packages/eve/src/tools/provided/web-fetch.tsindex 0aa0da771..32dc0f609 100644--- a/packages/eve/src/tools/web-fetch.ts+++ b/packages/eve/src/tools/provided/web-fetch.ts@@ -1,7 +1,7 @@import { z } from "#compiled/zod/index.js";-import { type WebFetchInput, executeWebFetchTool } from "#execution/web-fetch/tool.js";-import { defineTool } from "#public/definitions/tool.js";+import { type WebFetchInput, executeWebFetchTool } from "#execution/web-fetch/execute.js";+import { defineTool, type ToolDefinition } from "#tools/definition.js";export const WEB_FETCH_INPUT_SCHEMA = z.strictObject({format: z@@ -21,7 +21,10 @@ export const WEB_FETCH_OUTPUT_SCHEMA = z.strictObject({url: z.string(),});-export const webFetch = defineTool({+export type WebFetchToolInput = z.infer<typeof WEB_FETCH_INPUT_SCHEMA>;+export type WebFetchToolOutput = z.infer<typeof WEB_FETCH_OUTPUT_SCHEMA>;++export const webFetch: ToolDefinition<WebFetchToolInput, WebFetchToolOutput> = defineTool({description: ["Fetch a webpage and return its content in the requested format. Use this to retrieve and analyze content from URLs.","",diff --git a/packages/eve/src/public/tools/web-search.test.ts b/packages/eve/src/tools/provided/web-search.test.tssimilarity index 82%rename from packages/eve/src/public/tools/web-search.test.tsrename to packages/eve/src/tools/provided/web-search.test.tsindex 53d838f5f..7c36da002 100644--- a/packages/eve/src/public/tools/web-search.test.ts+++ b/packages/eve/src/tools/provided/web-search.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { webSearch } from "#public/tools/web-search.js";+import { webSearch } from "#tools/provided/web-search.js";describe("webSearch", () => {it.each(["parallel", "exa"] as const)("configures the %s provider", (provider) => {diff --git a/packages/eve/src/tools/provided/web-search.ts b/packages/eve/src/tools/provided/web-search.tsnew file mode 100644index 000000000..f9ac474ac--- /dev/null+++ b/packages/eve/src/tools/provided/web-search.ts@@ -0,0 +1,58 @@+import type { WebSearchProvider } from "#shared/web-search.js";++export type { WebSearchProvider };++const WEB_SEARCH_TOOL_KIND = "eve:web-search-tool";++/** Configuration accepted by {@link webSearch}. */+export interface WebSearchToolInput {+ /** Provider to use when the agent model is routed through AI Gateway. */+ readonly provider: WebSearchProvider;+}++/**+ * Provider-managed web search configuration.+ *+ * Export this from `agent/tools/web_search.ts` to select the AI Gateway+ * search provider for that agent. Direct provider models continue to use+ * their native web search implementation.+ */+export interface WebSearchToolDefinition {+ readonly kind: typeof WEB_SEARCH_TOOL_KIND;+ readonly provider: WebSearchProvider;+}++/**+ * Configures the framework-provided `web_search` tool.+ *+ * When no configuration file is present, eve uses Exa for AI Gateway+ * models.+ *+ * @example+ * ```ts+ * // agent/tools/web_search.ts+ * import { webSearch } from "eve/tools/web_search";+ *+ * export default webSearch({ provider: "parallel" });+ * ```+ */+export function webSearch(input: WebSearchToolInput): WebSearchToolDefinition {+ return {+ kind: WEB_SEARCH_TOOL_KIND,+ provider: input.provider,+ };+}++/** Default provider-managed web search configuration. */+export const defaultWebSearch = webSearch({ provider: "exa" });++export default defaultWebSearch;++/** Returns whether a value is a provider-managed web search definition. */+export function isWebSearchToolDefinition(value: unknown): value is WebSearchToolDefinition {+ return (+ typeof value === "object" &&+ value !== null &&+ (value as { kind?: unknown }).kind === WEB_SEARCH_TOOL_KIND+ );+}diff --git a/packages/eve/src/tools/write-file.ts b/packages/eve/src/tools/provided/write-file.tssimilarity index 68%rename from packages/eve/src/tools/write-file.tsrename to packages/eve/src/tools/provided/write-file.tsindex 40b86822e..1f4426be1 100644--- a/packages/eve/src/tools/write-file.ts+++ b/packages/eve/src/tools/provided/write-file.ts@@ -1,18 +1,10 @@import { z } from "#compiled/zod/index.js";-import {- type WriteFileInput,- executeWriteFileOnSandbox,-} from "#execution/sandbox/write-file-tool.js";-import { defineTool } from "#public/definitions/tool.js";+import { type WriteFileInput, executeWriteFileOnSandbox } from "#execution/sandbox/write-file.js";+import { defineTool, type ToolDefinition } from "#tools/definition.js";/**- * Shared input schema used by the framework `write_file` tool and any author- * tool constructed via {@link defineWriteFileTool}.- *- * Exported so the public `defineWriteFileTool` factory and the framework- * `WRITE_FILE_TOOL_DEFINITION` use the exact same schema object — keeping- * model input contracts in sync without duplication.+ * Input schema for the provided `write_file` tool.*/export const WRITE_FILE_INPUT_SCHEMA = z.strictObject({content: z.string().describe("Complete replacement file contents."),@@ -22,18 +14,20 @@ export const WRITE_FILE_INPUT_SCHEMA = z.strictObject({});/**- * Shared output schema used by the framework `write_file` tool and any author- * tool constructed via {@link defineWriteFileTool}.+ * Output schema for the provided `write_file` tool.*/export const WRITE_FILE_OUTPUT_SCHEMA = z.strictObject({existed: z.boolean(),path: z.string(),});+export type WriteFileToolInput = z.infer<typeof WRITE_FILE_INPUT_SCHEMA>;+export type WriteFileToolOutput = z.infer<typeof WRITE_FILE_OUTPUT_SCHEMA>;+/*** Framework-owned executor that delegates to the default sandbox.*/-export const writeFile = defineTool({+export const writeFile: ToolDefinition<WriteFileToolInput, WriteFileToolOutput> = defineTool({description: ["Writes a file to the local filesystem.","",diff --git a/packages/eve/src/shared/tool-schema.test.ts b/packages/eve/src/tools/schema.test.tssimilarity index 99%rename from packages/eve/src/shared/tool-schema.test.tsrename to packages/eve/src/tools/schema.test.tsindex 3bee57a27..dbfaf6705 100644--- a/packages/eve/src/shared/tool-schema.test.ts+++ b/packages/eve/src/tools/schema.test.ts@@ -10,7 +10,7 @@ import {serializeOutputSchema,toInputSchema,toOutputSchema,-} from "#shared/tool-schema.js";+} from "#tools/schema.js";describe("ToolSchema", () => {it("rehydrates and validates serialized JSON Schema", async () => {diff --git a/packages/eve/src/shared/tool-schema.ts b/packages/eve/src/tools/schema.tssimilarity index 100%rename from packages/eve/src/shared/tool-schema.tsrename to packages/eve/src/tools/schema.tsdiff --git a/packages/eve/src/shared/tool-task.ts b/packages/eve/src/tools/task.tssimilarity index 100%rename from packages/eve/src/shared/tool-task.tsrename to packages/eve/src/tools/task.tsdiff --git a/packages/eve/src/tools/workflow.ts b/packages/eve/src/tools/workflow.tsnew file mode 100644index 000000000..166a89ac5--- /dev/null+++ b/packages/eve/src/tools/workflow.ts@@ -0,0 +1,61 @@+const EXPERIMENTAL_WORKFLOW_TOOL_KIND = "eve:enable-workflow-tool";++/** Configuration accepted by {@link experimental_workflow}. */+export interface ExperimentalWorkflowToolInput {+ /**+ * Maximum number of subagent or remote-agent calls one `Workflow` program+ * may dispatch, counted across sequential and parallel calls alike.+ *+ * Calls beyond the limit fail with a `WORKFLOW_SUBAGENT_LIMIT_REACHED`+ * result instead of starting a child session.+ *+ * @default 100+ */+ readonly maxSubagents?: number;+}++/** Framework `Workflow` tool definition returned by {@link experimental_workflow}. */+export interface ExperimentalWorkflowToolDefinition extends ExperimentalWorkflowToolInput {+ readonly kind: typeof EXPERIMENTAL_WORKFLOW_TOOL_KIND;+}++/**+ * Enables and configures the experimental framework `Workflow` tool, an+ * isolated JavaScript sandbox whose only callable operations are this agent's+ * subagents and remote agents. Export the result from+ * `agent/tools/workflow.ts`:+ *+ * ```ts+ * import { experimental_workflow } from "eve/tools";+ *+ * export default experimental_workflow({ maxSubagents: 25 });+ * ```+ *+ * Only the root session sees the tool. The resulting model-facing tool is+ * still called `Workflow`.+ */+export function experimental_workflow(+ input: ExperimentalWorkflowToolInput = {},+): ExperimentalWorkflowToolDefinition {+ const definition: {+ kind: typeof EXPERIMENTAL_WORKFLOW_TOOL_KIND;+ maxSubagents?: number;+ } = {+ kind: EXPERIMENTAL_WORKFLOW_TOOL_KIND,+ };+ if (input.maxSubagents !== undefined) {+ definition.maxSubagents = input.maxSubagents;+ }+ return definition;+}++/** Type guard for a definition returned by {@link experimental_workflow}. */+export function isExperimentalWorkflowToolDefinition(+ value: unknown,+): value is ExperimentalWorkflowToolDefinition {+ return (+ typeof value === "object" &&+ value !== null &&+ (value as { kind?: unknown }).kind === EXPERIMENTAL_WORKFLOW_TOOL_KIND+ );+}diff --git a/packages/eve/test/define-bash-tool.test.ts b/packages/eve/test/define-bash-tool.test.tsdeleted file mode 100644index a605dd9c9..000000000--- a/packages/eve/test/define-bash-tool.test.ts+++ /dev/null@@ -1,186 +0,0 @@-import { describe, expect, it } from "vitest";--import { stubSpawnProcess } from "./_helpers/sandbox-session-stub.js";--import { ContextContainer, contextStorage } from "../src/context/container.js";-import { SandboxKey } from "../src/context/keys.js";-import type { SandboxAccess } from "../src/sandbox/state.js";-import { defineBashTool } from "../src/public/tools/define-bash-tool.js";-import { serializeInputSchema } from "../src/shared/tool-schema.js";--describe("defineBashTool", () => {- it("produces a schema that never exposes a sandbox property to the model", () => {- const tool = defineBashTool();-- expect(tool).not.toHaveProperty("name");- expect(tool.description).toBe("Execute a shell command in the workspace sandbox.");- expect(typeof tool.execute).toBe("function");-- const schema = serializeInputSchema(tool.inputSchema);- expect(schema).toMatchObject({- properties: { command: { type: "string" } },- required: ["command"],- type: "object",- });- expect((schema.properties as Record<string, unknown>).sandbox).toBeUndefined();- });-- it("uses an authored description when provided", () => {- const tool = defineBashTool({- description: "Run shell commands in the cloned repo.",- });-- expect(tool.description).toBe("Run shell commands in the cloned repo.");- });-- it("dispatches shell commands to the agent's sandbox", async () => {- const recordedCommands: { command: string }[] = [];- const fakeAccess: SandboxAccess = {- async captureState() {- return {- initialized: false,- session: null,- };- },-- async stop() {},-- async get() {- return {- id: "test-bash-sandbox",- async readFile() {- return null;- },- async readBinaryFile() {- return null;- },- async readTextFile() {- return null;- },- async setNetworkPolicy() {},- async removePath() {},- resolvePath(path: string) {- return path;- },- async run({ command }: { command: string }) {- recordedCommands.push({ command });- return { exitCode: 0, stderr: "", stdout: `stdout:${command}` };- },- async spawn() {- return stubSpawnProcess();- },- async writeFile() {},- async writeBinaryFile() {},- async writeTextFile() {},- };- },- };-- const tool = defineBashTool();-- const ctx = new ContextContainer();- ctx.set(SandboxKey, fakeAccess);-- const result = await contextStorage.run(ctx, async () =>- tool.execute({ command: "echo hi" }, { getSandbox: () => fakeAccess.get() } as any),- );-- expect(result).toEqual({ exitCode: 0, stderr: "", stdout: "stdout:echo hi", truncated: false });- expect(recordedCommands).toEqual([{ command: "echo hi" }]);- });-- // ---------------------------------------------------------------------------- // Error case- // ----------------------------------------------------------------------------- it("throws a clear error when no sandbox session is available", async () => {- const fakeAccess: SandboxAccess = {- async captureState() {- return {- initialized: false,- session: null,- };- },-- async stop() {},-- async get() {- return null;- },- };-- const tool = defineBashTool();-- const ctx = new ContextContainer();- ctx.set(SandboxKey, fakeAccess);-- await expect(- contextStorage.run(ctx, async () =>- tool.execute({ command: "echo" }, {- getSandbox: () =>- Promise.reject(- new Error("The sandbox is not available in the current runtime context."),- ),- } as any),- ),- ).rejects.toThrow("The sandbox is not available in the current runtime context.");- });-- // ---------------------------------------------------------------------------- // Truncation- // ----------------------------------------------------------------------------- it("truncates large stdout and preserves the tail", async () => {- const largeOutput = Array.from({ length: 3000 }, (_, i) => `line ${i + 1}`).join("\n");- const fakeAccess: SandboxAccess = {- async captureState() {- return { initialized: false, session: null };- },-- async stop() {},-- async get() {- return {- id: "test-bash-sandbox-large",- async readFile() {- return null;- },- async run() {- return { exitCode: 0, stderr: "", stdout: largeOutput };- },- async spawn() {- return stubSpawnProcess();- },- async writeFile() {},- async writeBinaryFile() {},- async writeTextFile() {},- async readBinaryFile() {- return null;- },- async readTextFile() {- return null;- },- async setNetworkPolicy() {},- async removePath() {},- resolvePath(arg: string) {- return arg;- },- };- },- };-- const tool = defineBashTool();- const ctx = new ContextContainer();- ctx.set(SandboxKey, fakeAccess);-- const result = (await contextStorage.run(ctx, async () =>- tool.execute({ command: "seq 3000" }, { getSandbox: () => fakeAccess.get() } as any),- )) as { exitCode: number; stderr: string; stdout: string; truncated: boolean };-- expect(result.truncated).toBe(true);- // Should keep the tail (last lines)- expect(result.stdout).toContain("line 3000");- // Should have the truncation notice- expect(result.stdout).toContain("[stdout truncated:");- });-});diff --git a/packages/eve/test/define-glob-tool.test.ts b/packages/eve/test/define-glob-tool.test.tsdeleted file mode 100644index eb04629df..000000000--- a/packages/eve/test/define-glob-tool.test.ts+++ /dev/null@@ -1,167 +0,0 @@-import { describe, expect, it } from "vitest";--import { stubSpawnProcess } from "./_helpers/sandbox-session-stub.js";--import { ContextContainer, contextStorage } from "../src/context/container.js";-import { SandboxKey } from "../src/context/keys.js";-import type { SandboxAccess } from "../src/sandbox/state.js";-import { defineGlobTool } from "../src/public/tools/define-glob-tool.js";-import { serializeInputSchema } from "../src/shared/tool-schema.js";--function createFakeAccess(- handler: (command: string) => { exitCode: number; stderr: string; stdout: string } | null,-): SandboxAccess {- return {- async captureState() {- return { initialized: false, session: null };- },-- async stop() {},-- async get() {- const callHandler = handler;- if (callHandler === null) return null;- return {- id: `test-glob-sandbox-${crypto.randomUUID()}`,- async readFile() {- return null;- },- async readBinaryFile() {- return null;- },- async readTextFile() {- return null;- },- async setNetworkPolicy() {},- async removePath() {},- resolvePath(path: string) {- return path;- },- async run({ command }: { command: string }) {- const result = callHandler(command);- if (result === null) {- throw new Error("no handler");- }- return result;- },- async spawn() {- return stubSpawnProcess();- },- async writeFile() {},- async writeBinaryFile() {},- async writeTextFile() {},- };- },- };-}--describe("defineGlobTool", () => {- it("produces a schema that never exposes a sandbox property to the model", () => {- const tool = defineGlobTool();-- expect(tool).not.toHaveProperty("name");- expect(tool.description).toBe("Search for files by glob pattern in the workspace sandbox.");- expect(typeof tool.execute).toBe("function");-- const schema = serializeInputSchema(tool.inputSchema);- expect(schema).toMatchObject({- properties: { pattern: { type: "string" } },- required: ["pattern"],- type: "object",- });- expect((schema.properties as Record<string, unknown>).sandbox).toBeUndefined();- });-- it("uses an authored description when provided", () => {- const tool = defineGlobTool({- description: "Search for files in the repo.",- });-- expect(tool.description).toBe("Search for files in the repo.");- });-- it("dispatches glob commands to the agent's sandbox", async () => {- const fakeAccess = createFakeAccess(() => ({- exitCode: 0,- stderr: "",- stdout: "/workspace/foo.ts\n",- }));-- const tool = defineGlobTool();-- const ctx = new ContextContainer();- ctx.set(SandboxKey, fakeAccess);-- const result = (await contextStorage.run(ctx, async () =>- tool.execute({ pattern: "**/*.ts" }, { getSandbox: () => fakeAccess.get() } as any),- )) as { content: string; count: number };-- expect(result.count).toBe(1);- expect(result.content).toContain("/workspace/foo.ts");- });-- it("throws a clear error when no sandbox session is available", async () => {- const fakeAccess: SandboxAccess = {- async captureState() {- return { initialized: false, session: null };- },-- async stop() {},-- async get() {- return null;- },- };-- const tool = defineGlobTool();-- const ctx = new ContextContainer();- ctx.set(SandboxKey, fakeAccess);-- await expect(- contextStorage.run(ctx, async () =>- tool.execute({ pattern: "**/*.ts" }, {- getSandbox: () =>- Promise.reject(- new Error("The sandbox is not available in the current runtime context."),- ),- } as any),- ),- ).rejects.toThrow("The sandbox is not available in the current runtime context.");- });-- // ---------------------------------------------------------------------------- // Truncation- // ----------------------------------------------------------------------------- it("truncates results that exceed the byte cap", async () => {- // Generate 500 very long file paths (~200 chars each) = ~100KB > 50KB limit- const longPaths = Array.from(- { length: 500 },- (_, i) => `/workspace/deeply/nested/${"sub/".repeat(20)}file_${i}.ts`,- );- const fakeAccess = createFakeAccess(() => ({- exitCode: 0,- stderr: "",- stdout: longPaths.join("\n"),- }));-- const tool = defineGlobTool();- const ctx = new ContextContainer();- ctx.set(SandboxKey, fakeAccess);-- const result = (await contextStorage.run(ctx, async () =>- tool.execute(- {- pattern: "**/*.ts",- limit: 500,- },- { getSandbox: () => fakeAccess.get() } as any,- ),- )) as { content: string; count: number; truncated: boolean };-- expect(result.truncated).toBe(true);- expect(result.count).toBeLessThan(500);- expect(Buffer.byteLength(result.content, "utf8")).toBeLessThan(60_000);- });-});diff --git a/packages/eve/test/define-grep-tool.test.ts b/packages/eve/test/define-grep-tool.test.tsdeleted file mode 100644index 93ce2eda5..000000000--- a/packages/eve/test/define-grep-tool.test.ts+++ /dev/null@@ -1,132 +0,0 @@-import { describe, expect, it } from "vitest";--import { stubSpawnProcess } from "./_helpers/sandbox-session-stub.js";--import { ContextContainer, contextStorage } from "../src/context/container.js";-import { SandboxKey } from "../src/context/keys.js";-import type { SandboxAccess } from "../src/sandbox/state.js";-import { defineGrepTool } from "../src/public/tools/define-grep-tool.js";-import { serializeInputSchema } from "../src/shared/tool-schema.js";--function createFakeAccess(- handler: (command: string) => { exitCode: number; stderr: string; stdout: string } | null,-): SandboxAccess {- return {- async captureState() {- return { initialized: false, session: null };- },-- async stop() {},-- async get() {- const callHandler = handler;- if (callHandler === null) return null;- return {- id: `test-grep-sandbox-${crypto.randomUUID()}`,- async readFile() {- return null;- },- async readBinaryFile() {- return null;- },- async readTextFile() {- return null;- },- async setNetworkPolicy() {},- async removePath() {},- resolvePath(path: string) {- return path;- },- async run({ command }: { command: string }) {- const result = callHandler(command);- if (result === null) {- throw new Error("no handler");- }- return result;- },- async spawn() {- return stubSpawnProcess();- },- async writeFile() {},- async writeBinaryFile() {},- async writeTextFile() {},- };- },- };-}--describe("defineGrepTool", () => {- it("produces a schema that never exposes a sandbox property to the model", () => {- const tool = defineGrepTool();-- expect(tool).not.toHaveProperty("name");- expect(tool.description).toBe("Search file contents by pattern in the workspace sandbox.");- expect(typeof tool.execute).toBe("function");-- const schema = serializeInputSchema(tool.inputSchema);- expect(schema).toMatchObject({- properties: { pattern: { type: "string" } },- required: ["pattern"],- type: "object",- });- expect((schema.properties as Record<string, unknown>).sandbox).toBeUndefined();- });-- it("uses an authored description when provided", () => {- const tool = defineGrepTool({- description: "Search code in the repo.",- });-- expect(tool.description).toBe("Search code in the repo.");- });-- it("dispatches grep commands to the agent's sandbox", async () => {- const fakeAccess = createFakeAccess(() => ({- exitCode: 0,- stderr: "",- stdout: "/workspace/foo.ts:10:const x = 1;\n",- }));-- const tool = defineGrepTool();-- const ctx = new ContextContainer();- ctx.set(SandboxKey, fakeAccess);-- const result = (await contextStorage.run(ctx, async () =>- tool.execute({ pattern: "const x" }, { getSandbox: () => fakeAccess.get() } as any),- )) as { content: string; matchCount: number };-- expect(result.matchCount).toBe(1);- expect(result.content).toContain("/workspace/foo.ts:10:const x = 1;");- });-- it("throws a clear error when no sandbox session is available", async () => {- const fakeAccess: SandboxAccess = {- async captureState() {- return { initialized: false, session: null };- },-- async stop() {},-- async get() {- return null;- },- };-- const tool = defineGrepTool();-- const ctx = new ContextContainer();- ctx.set(SandboxKey, fakeAccess);-- await expect(- contextStorage.run(ctx, async () =>- tool.execute({ pattern: "foo" }, {- getSandbox: () =>- Promise.reject(- new Error("The sandbox is not available in the current runtime context."),- ),- } as any),- ),- ).rejects.toThrow("The sandbox is not available in the current runtime context.");- });-});diff --git a/packages/eve/test/define-read-file-tool.test.ts b/packages/eve/test/define-read-file-tool.test.tsdeleted file mode 100644index daaa1c52d..000000000--- a/packages/eve/test/define-read-file-tool.test.ts+++ /dev/null@@ -1,129 +0,0 @@-import { describe, expect, it } from "vitest";--import { stubSpawnProcess } from "./_helpers/sandbox-session-stub.js";--import { ContextContainer, contextStorage } from "../src/context/container.js";-import { SandboxKey } from "../src/context/keys.js";-import type { SandboxAccess } from "../src/sandbox/state.js";-import { defineReadFileTool } from "../src/public/tools/define-read-file-tool.js";-import { serializeInputSchema } from "../src/shared/tool-schema.js";-import { ReadFileStateKey } from "../src/execution/tools/file-state.js";--function createFakeAccess(files: Record<string, string>): SandboxAccess {- return {- async captureState() {- return { initialized: false, session: null };- },-- async stop() {},-- async get() {- return {- id: "test-read-file-sandbox",- async readFile() {- return null;- },- async readBinaryFile() {- return null;- },- async readTextFile({ path }: { path: string }) {- return files[path] ?? null;- },- async setNetworkPolicy() {},- async removePath() {},- resolvePath(path: string) {- return path;- },- async run(_options: { command: string }) {- return { exitCode: 0, stderr: "", stdout: "" };- },- async spawn() {- return stubSpawnProcess();- },- async writeFile() {},- async writeBinaryFile() {},- async writeTextFile() {},- };- },- };-}--describe("defineReadFileTool", () => {- it("produces a schema that never exposes a sandbox property to the model", () => {- const tool = defineReadFileTool();-- expect(tool).not.toHaveProperty("name");- expect(tool.description).toBe("Read a file from the workspace sandbox.");- expect(typeof tool.execute).toBe("function");-- const schema = serializeInputSchema(tool.inputSchema);- expect(schema).toMatchObject({- properties: { filePath: { type: "string" } },- required: ["filePath"],- type: "object",- });- expect((schema.properties as Record<string, unknown>).sandbox).toBeUndefined();- });-- it("uses an authored description when provided", () => {- const tool = defineReadFileTool({- description: "Read files from the repo.",- });-- expect(tool.description).toBe("Read files from the repo.");- });-- it("dispatches read_file calls to the agent's sandbox", async () => {- const fakeAccess = createFakeAccess({ "/workspace/foo.ts": "line1\nline2\n" });-- const tool = defineReadFileTool();-- const ctx = new ContextContainer();- ctx.set(SandboxKey, fakeAccess);- ctx.set(ReadFileStateKey, { byTarget: {} });-- const result = (await contextStorage.run(ctx, async () =>- tool.execute(- {- filePath: "/workspace/foo.ts",- },- { getSandbox: () => fakeAccess.get() } as any,- ),- )) as { content: string; totalLines: number };-- expect(result.totalLines).toBe(2);- expect(result.content).toContain("1: line1");- expect(result.content).toContain("2: line2");- });-- it("throws a clear error when no sandbox session is available", async () => {- const fakeAccess: SandboxAccess = {- async captureState() {- return { initialized: false, session: null };- },-- async stop() {},-- async get() {- return null;- },- };-- const tool = defineReadFileTool();-- const ctx = new ContextContainer();- ctx.set(SandboxKey, fakeAccess);- ctx.set(ReadFileStateKey, { byTarget: {} });-- await expect(- contextStorage.run(ctx, async () =>- tool.execute({ filePath: "/workspace/foo.ts" }, {- getSandbox: () =>- Promise.reject(- new Error("The sandbox is not available in the current runtime context."),- ),- } as any),- ),- ).rejects.toThrow("The sandbox is not available in the current runtime context.");- });-});diff --git a/packages/eve/test/define-write-file-tool.test.ts b/packages/eve/test/define-write-file-tool.test.tsdeleted file mode 100644index 76df73f07..000000000--- a/packages/eve/test/define-write-file-tool.test.ts+++ /dev/null@@ -1,191 +0,0 @@-import { describe, expect, it } from "vitest";--import { stubSpawnProcess } from "./_helpers/sandbox-session-stub.js";--import { ContextContainer, contextStorage } from "../src/context/container.js";-import { SandboxKey } from "../src/context/keys.js";-import type { SandboxAccess } from "../src/sandbox/state.js";-import { defineWriteFileTool } from "../src/public/tools/define-write-file-tool.js";-import { serializeInputSchema } from "../src/shared/tool-schema.js";-import { createReadFileStamp, ReadFileStateKey } from "../src/execution/tools/file-state.js";--function createFakeAccess(files: Record<string, string>): SandboxAccess {- return {- async captureState() {- return { initialized: false, session: null };- },-- async stop() {},-- async get() {- return {- id: "test-write-file-sandbox",- async readFile() {- return null;- },- async readBinaryFile() {- return null;- },- async readTextFile({ path }: { path: string }) {- return files[path] ?? null;- },- async setNetworkPolicy() {},- async removePath() {},- resolvePath(path: string) {- return path;- },- async run(_options: { command: string }) {- return { exitCode: 0, stderr: "", stdout: "" };- },- async spawn() {- return stubSpawnProcess();- },- async writeFile() {},- async writeBinaryFile() {},- async writeTextFile({ path, content }: { path: string; content: string }) {- files[path] = content;- },- };- },- };-}--describe("defineWriteFileTool", () => {- it("produces a schema that never exposes a sandbox property to the model", () => {- const tool = defineWriteFileTool();-- expect(tool).not.toHaveProperty("name");- expect(tool.description).toBe("Write a file to the workspace sandbox.");- expect(typeof tool.execute).toBe("function");-- const schema = serializeInputSchema(tool.inputSchema);- expect(schema).toMatchObject({- properties: {- content: { type: "string" },- filePath: { type: "string" },- },- type: "object",- });- expect(new Set(schema.required as string[])).toEqual(new Set(["filePath", "content"]));- expect((schema.properties as Record<string, unknown>).sandbox).toBeUndefined();- });-- it("uses an authored description when provided", () => {- const tool = defineWriteFileTool({- description: "Write files to the repo.",- });-- expect(tool.description).toBe("Write files to the repo.");- });-- it("writes new files through the agent's sandbox", async () => {- const files: Record<string, string> = {};- const fakeAccess = createFakeAccess(files);-- const tool = defineWriteFileTool();-- const ctx = new ContextContainer();- ctx.set(SandboxKey, fakeAccess);- ctx.set(ReadFileStateKey, { byTarget: {} });-- const result = (await contextStorage.run(ctx, async () =>- tool.execute(- {- filePath: "/workspace/new.ts",- content: "hello",- },- { getSandbox: () => fakeAccess.get() } as any,- ),- )) as { existed: boolean; path: string };-- expect(result.existed).toBe(false);- expect(result.path).toBe("/workspace/new.ts");- expect(files["/workspace/new.ts"]).toBe("hello");- });-- it("throws a clear error when no sandbox session is available", async () => {- const fakeAccess: SandboxAccess = {- async captureState() {- return { initialized: false, session: null };- },-- async stop() {},-- async get() {- return null;- },- };-- const tool = defineWriteFileTool();-- const ctx = new ContextContainer();- ctx.set(SandboxKey, fakeAccess);- ctx.set(ReadFileStateKey, { byTarget: {} });-- await expect(- contextStorage.run(ctx, async () =>- tool.execute({ filePath: "/workspace/foo.ts", content: "x" }, {- getSandbox: () =>- Promise.reject(- new Error("The sandbox is not available in the current runtime context."),- ),- } as any),- ),- ).rejects.toThrow("The sandbox is not available in the current runtime context.");- });-- it("rejects overwrite of existing file without prior read", async () => {- const fakeAccess = createFakeAccess({ "/workspace/foo.ts": "original" });-- const tool = defineWriteFileTool();-- const ctx = new ContextContainer();- ctx.set(SandboxKey, fakeAccess);- ctx.set(ReadFileStateKey, { byTarget: {} });-- await expect(- contextStorage.run(ctx, async () =>- tool.execute(- {- filePath: "/workspace/foo.ts",- content: "new content",- },- { getSandbox: () => fakeAccess.get() } as any,- ),- ),- ).rejects.toThrow(- "You must read file /workspace/foo.ts before overwriting it. Use the read_file tool first.",- );- });-- it("overwrites an existing file after prior read", async () => {- const files: Record<string, string> = { "/workspace/foo.ts": "original" };- const fakeAccess = createFakeAccess(files);-- const tool = defineWriteFileTool();-- const stamp = createReadFileStamp({- content: "original",- filePath: "/workspace/foo.ts",- });-- const ctx = new ContextContainer();- ctx.set(SandboxKey, fakeAccess);- ctx.set(ReadFileStateKey, {- byTarget: { "/workspace/foo.ts": stamp },- });-- const result = (await contextStorage.run(ctx, async () =>- tool.execute(- {- filePath: "/workspace/foo.ts",- content: "new content",- },- { getSandbox: () => fakeAccess.get() } as any,- ),- )) as { existed: boolean };-- expect(result.existed).toBe(true);- expect(files["/workspace/foo.ts"]).toBe("new content");- });-});diff --git a/packages/eve/test/file-tool-compaction.test.ts b/packages/eve/test/file-tool-compaction.test.tsindex d4f61e00a..9522afd07 100644--- a/packages/eve/test/file-tool-compaction.test.ts+++ b/packages/eve/test/file-tool-compaction.test.ts@@ -4,10 +4,10 @@ import { stubSpawnProcess } from "./_helpers/sandbox-session-stub.js";import { ContextContainer, contextStorage } from "../src/context/container.js";import { SandboxKey } from "../src/context/keys.js";-import { executeReadFileOnSandbox } from "../src/execution/sandbox/read-file-tool.js";+import { executeReadFileOnSandbox } from "../src/execution/sandbox/read-file.js";import type { SandboxAccess } from "../src/sandbox/state.js";import type { SandboxSession } from "../src/shared/sandbox-session.js";-import { executeWriteFileOnSandbox } from "../src/execution/sandbox/write-file-tool.js";+import { executeWriteFileOnSandbox } from "../src/execution/sandbox/write-file.js";import { ReadFileStateKey } from "../src/execution/tools/file-state.js";import { preserveFrameworkStateOnCompaction } from "../src/execution/compaction.js";diff --git a/packages/eve/test/read-file-tool.test.ts b/packages/eve/test/read-file-tool.test.tsindex e5f536d44..93f623da5 100644--- a/packages/eve/test/read-file-tool.test.ts+++ b/packages/eve/test/read-file-tool.test.ts@@ -4,8 +4,8 @@ import { stubSpawnProcess } from "./_helpers/sandbox-session-stub.js";import { ContextContainer, contextStorage } from "../src/context/container.js";import { SandboxKey } from "../src/context/keys.js";-import type { ReadFileResult } from "../src/execution/sandbox/read-file-tool.js";-import { executeReadFileOnSandbox } from "../src/execution/sandbox/read-file-tool.js";+import type { ReadFileResult } from "../src/execution/sandbox/read-file.js";+import { executeReadFileOnSandbox } from "../src/execution/sandbox/read-file.js";import type { SandboxAccess } from "../src/sandbox/state.js";import type { SandboxSession } from "../src/shared/sandbox-session.js";import { ReadFileStateKey } from "../src/execution/tools/file-state.js";diff --git a/packages/eve/test/resolve-agent.test.ts b/packages/eve/test/resolve-agent.test.tsindex 0f8e570da..3cd35ab21 100644--- a/packages/eve/test/resolve-agent.test.ts+++ b/packages/eve/test/resolve-agent.test.ts@@ -3,9 +3,9 @@ import { describe, expect, it } from "vitest";import { z } from "#compiled/zod/index.js";import { compileFromMemory } from "../src/compiler/compile-from-memory.js";-import { defineTool } from "../src/public/definitions/tool.js";+import { defineTool } from "../src/tools/definition.js";import { ResolveAgentError, resolveAgent } from "../src/runtime/resolve-agent.js";-import { serializeInputSchema } from "../src/shared/tool-schema.js";+import { serializeInputSchema } from "../src/tools/schema.js";describe("resolveAgent", () => {it("hydrates the effective compiled graph and reattaches tool execution", async () => {diff --git a/packages/eve/test/runtime-agent-graph.test.ts b/packages/eve/test/runtime-agent-graph.test.tsindex 0d72522ac..966c7c883 100644--- a/packages/eve/test/runtime-agent-graph.test.ts+++ b/packages/eve/test/runtime-agent-graph.test.ts@@ -1,7 +1,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { compileFromMemory } from "../src/compiler/compile-from-memory.js";-import { disableTool } from "../src/public/definitions/tool.js";+import { disableTool } from "../src/tools/definition.js";import { resolveRuntimeAgentGraph } from "../src/runtime/resolve-agent-graph.js";describe("resolveRuntimeAgentGraph", () => {diff --git a/packages/eve/test/runtime-subagent-registry.test.ts b/packages/eve/test/runtime-subagent-registry.test.tsindex 7a64542e3..3edaf5c1f 100644--- a/packages/eve/test/runtime-subagent-registry.test.ts+++ b/packages/eve/test/runtime-subagent-registry.test.ts@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";import { RuntimeRegistryError } from "../src/internal/runtime-registry.js";import { createRuntimeSubagentRegistry } from "../src/runtime/subagents/registry.js";-import { PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA } from "../src/shared/agent-tool.js";+import { PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA } from "../src/tools/framework/agent-contract.js";import type { ResolvedRuntimeSubagentNode } from "../src/runtime/types.js";const SUBAGENT_TOOL_INPUT_SCHEMA = {diff --git a/packages/eve/test/runtime-tool-registry.test.ts b/packages/eve/test/runtime-tool-registry.test.tsindex fda15ead1..8e9a03c66 100644--- a/packages/eve/test/runtime-tool-registry.test.ts+++ b/packages/eve/test/runtime-tool-registry.test.ts@@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest";import { RuntimeRegistryError } from "../src/internal/runtime-registry.js";import { createRuntimeToolRegistry } from "../src/runtime/tools/registry.js";import type { ResolvedToolDefinition } from "../src/runtime/types.js";-import { toInputSchema } from "../src/shared/tool-schema.js";+import { toInputSchema } from "../src/tools/schema.js";describe("createRuntimeToolRegistry", () => {it("lowers authored tool schemas into serializable runtime descriptors", async () => {diff --git a/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.ts b/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.tsindex ef9722b0f..53dd38c92 100644--- a/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.ts+++ b/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.ts@@ -788,9 +788,9 @@ describe("app runtime dependency tracing", () => {)).join("\n");- expect(serverModuleSource).not.toContain("../execution/sandbox/bash-tool.js");+ expect(serverModuleSource).not.toContain("../execution/sandbox/bash.js");expect(serverModuleSource).not.toContain("../execution/skills/activate.js");- expect(serverModuleSource).not.toContain("../execution/web-fetch/tool.js");+ expect(serverModuleSource).not.toContain("../execution/web-fetch/execute.js");expect(functionEntries.some((entry) => entry.includes("node_modules/esbuild"))).toBe(false);expect(functionEntries.some((entry) => entry.includes("node_modules/.nf3/esbuild"))).toBe(false,diff --git a/packages/eve/test/write-file-tool.test.ts b/packages/eve/test/write-file-tool.test.tsindex 0e0968b6d..3a9cb1d37 100644--- a/packages/eve/test/write-file-tool.test.ts+++ b/packages/eve/test/write-file-tool.test.ts@@ -4,11 +4,11 @@ import { stubSpawnProcess } from "./_helpers/sandbox-session-stub.js";import { ContextContainer, contextStorage } from "../src/context/container.js";import { SandboxKey } from "../src/context/keys.js";-import { executeReadFileOnSandbox } from "../src/execution/sandbox/read-file-tool.js";+import { executeReadFileOnSandbox } from "../src/execution/sandbox/read-file.js";import type { SandboxAccess } from "../src/sandbox/state.js";import type { SandboxSession } from "../src/shared/sandbox-session.js";-import type { WriteFileResult } from "../src/execution/sandbox/write-file-tool.js";-import { executeWriteFileOnSandbox } from "../src/execution/sandbox/write-file-tool.js";+import type { WriteFileResult } from "../src/execution/sandbox/write-file.js";+import { executeWriteFileOnSandbox } from "../src/execution/sandbox/write-file.js";import { createReadFileStamp, ReadFileStateKey } from "../src/execution/tools/file-state.js";const HOME_PROBE_COMMAND = `printf '%s\\n' "$HOME"`;diff --git a/scripts/extension-contracts/configuration.mjs b/scripts/extension-contracts/configuration.mjsindex 00dd0890f..d9acda5e2 100644--- a/scripts/extension-contracts/configuration.mjs+++ b/scripts/extension-contracts/configuration.mjs@@ -21,7 +21,14 @@ export const PUBLIC_SURFACES = [{ path: "src/public/channels/index.ts", capabilities: ["channel"] },{ path: "src/public/schedules/index.ts", capabilities: ["schedule"] },{ path: "src/public/index.ts", capabilities: ["subagent"] },- { path: "src/public/tools/index.ts", capabilities: ["tool", "dynamicTool"] },+ {+ paths: [+ "src/public/tools/index.ts",+ "src/public/tools/workflow.ts",+ "src/public/tools/web-search.ts",+ ],+ capabilities: ["tool", "dynamicTool"],+ },{ path: "src/public/connections/index.ts", capabilities: ["connection"] },{ path: "src/public/hooks/index.ts", capabilities: ["hook"] },{ path: "src/public/skills/index.ts", capabilities: ["skill", "dynamicSkill"] },@@ -32,6 +39,10 @@ export const PUBLIC_SURFACES = [{ path: "src/public/context/index.ts", capabilities: ["state"] },];+export function publicSurfacePaths(surface) {+ return surface.paths ?? [surface.path];+}+export function toPosix(path) {return sep === "/" ? path : path.split(sep).join("/");}@@ -351,8 +362,14 @@ export async function validateCapabilityConfiguration(configuration) {}for (const surface of PUBLIC_SURFACES) {- const publicSource = await readFile(join(EVE_ROOT, surface.path), "utf8");- const publicNames = collectExportNames(publicSource, { valuesOnly: true });+ const paths = publicSurfacePaths(surface);+ const publicNames = new Set();+ for (const path of paths) {+ const publicSource = await readFile(join(EVE_ROOT, path), "utf8");+ for (const name of collectExportNames(publicSource, { valuesOnly: true })) {+ publicNames.add(name);+ }+ }const contractNames = new Set();for (const capability of surface.capabilities) {const contractSource = await readFile(join(ENTRYPOINT_ROOT, `${capability}.ts`), "utf8");@@ -370,7 +387,7 @@ export async function validateCapabilityConfiguration(configuration) {.filter(Boolean).join("; ");issues.push({- file: toPosix(relative(REPO_ROOT, join(EVE_ROOT, surface.path))),+ file: toPosix(relative(REPO_ROOT, join(EVE_ROOT, paths[0]))),message: `Capability contract roots are incomplete (${details}). Assign every public authoring value to one of: ${surface.capabilities.join(", ")}.`,});}diff --git a/scripts/extension-contracts/reports.mjs b/scripts/extension-contracts/reports.mjsindex 16f1f27f0..88b224d1d 100644--- a/scripts/extension-contracts/reports.mjs+++ b/scripts/extension-contracts/reports.mjs@@ -13,6 +13,7 @@ import {REPORT_ROOT,REPO_ROOT,collectExportNames,+ publicSurfacePaths,toPosix,} from "./configuration.mjs";import { collectReportDeclarationNames } from "./compatibility.mjs";@@ -281,9 +282,16 @@ export async function checkCapabilityReports(configuration, update) {try {const reports = await generateCapabilityReports(configuration);for (const surface of PUBLIC_SURFACES) {- const publicSource = await readFile(join(EVE_ROOT, surface.path), "utf8");- const publicNames = collectExportNames(publicSource);- const publicValues = collectExportNames(publicSource, { valuesOnly: true });+ const paths = publicSurfacePaths(surface);+ const publicNames = new Set();+ const publicValues = new Set();+ for (const path of paths) {+ const publicSource = await readFile(join(EVE_ROOT, path), "utf8");+ for (const name of collectExportNames(publicSource)) publicNames.add(name);+ for (const name of collectExportNames(publicSource, { valuesOnly: true })) {+ publicValues.add(name);+ }+ }const tracedNames = new Set();for (const capability of surface.capabilities) {const report = reports.get(capability);@@ -295,7 +303,7 @@ export async function checkCapabilityReports(configuration, update) {.sort();if (missingTypes.length > 0) {issues.push({- file: toPosix(relative(REPO_ROOT, join(EVE_ROOT, surface.path))),+ file: toPosix(relative(REPO_ROOT, join(EVE_ROOT, paths[0]))),message: `Public extension types are not reachable from the ${surface.capabilities.join("/")} authoring roots: ${missingTypes.join(", ")}. Add only these standalone types to the appropriate capability entrypoint.`,});}diff --git a/scripts/guard-invariants-baseline.json b/scripts/guard-invariants-baseline.jsonindex 7ce44b66d..570b8be79 100644--- a/scripts/guard-invariants-baseline.json+++ b/scripts/guard-invariants-baseline.json@@ -31,20 +31,10 @@"packages/eve/src/internal/nitro/host/dev-authored-source-watcher.scenario.test.ts": 2,"packages/eve/src/internal/nitro/host/schedule-task-routes.test.ts": 1,"packages/eve/src/internal/nitro/routes/runtime-artifacts.test.ts": 1,- "packages/eve/src/public/tools/define-bash-tool.ts": 1,- "packages/eve/src/public/tools/define-glob-tool.ts": 1,- "packages/eve/src/public/tools/define-grep-tool.ts": 1,- "packages/eve/src/public/tools/define-read-file-tool.ts": 1,- "packages/eve/src/public/tools/define-write-file-tool.ts": 1,"packages/eve/src/runtime/agent/bootstrap-model-utils.ts": 3,"packages/eve/src/runtime/agent/mock-model-adapter.test.ts": 1,"packages/eve/src/runtime/agent/mock-model-adapter.ts": 1,- "packages/eve/src/runtime/resolve-sandbox.ts": 1,- "packages/eve/test/define-bash-tool.test.ts": 1,- "packages/eve/test/define-glob-tool.test.ts": 1,- "packages/eve/test/define-grep-tool.test.ts": 1,- "packages/eve/test/define-read-file-tool.test.ts": 1,- "packages/eve/test/define-write-file-tool.test.ts": 1+ "packages/eve/src/runtime/resolve-sandbox.ts": 1},"rule25_installRuntimeArtifactsAllowlist": ["packages/eve/src/internal/application/compiled-artifacts.ts",