Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): sources - compile one canonical graph (#2516)

Andrew Barbab3cf8ee10259
diff --git a/.changeset/canonical-agent-sources.md b/.changeset/canonical-agent-sources.md
new file mode 100644
index 000000000..065c201a7
--- /dev/null
+++ b/.changeset/canonical-agent-sources.md
@@ -0,0 +1,5 @@
+---
+"eve": minor
+---
+
+eve now compiles framework defaults, authored files, extensions, overrides, and in-memory modules through one authoritative source graph, with replaceable default config, sandbox, home, health, and inspection routes plus agent-info v3. Built-in tool definitions move from `eve/tools/defaults` to individual `eve/tools/<name>` subpaths.
diff --git a/docs/agent-config.md b/docs/agent-config.md
index f6c593e38..614e4a5f0 100644
--- a/docs/agent-config.md
+++ b/docs/agent-config.md
@@ -21,8 +21,7 @@ For a static AI Gateway model ID, you can make the same source change from the
project root with `eve set --model anthropic/claude-opus-4.8` or from the local
dev TUI with `/model anthropic/claude-opus-4.8`.
-The root `agent.ts` can be omitted when no runtime config is needed. In that case, eve defaults
-to `zai/glm-5.2`. GLM 5.2 does not support image input; choose a
+The root `agent.ts` can be omitted when no runtime config is needed. eve then selects its default `agent.ts` source at the same slot, configured with `zai/glm-5.2`; authoring the file replaces that source. GLM 5.2 does not support image input; choose a
vision-capable model or [route image inputs to Gemini
Flash](./guides/dynamic-capabilities#route-image-inputs-to-a-vision-model).
When `agent.ts` is present, `model` is required.
diff --git a/docs/channels/eve.mdx b/docs/channels/eve.mdx
index 9959f6849..dd67da68e 100644
--- a/docs/channels/eve.mdx
+++ b/docs/channels/eve.mdx
@@ -3,7 +3,7 @@ title: "eve"
description: "The default HTTP API for an agent, covering session routes, auth, and customization."
---
-The eve channel is the framework's default HTTP API. It's what the terminal UI, [`useEveAgent`](../guides/frontend/overview), `curl`, and any SDK client talk to when they start sessions, send messages, and stream events. `eveChannel()` mounts the canonical session routes under `/eve/v1/session*`, and they are enabled by default even when `agent/channels/eve.ts` does not exist.
+The eve channel is the framework's default HTTP API. It's what the terminal UI, [`useEveAgent`](../guides/frontend/overview), `curl`, and any SDK client talk to when they start sessions, send messages, and stream events. The selected `channels/eve.ts` source owns the complete `/eve/v1` surface, including health, inspection, callbacks, task input, and session routes. eve supplies that source when `agent/channels/eve.ts` does not exist.
Every running eve app exposes its own API. `eve.dev` publishes framework documentation; it is not a shared API, authorization server, MCP server, or A2A server. Each deployment supplies its own host and authentication policy.
@@ -20,7 +20,7 @@ export default eveChannel({
## Routes
-The application exposes a health route plus eve channel routes that inspect the agent, create sessions, send follow-ups, control sessions, and stream events:
+The default eve channel inspects the agent, creates sessions, accepts callbacks and task input, controls sessions, and streams events. Its public routes include:
- `GET /eve/v1/health` (check whether the application is reachable)
- `GET /eve/v1/info` (inspect the agent)
@@ -34,6 +34,8 @@ The application exposes a health route plus eve channel routes that inspect the
The session routes use only durable session IDs. Create a session explicitly, then put its returned ID in every follow-up, control, and stream path.
+`GET /eve/v1/health` is public and returns `{ ok: true, status: "ready", workflowId: string }`. `GET /eve/v1/info` uses the channel's auth policy and returns agent-info version 3. The TypeScript client validates both successful payloads: malformed health JSON throws `HealthResponseError`, malformed inspection JSON throws `AgentInfoResponseError`, and a non-success response from either route throws `ClientError`.
+
### Start and continue a session
Start a session with an initial message, then use the returned `sessionId` for every follow-up and control operation:
@@ -97,6 +99,20 @@ Post to `/eve/v1/session/:sessionId/compact` to summarize context without sendin
Post to `/eve/v1/session/:sessionId/reset` to terminally retire that session. Reset never replaces the ID automatically; create a new session explicitly for a fresh conversation. See [Compact, clear, and reset](../concepts/sessions-runs-and-streaming#compact-clear-and-reset).
+## Replace or disable the defaults
+
+An authored `agent/channels/eve.ts` replaces the complete default eve channel. An `eveChannel(...)` replacement keeps the standard route set with your options; a custom `defineChannel(...)` replacement exposes only the routes you declare. Health, inspection, and callbacks do not reappear through a hidden host fallback.
+
+Disable the complete surface by exporting `disableRoute()` at that slot:
+
+```ts title="agent/channels/eve.ts"
+import { disableRoute } from "eve/channels";
+
+export default disableRoute();
+```
+
+The default home page is a separate `channels/home.ts` source that serves `GET /` and `HEAD /`. Author `agent/channels/home.ts` to replace it or export `disableRoute()` there to remove it without affecting `/eve/v1`.
+
## CORS
The eve channel leaves CORS untouched by default. Pass `cors: true` to enable
@@ -129,7 +145,7 @@ The `auth` option decides who can call `/eve/v1/info` and the session routes. Th
Neither admits browser users or external clients in production. For a public app, wire the channel to your own auth (Clerk, Auth.js, your own OIDC/JWT verification, an API-key verifier, or any custom `AuthFn`). Vercel OIDC is optional; use it only when Vercel-issued deployment tokens are part of your trust model.
-`eve init` scaffolds an `agent/channels/eve.ts` with a production placeholder so you replace it before going live. The generated channel checks Vercel OIDC before falling back to localhost access, and includes `placeholderAuth()`, which returns a setup-focused 401 in production until you swap it for real auth. Delete the file and eve falls back to `[vercelOidc(), localDev(), placeholderAuth()]`, which rejects all production traffic.
+`eve init` scaffolds an `agent/channels/eve.ts` with a production placeholder so you replace it before going live. The generated channel checks Vercel OIDC before falling back to localhost access, and includes `placeholderAuth()`, which returns a setup-focused 401 in production until you swap it for real auth. Delete the file and eve selects its default channel source with `[vercelOidc(), localDev(), placeholderAuth()]`, which rejects all production traffic.
For the full auth model and helper list, see [Auth & route protection](../guides/auth-and-route-protection).
diff --git a/docs/channels/overview.mdx b/docs/channels/overview.mdx
index 782879d0c..5280d9c55 100644
--- a/docs/channels/overview.mdx
+++ b/docs/channels/overview.mdx
@@ -51,7 +51,7 @@ Install a channel from the registry with `eve add channel/<name>`, such as `eve
## The eve HTTP channel (default)
-The eve channel is the framework's default HTTP session API, the routes the terminal UI, [`useEveAgent`](../guides/frontend/overview), and `curl` all talk to. It is enabled by default, even with no `agent/channels/eve.ts` file. Add that file only to override the defaults, most often the route auth policy. See [HTTP channel](./eve) for routes, auth, and customization.
+The eve channel is the framework's default HTTP session API, the routes the terminal UI, [`useEveAgent`](../guides/frontend/overview), and `curl` all talk to. Its selected `channels/eve.ts` source owns health, inspection, callbacks, task input, and the session protocol as one replaceable surface. eve supplies the source when no `agent/channels/eve.ts` file exists; author that file to replace it, most often to change route auth. See [HTTP channel](./eve) for routes, auth, replacement, and disablement.
## Custom channels
diff --git a/docs/concepts/built-in-tools.md b/docs/concepts/built-in-tools.md
index 6e79cdf72..f24132b1b 100644
--- a/docs/concepts/built-in-tools.md
+++ b/docs/concepts/built-in-tools.md
@@ -3,7 +3,7 @@ title: "Built-in Tools"
description: "The default and opt-in tools eve provides, including Workflow, glob, grep, and sleep."
---
-eve provides a default tool set for every agent and additional framework tools you can add with one file. Use this page to review what the model can call, opt into more capabilities, or override and disable defaults. For custom tools, see [Tools](../tools).
+eve provides a default tool set for every agent and additional tools you can add with one file. Each default occupies the same `agent/tools/<name>.ts` slot you would author yourself, so an authored definition replaces it and `disableTool()` removes it. Use this page to review what the model can call, opt into more capabilities, or override and disable defaults. For custom tools, see [Tools](../tools).
## Default tools
@@ -30,7 +30,7 @@ Notes:
- **`agent`** is available only in the root session. Its child uses the root's instructions, tools, connections, and sandbox, but starts with fresh conversation history and fresh [state](./state). The child receives neither `agent` nor `Workflow`; declared subagents do not receive the built-in `agent` either. See [Subagents](../subagents).
- **`load_skill`** only pulls instructions into context. It adds no new execution surface, because behavior still comes from the tools the agent already has.
-- **`connection_search`** surfaces a connection's tools by their qualified name (e.g. `linear__list_issues`), which the model can then call directly. It's registered only when the agent has connections.
+- **`connection_search`** surfaces a connection's tools by their qualified name (e.g. `linear__list_issues`), which the model can then call directly. The model sees it only when the agent has connections.
- **`web_search`** has no local executor; the provider runs it. AI Gateway models use Exa by default. To use Parallel instead, export `webSearch({ provider: "parallel" })` from `agent/tools/web_search.ts`. Direct provider models continue to use their native search implementation. To supply your own implementation, override it with `defineTool()`.
- **`web_fetch`** follows up to ten redirects, rechecking every destination for SSRF safety. Non-success HTTP responses return a plain-text failure result with the response body when available instead of failing the tool call.
@@ -71,7 +71,7 @@ Author a tool at the same slug and it takes over the built-in of that name. The
```ts title="agent/tools/write_file.ts"
import { defineTool } from "eve/tools";
-import { writeFile } from "eve/tools/defaults";
+import { writeFile } from "eve/tools/write_file";
export default defineTool({
...writeFile, // keep the default description, schema, and executor
@@ -82,7 +82,20 @@ export default defineTool({
});
```
-Framework tool definitions are importable from `eve/tools/defaults` (`bash`, `readFile`, `writeFile`, `glob`, `grep`, `webFetch`, `todo`, `loadSkill`), so you can spread, wrap, or patch them. Importing a definition does not add it to an agent; export it from the corresponding `agent/tools/*.ts` file. Skip the spread and your replacement owns its own context. A fresh `defineTool` for `todo` won't inherit the framework's durable state key.
+Import each reusable definition from its own subpath:
+
+| Definition | Import | Registered by default |
+| ----------- | ---------------------- | --------------------- |
+| `bash` | `eve/tools/bash` | Yes |
+| `readFile` | `eve/tools/read_file` | Yes |
+| `writeFile` | `eve/tools/write_file` | Yes |
+| `todo` | `eve/tools/todo` | Yes |
+| `webFetch` | `eve/tools/web_fetch` | Yes |
+| `loadSkill` | `eve/tools/load_skill` | Yes |
+| `glob` | `eve/tools/glob` | No |
+| `grep` | `eve/tools/grep` | No |
+
+Importing a definition does not add it to an agent; export it from the corresponding `agent/tools/*.ts` file. Skip the spread and your replacement owns its own context. A fresh `defineTool` for `todo` does not inherit the default's durable state key.
Provider-managed web search has a dedicated configuration helper instead of an executable default:
@@ -112,7 +125,7 @@ If the filename matches no known framework tool, resolution fails instead of sil
Three moves shape the harness. The right one depends on whether the model should keep the built-in capability.
-- **Override** when you want the same capability with different behavior. Spread the default from `eve/tools/defaults` and wrap it (logging, an extra guard, a different backend), and the model still sees a tool by that name. Spreading keeps the default's description, schema, and any framework state, such as the `todo` tool's durable state key. Drop the spread and your replacement owns its own context, losing that wiring.
+- **Override** when you want the same capability with different behavior. Import its definition from the matching `eve/tools/<name>` subpath and wrap it (logging, an extra guard, or a different backend), and the model still sees a tool by that name. Spreading keeps the default's description, schema, and any framework state, such as the `todo` tool's durable state key. Drop the spread and your replacement owns its own context, losing that wiring.
- **Disable** when the model should not have the capability at all. A `disableTool()` sentinel removes the built-in, and the model never sees it. Reach for this to lock down `bash` or `web_fetch` in an agent that should not run shell commands or fetch arbitrary URLs.
- **Author a new tool** when you want a capability the harness does not ship. Give it a fresh slug under `agent/tools/` and it joins the built-ins instead of replacing one. See [Tools](../tools) for the authoring model.
diff --git a/docs/concepts/sessions-runs-and-streaming.md b/docs/concepts/sessions-runs-and-streaming.md
index eeb6c3705..c16b95de1 100644
--- a/docs/concepts/sessions-runs-and-streaming.md
+++ b/docs/concepts/sessions-runs-and-streaming.md
@@ -244,7 +244,9 @@ Start with the [Client SDK](../guides/client/overview) guide. It covers basic us
## Inspect the agent over HTTP
-`GET /eve/v1/info` returns a JSON inspection snapshot for the running agent: model, static instructions, authored and framework tools, skills, channels, schedules, subagents, sandbox, connections, hooks, workflow, and workspace metadata. Static instructions are an ordered array whose entries expose `content` and `role`; dynamic resolver output is runtime context and is not included. The route uses the resolved `eveChannel()` auth when `agent/channels/eve.ts` authors one; otherwise it falls back to the framework default of Vercel OIDC plus local development access.
+`GET /eve/v1/info` returns agent-info version 3, a JSON inspection snapshot of the effective compiled agent. It reports the selected config; active tools, instructions, skills, channels, schedules, sandbox, connections, hooks, and instrumentation with explicit source ownership; dynamic resolvers separately from their session-specific output; local and remote agents in separate collections; prepared built-in effects; and shadowed or disabled source diagnostics. Channel routes appear in the same effective order used by the HTTP host. Static instructions remain an ordered array whose entries expose `content` and `role`.
+
+The info route belongs to the selected `channels/eve.ts` source and uses its resolved auth policy. Without an authored replacement, eve selects the default channel source with Vercel OIDC, local development access, and the production placeholder. Replacing or disabling that source replaces or removes the info route too; no native fallback serves it.
```bash
curl http://127.0.0.1:2000/eve/v1/info
diff --git a/docs/extensions.md b/docs/extensions.md
index 7d1343abe..950a9101c 100644
--- a/docs/extensions.md
+++ b/docs/extensions.md
@@ -273,7 +273,7 @@ Production `eve build` expects the extension distribution to exist already. Keep
### Override a contribution
-Use a directory mount to replace or remove an extension contribution. Put the mount declaration in `extension.ts` and add overrides beside it:
+Use a directory mount to keep overrides beside the mount declaration. Put the declaration in `extension.ts` and add overrides beside it:
```
agent/extensions/crm/
@@ -307,7 +307,7 @@ export default disableTool();
Hooks and instruction fragments are additive, so they cannot be replaced. To replace a dynamic tool, use a dynamic definition in the same slot; dynamic tools win over same-named static tools at runtime. `disableTool()` removes either kind.
-The `crm__` prefix is reserved for this directory mount. A consumer cannot override the extension from `agent/tools/`, `agent/connections/`, `agent/subagents/`, or another agent-root slot.
+You can also place an override in the corresponding agent-root slot by using the final qualified name. For example, `agent/tools/crm__search.ts` replaces `tools/search.ts` from the extension package or its directory override. Application sources have the highest precedence, so an agent-root override wins when both forms exist.
### Use an extension tool result in a hook
diff --git a/docs/getting-started.mdx b/docs/getting-started.mdx
index 87a322b8b..a6ea168d9 100644
--- a/docs/getting-started.mdx
+++ b/docs/getting-started.mdx
@@ -71,7 +71,7 @@ The root agent uses its `package.json` `name`, or its app directory name if none
### Recommended layout
-A minimal agent needs `instructions.md`; `agent.ts` is optional when the defaults are sufficient. Add other slots as the agent needs them:
+A minimal agent needs `instructions.md`; `agent.ts` is optional when the default config is sufficient. Framework defaults occupy ordinary agent slots, so authoring the same path replaces the default before eve compiles the agent. Add other slots as the agent needs them:
```text
my-agent/
diff --git a/docs/guides/auth-and-route-protection.md b/docs/guides/auth-and-route-protection.md
index ee7ebe28a..93ef3c90a 100644
--- a/docs/guides/auth-and-route-protection.md
+++ b/docs/guides/auth-and-route-protection.md
@@ -21,7 +21,7 @@ The route-auth policy lives on the HTTP channel factory (`agent/channels/eve.ts`
These routes are protected by the channel's auth policy. eve fails closed by default: production traffic is rejected unless you configure an authenticator that accepts it, and anonymous access requires an explicit `none()`.
-`GET /eve/v1/health` is always public and skips the walk entirely, so load balancers and uptime monitors can probe it without credentials.
+The health route created by `eveChannel()` is public and skips the walk entirely, so load balancers and uptime monitors can probe it without credentials. Replacing `agent/channels/eve.ts` with a custom `defineChannel(...)` or disabling that slot also replaces or removes the health route.
```ts title="agent/channels/eve.ts"
import { eveChannel } from "eve/channels/eve";
@@ -215,7 +215,7 @@ export default eveChannel({
});
```
-In production, `placeholderAuth()` returns a structured `401` so a generated web chat app can say "auth isn't configured yet" instead of throwing an internal error. Replace it before a browser caller submits a production request: swap in your app's `AuthFn` or one of the shipped helpers. Delete the authored channel file entirely and eve falls back to the framework default `[vercelOidc(), localDev(), placeholderAuth()]`, which also rejects production traffic.
+In production, `placeholderAuth()` returns a structured `401` so a generated web chat app can say "auth isn't configured yet" instead of throwing an internal error. Replace it before a browser caller submits a production request: swap in your app's `AuthFn` or one of the shipped helpers. Delete the authored channel file entirely and eve selects the default channel source with `[vercelOidc(), localDev(), placeholderAuth()]`, which also rejects production traffic.
You do not have to keep `vercelOidc()` in the final policy. For a self-hosted app, an app-embedded frontend, or any deployment that uses a non-Vercel identity system, use `httpBasic()`, `jwtHmac()`, `jwtEcdsa()`, generic `oidc()`, or a custom `AuthFn` that maps your verified user/session/API key into a `SessionAuthContext`.
diff --git a/docs/guides/client/overview.mdx b/docs/guides/client/overview.mdx
index dd30b08ee..88148682f 100644
--- a/docs/guides/client/overview.mdx
+++ b/docs/guides/client/overview.mdx
@@ -30,17 +30,19 @@ const health = await client.health();
console.log(health.status, health.workflowId);
```
-Non-2xx responses throw `ClientError`, which carries the HTTP `status` and response `body`.
+The client requires the successful response to match `{ ok: true, status: "ready", workflowId: string }`. Non-2xx responses throw `ClientError`, which carries the HTTP `status` and response `body`; invalid JSON or a malformed successful payload throws `HealthResponseError`.
## Inspect an agent
-Use `info()` to inspect a development agent. The client parses and validates the complete response before returning it:
+Use `info()` to inspect an agent. The client requires the complete agent-info version 3 response before returning it:
```ts
const info = await client.info();
console.log(info.agent.name, info.agent.model.id);
```
+Version 3 separates active static definitions from dynamic resolvers, includes binding-backed source ownership and composition history, reports local and remote agents separately, and returns the exact compiled channel route order. A non-success response throws `ClientError`; invalid JSON, an earlier schema version, duplicate identities, inconsistent totals, or mismatched source provenance throws `AgentInfoResponseError`.
+
## Authentication
Pass `auth` when the [eve channel](../../channels/eve) route requires credentials:
diff --git a/docs/reference/typescript-api.md b/docs/reference/typescript-api.md
index 4c3e1a58c..b9546aec8 100644
--- a/docs/reference/typescript-api.md
+++ b/docs/reference/typescript-api.md
@@ -52,7 +52,7 @@ 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`/`POST`/`PUT`/`PATCH`/`DELETE`/`WS` from `eve/channels`, the approval policies `always`/`once`/`never` from `eve/tools/approval`, and the channel auth helpers `localDev`/`vercelOidc`/`placeholderAuth` from `eve/channels/auth`. To wrap a framework-provided tool, import its definition from `eve/tools/defaults` (`bash`, `readFile`, `writeFile`, `glob`, `grep`, `webFetch`, `todo`, `loadSkill`). `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.
+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.
`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,33 +70,33 @@ 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/defaults` | framework tool definitions as plain values |
-| `eve/tools/approval` | `always`, `once`, `never` |
-| `eve/tools/sleep` | opt-in durable `sleep` tool |
-| `eve/connections` | `defineMcpClientConnection`, `defineOpenAPIConnection` |
-| `eve/channels` | `defineChannel`, 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` |
+| 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`.
diff --git a/docs/sandbox.mdx b/docs/sandbox.mdx
index 2b0250fde..bd07944c5 100644
--- a/docs/sandbox.mdx
+++ b/docs/sandbox.mdx
@@ -5,7 +5,7 @@ description: "The agent's isolated bash environment, including built-in file too
The sandbox is the agent's isolated bash environment: a filesystem rooted at `/workspace` where it can run shell commands, execute scripts, and read or write files without ever touching your app runtime. Every eve agent has exactly one. The default `bash`, `read_file`, and `write_file` tools target it; you can also add the framework's `glob` and `grep` tools or access it from authored code.
-A working sandbox exists by default, with nothing to author. Override it only to add setup, seed files, pick a backend, or lock down the network.
+A working sandbox exists by default, with nothing to author. eve selects a framework-provided `defineSandbox({})` source for each local agent; `agent/sandbox.ts` or `agent/sandbox/sandbox.ts` replaces that source. Override it only to add setup, seed files, pick a backend, or lock down the network.
The default sandbox is not a substitute for configuring network policy, credentials, retention, deletion, or other controls your application requires.
diff --git a/docs/subagents/index.mdx b/docs/subagents/index.mdx
index 9f4681d8c..9d7e2cfd3 100644
--- a/docs/subagents/index.mdx
+++ b/docs/subagents/index.mdx
@@ -126,7 +126,7 @@ The root agent does not receive the extension's tools, skills, instructions, con
## The isolation boundary
-A declared subagent inherits nothing from the root's authored slots. Discovery treats its directory as its own agent root, so it has only the instructions, tools, connections, skills, sandbox, hooks, and nested subagents authored under `agent/subagents/<id>/`. An absent slot falls back to the framework default, not to the root's version.
+A declared subagent inherits nothing from the root's authored slots. Discovery treats its directory as its own agent root, so it has only the instructions, tools, connections, skills, sandbox, hooks, and nested subagents authored under `agent/subagents/<id>/`. For a slot with a framework default, eve selects that source when the subagent does not author a replacement; it never inherits the root's authored version.
| Slot | Root built-in `agent` tool | Declared subagent |
| ------------ | ----------------------------- | -------------------------------------- |
@@ -141,7 +141,7 @@ A declared subagent inherits nothing from the root's authored slots. Discovery t
| Channels | Root-only | Root-only |
| Schedules | Root-only | Root-only |
-For a declared subagent this means authoring or mounting anything the child needs. When two subagents need the same procedure, package the skill in a [workspace extension](./extensions#use-an-extension-in-a-workspace) and mount that extension in each subagent. Share typed helpers through `lib/`. The sandbox does not inherit from the parent; it falls back to the framework default unless the subagent authors `subagents/<id>/sandbox.ts` or seeds files via `subagents/<id>/sandbox/workspace/`.
+For a declared subagent this means authoring or mounting anything the child needs. When two subagents need the same procedure, package the skill in a [workspace extension](./extensions#use-an-extension-in-a-workspace) and mount that extension in each subagent. Share typed helpers through `lib/`. The sandbox does not inherit from the parent; eve selects the default sandbox source unless the subagent authors `subagents/<id>/sandbox.ts` or seeds files via `subagents/<id>/sandbox/workspace/`.
The root built-in `agent` tool is the exception. Its children share the root's sandbox and tools because they are copies of the same agent working on the same files.
diff --git a/e2e/fixtures/agent-compaction-regressions/agent/tools/perform-source-analysis.ts b/e2e/fixtures/agent-compaction-regressions/agent/tools/perform-source-analysis.ts
index 63b49a988..36ee31a50 100644
--- a/e2e/fixtures/agent-compaction-regressions/agent/tools/perform-source-analysis.ts
+++ b/e2e/fixtures/agent-compaction-regressions/agent/tools/perform-source-analysis.ts
@@ -1,6 +1,6 @@
import { defineState } from "eve/context";
import { defineTool } from "eve/tools";
-import { todo } from "eve/tools/defaults";
+import { todo } from "eve/tools/todo";
import { z } from "zod";
const completionMarker = "SOURCE_ANALYSIS_COMPLETE";
diff --git a/packages/eve/extension-contracts/compatibility/channel/v8.ts b/packages/eve/extension-contracts/compatibility/channel/v8.ts
new file mode 100644
index 000000000..f9d1a0872
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/channel/v8.ts
@@ -0,0 +1,20 @@
+import { defineChannel, POST } from "#public/channels/index.js";
+
+export default defineChannel({
+ state: { threadId: null as string | null },
+ metadata(state) {
+ return { threadId: state.threadId };
+ },
+ routes: [
+ POST("/input", async (_request, { from }) => {
+ await from("thread-1").respond([{ optionId: "approve", requestId: "approval-1" }], {
+ auth: null,
+ });
+ return new Response("ok");
+ }),
+ ],
+ async fetchFile(url) {
+ return url.startsWith("https://files.example.com/") ? Buffer.from("example") : null;
+ },
+ turnPolicy: "queue",
+});
diff --git a/packages/eve/extension-contracts/entrypoints/channel.ts b/packages/eve/extension-contracts/entrypoints/channel.ts
index dd9a5e823..a96385e13 100644
--- a/packages/eve/extension-contracts/entrypoints/channel.ts
+++ b/packages/eve/extension-contracts/entrypoints/channel.ts
@@ -1,11 +1,15 @@
export {
DELETE,
GET,
+ HEAD,
+ OPTIONS,
PATCH,
POST,
PUT,
WS,
createWebSocketUpgradeServer,
defineChannel,
+ disableRoute,
isChannel,
+ isDisabledRouteSentinel,
} from "../../src/public/channels/index.ts";
diff --git a/packages/eve/extension-contracts/reports/channel/v9.json b/packages/eve/extension-contracts/reports/channel/v9.json
new file mode 100644
index 000000000..74670799a
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/channel/v9.json
@@ -0,0 +1,21 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "channel",
+ "epoch": 9,
+ "sha256": "e350f08ba2c8482c7719952182f20c83fe2368914e668a55526ef1a342256247",
+ "exports": [
+ "DELETE",
+ "GET",
+ "HEAD",
+ "OPTIONS",
+ "PATCH",
+ "POST",
+ "PUT",
+ "WS",
+ "createWebSocketUpgradeServer",
+ "defineChannel",
+ "disableRoute",
+ "isChannel",
+ "isDisabledRouteSentinel"
+ ]
+}
diff --git a/packages/eve/package.json b/packages/eve/package.json
index 4b921a79d..85b52baac 100644
--- a/packages/eve/package.json
+++ b/packages/eve/package.json
@@ -111,10 +111,45 @@
"import": "./dist/src/public/tools/index.js",
"default": "./dist/src/public/tools/index.js"
},
- "./tools/defaults": {
- "types": "./dist/src/public/tools/defaults.d.ts",
- "import": "./dist/src/public/tools/defaults.js",
- "default": "./dist/src/public/tools/defaults.js"
+ "./tools/bash": {
+ "types": "./dist/src/public/tools/bash.d.ts",
+ "import": "./dist/src/public/tools/bash.js",
+ "default": "./dist/src/public/tools/bash.js"
+ },
+ "./tools/read_file": {
+ "types": "./dist/src/public/tools/read-file.d.ts",
+ "import": "./dist/src/public/tools/read-file.js",
+ "default": "./dist/src/public/tools/read-file.js"
+ },
+ "./tools/write_file": {
+ "types": "./dist/src/public/tools/write-file.d.ts",
+ "import": "./dist/src/public/tools/write-file.js",
+ "default": "./dist/src/public/tools/write-file.js"
+ },
+ "./tools/todo": {
+ "types": "./dist/src/public/tools/todo.d.ts",
+ "import": "./dist/src/public/tools/todo.js",
+ "default": "./dist/src/public/tools/todo.js"
+ },
+ "./tools/web_fetch": {
+ "types": "./dist/src/public/tools/web-fetch.d.ts",
+ "import": "./dist/src/public/tools/web-fetch.js",
+ "default": "./dist/src/public/tools/web-fetch.js"
+ },
+ "./tools/load_skill": {
+ "types": "./dist/src/public/tools/load-skill.d.ts",
+ "import": "./dist/src/public/tools/load-skill.js",
+ "default": "./dist/src/public/tools/load-skill.js"
+ },
+ "./tools/glob": {
+ "types": "./dist/src/public/tools/glob.d.ts",
+ "import": "./dist/src/public/tools/glob.js",
+ "default": "./dist/src/public/tools/glob.js"
+ },
+ "./tools/grep": {
+ "types": "./dist/src/public/tools/grep.d.ts",
+ "import": "./dist/src/public/tools/grep.js",
+ "default": "./dist/src/public/tools/grep.js"
},
"./models/openai": {
"types": "./dist/src/public/models/openai/index.d.ts",
@@ -196,6 +231,11 @@
"import": "./dist/src/public/context/index.js",
"default": "./dist/src/public/context/index.js"
},
+ "./internal/programmatic-source-loader": {
+ "types": "./dist/src/internal/programmatic-source-loader.d.ts",
+ "import": "./dist/src/internal/programmatic-source-loader.js",
+ "default": "./dist/src/internal/programmatic-source-loader.js"
+ },
"./extension": {
"types": "./dist/src/public/extension/index.d.ts",
"import": "./dist/src/public/extension/index.js",
diff --git a/packages/eve/src/acp/adapter.ts b/packages/eve/src/acp/adapter.ts
index 2dc2d388d..0c2769ff6 100644
--- a/packages/eve/src/acp/adapter.ts
+++ b/packages/eve/src/acp/adapter.ts
@@ -18,8 +18,8 @@ import {
import { Client, ClientError } from "#client/index.js";
import type { ClientOptions, SendTurnInput, SendTurnPayload } from "#client/types.js";
import type { HandleMessageStreamEvent } from "#protocol/message.js";
-import type { RuntimeActionRequest, RuntimeActionResult } from "#runtime/actions/types.js";
-import type { InputRequest, InputResponse } from "#runtime/input/types.js";
+import type { RuntimeActionRequest, RuntimeActionResult } from "#shared/action-types.js";
+import type { InputRequest, InputResponse } from "#shared/input.js";
const ANSWER_FIELD = "answer";
const ERROR_CODE_BUSY = -32_001;
diff --git a/packages/eve/src/runtime/governance/auth/http-basic.ts b/packages/eve/src/channel/auth/http-basic.ts
similarity index 98%
rename from packages/eve/src/runtime/governance/auth/http-basic.ts
rename to packages/eve/src/channel/auth/http-basic.ts
index d6cd2dce3..4f951a829 100644
--- a/packages/eve/src/runtime/governance/auth/http-basic.ts
+++ b/packages/eve/src/channel/auth/http-basic.ts
@@ -3,7 +3,7 @@ import { createHash, timingSafeEqual } from "node:crypto";
import type {
ResolvedHttpBasicAuthStrategy,
RouteStrategyAuthenticationResult,
-} from "#runtime/governance/auth/types.js";
+} from "#channel/auth/types.js";
/**
* Verifies one HTTP Basic credential against a resolved eve strategy.
diff --git a/packages/eve/src/runtime/governance/auth/jwt-ecdsa.ts b/packages/eve/src/channel/auth/jwt-ecdsa.ts
similarity index 96%
rename from packages/eve/src/runtime/governance/auth/jwt-ecdsa.ts
rename to packages/eve/src/channel/auth/jwt-ecdsa.ts
index 3b80c51af..cb19890c3 100644
--- a/packages/eve/src/runtime/governance/auth/jwt-ecdsa.ts
+++ b/packages/eve/src/channel/auth/jwt-ecdsa.ts
@@ -3,11 +3,11 @@ import { importJWK, importSPKI, jwtVerify } from "#compiled/jose/index.js";
import {
areTokenClaimMatchersSatisfied,
createJwtAuthenticatedCallerPrincipal,
-} from "#runtime/governance/auth/token-claims.js";
+} from "#channel/auth/token-claims.js";
import type {
ResolvedJwtEcdsaAuthStrategy,
RouteStrategyAuthenticationResult,
-} from "#runtime/governance/auth/types.js";
+} from "#channel/auth/types.js";
type ImportedJwtPublicKey =
| Awaited<ReturnType<typeof importJWK>>
diff --git a/packages/eve/src/runtime/governance/auth/jwt-hmac.ts b/packages/eve/src/channel/auth/jwt-hmac.ts
similarity index 93%
rename from packages/eve/src/runtime/governance/auth/jwt-hmac.ts
rename to packages/eve/src/channel/auth/jwt-hmac.ts
index b430986e2..0f90043eb 100644
--- a/packages/eve/src/runtime/governance/auth/jwt-hmac.ts
+++ b/packages/eve/src/channel/auth/jwt-hmac.ts
@@ -5,11 +5,11 @@ import { jwtVerify } from "#compiled/jose/index.js";
import {
areTokenClaimMatchersSatisfied,
createJwtAuthenticatedCallerPrincipal,
-} from "#runtime/governance/auth/token-claims.js";
+} from "#channel/auth/token-claims.js";
import type {
ResolvedJwtHmacAuthStrategy,
RouteStrategyAuthenticationResult,
-} from "#runtime/governance/auth/types.js";
+} from "#channel/auth/types.js";
/**
* Verifies one bearer token against a resolved HMAC JWT strategy.
diff --git a/packages/eve/src/runtime/governance/auth/oidc.ts b/packages/eve/src/channel/auth/oidc.ts
similarity index 98%
rename from packages/eve/src/runtime/governance/auth/oidc.ts
rename to packages/eve/src/channel/auth/oidc.ts
index 1ddc6e4aa..ea908758e 100644
--- a/packages/eve/src/runtime/governance/auth/oidc.ts
+++ b/packages/eve/src/channel/auth/oidc.ts
@@ -5,11 +5,11 @@ import { z } from "#compiled/zod/index.js";
import {
areTokenClaimMatchersSatisfied,
createJwtAuthenticatedCallerPrincipal,
-} from "#runtime/governance/auth/token-claims.js";
+} from "#channel/auth/token-claims.js";
import type {
ResolvedOidcAuthStrategy,
RouteStrategyAuthenticationResult,
-} from "#runtime/governance/auth/types.js";
+} from "#channel/auth/types.js";
const oidcDiscoveryDocumentSchema = z
.object({
diff --git a/packages/eve/src/runtime/governance/auth/token-claims.ts b/packages/eve/src/channel/auth/token-claims.ts
similarity index 98%
rename from packages/eve/src/runtime/governance/auth/token-claims.ts
rename to packages/eve/src/channel/auth/token-claims.ts
index cdb5263b3..2d3278a81 100644
--- a/packages/eve/src/runtime/governance/auth/token-claims.ts
+++ b/packages/eve/src/channel/auth/token-claims.ts
@@ -4,7 +4,7 @@ import type {
AuthenticatedCallerPrincipal,
ResolvedTokenClaimMatchers,
RouteAuthAttributes,
-} from "#runtime/governance/auth/types.js";
+} from "#channel/auth/types.js";
const STANDARD_PROJECTED_CLAIM_KEYS = new Set(["aud", "exp", "iat", "iss", "jti", "nbf", "sub"]);
diff --git a/packages/eve/src/runtime/governance/auth/types.ts b/packages/eve/src/channel/auth/types.ts
similarity index 99%
rename from packages/eve/src/runtime/governance/auth/types.ts
rename to packages/eve/src/channel/auth/types.ts
index 5867e3178..eefc191b1 100644
--- a/packages/eve/src/runtime/governance/auth/types.ts
+++ b/packages/eve/src/channel/auth/types.ts
@@ -3,7 +3,7 @@ import type {
RuntimeSessionAuthContext,
RuntimeSessionAuthenticator,
RuntimeSessionPrincipalType,
-} from "#runtime/sessions/auth.js";
+} from "#shared/session-auth.js";
/**
* Shared serializable token-claim projection used by auth verifiers.
diff --git a/packages/eve/src/runtime/governance/auth/vercel-oidc-project.ts b/packages/eve/src/channel/auth/vercel-oidc-project.ts
similarity index 95%
rename from packages/eve/src/runtime/governance/auth/vercel-oidc-project.ts
rename to packages/eve/src/channel/auth/vercel-oidc-project.ts
index 87885653f..e9f2b58a0 100644
--- a/packages/eve/src/runtime/governance/auth/vercel-oidc-project.ts
+++ b/packages/eve/src/channel/auth/vercel-oidc-project.ts
@@ -1,4 +1,4 @@
-import type { CurrentVercelProject } from "#runtime/governance/auth/types.js";
+import type { CurrentVercelProject } from "#channel/auth/types.js";
type VercelOidcProjectResolver = () =>
| CurrentVercelProject
diff --git a/packages/eve/src/channel/channel-operations.test.ts b/packages/eve/src/channel/channel-operations.test.ts
index 6befd4505..104fdbb80 100644
--- a/packages/eve/src/channel/channel-operations.test.ts
+++ b/packages/eve/src/channel/channel-operations.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, it, vi } from "vitest";
import { createChannelOperations, type ChannelSource } from "#channel/channel-operations.js";
import type { Runtime } from "#channel/types.js";
-import { type InputResponse, parseInputResponses } from "#runtime/input/types.js";
+import { type InputResponse, parseInputResponses } from "#shared/input.js";
function authoredChannelRespondTypeChecks(source: ChannelSource): void {
const responseWithMetadata = {
diff --git a/packages/eve/src/channel/channel-operations.ts b/packages/eve/src/channel/channel-operations.ts
index 774b8e59e..ddf457037 100644
--- a/packages/eve/src/channel/channel-operations.ts
+++ b/packages/eve/src/channel/channel-operations.ts
@@ -22,7 +22,7 @@ import {
type InputResponse,
parseInputResponses,
type StrictInputResponses,
-} from "#runtime/input/types.js";
+} from "#shared/input.js";
import type { JsonObject } from "#shared/json.js";
import type { RunMode } from "#shared/run-mode.js";
diff --git a/packages/eve/src/runtime/governance/network/ip-allow-list.ts b/packages/eve/src/channel/ip-allow-list.ts
similarity index 100%
rename from packages/eve/src/runtime/governance/network/ip-allow-list.ts
rename to packages/eve/src/channel/ip-allow-list.ts
diff --git a/packages/eve/src/channel/resolve-text.test.ts b/packages/eve/src/channel/resolve-text.test.ts
index 49fef8370..d6920c990 100644
--- a/packages/eve/src/channel/resolve-text.test.ts
+++ b/packages/eve/src/channel/resolve-text.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import type { InputRequest } from "#runtime/input/types.js";
+import type { InputRequest } from "#shared/input.js";
import { resolveTextToResponse, resolveTextToResponses } from "#channel/resolve-text.js";
const APPROVAL_REQUEST: InputRequest = {
diff --git a/packages/eve/src/channel/resolve-text.ts b/packages/eve/src/channel/resolve-text.ts
index 7aa88b9e5..796e05663 100644
--- a/packages/eve/src/channel/resolve-text.ts
+++ b/packages/eve/src/channel/resolve-text.ts
@@ -1,4 +1,4 @@
-import type { InputOption, InputRequest, InputResponse } from "#runtime/input/types.js";
+import type { InputOption, InputRequest, InputResponse } from "#shared/input.js";
/**
* Maps freeform text to an {@link InputResponse} for a single request.
diff --git a/packages/eve/src/channel/routes.ts b/packages/eve/src/channel/routes.ts
index 76b07e657..15122cdec 100644
--- a/packages/eve/src/channel/routes.ts
+++ b/packages/eve/src/channel/routes.ts
@@ -2,7 +2,7 @@ import type { UserContent } from "ai";
import type { CrossChannelToFn } from "#channel/cross-channel-receive.js";
import type { ChannelFrom, ChannelResolveSession } from "#channel/channel-operations.js";
-import type { InputResponse } from "#runtime/input/types.js";
+import type { InputResponse } from "#shared/input.js";
import type { Session } from "#channel/session.js";
import type { JsonObject } from "#shared/json.js";
import type { ChannelMethod } from "#public/definitions/channel.js";
diff --git a/packages/eve/src/channel/session.test.ts b/packages/eve/src/channel/session.test.ts
index 9da4cf610..d33cc4515 100644
--- a/packages/eve/src/channel/session.test.ts
+++ b/packages/eve/src/channel/session.test.ts
@@ -9,7 +9,7 @@ import {
import type { Runtime } from "#channel/types.js";
import { ContextContainer } from "#context/container.js";
import { AuthKey, ContinuationTokenKey, InitiatorAuthKey, SessionIdKey } from "#context/keys.js";
-import { type InputResponse, parseInputResponses } from "#runtime/input/types.js";
+import { type InputResponse, parseInputResponses } from "#shared/input.js";
function fixedSessionRespondTypeChecks(session: Session): void {
const responsesWithMetadata = [
diff --git a/packages/eve/src/channel/session.ts b/packages/eve/src/channel/session.ts
index babfb31b7..48dbc3070 100644
--- a/packages/eve/src/channel/session.ts
+++ b/packages/eve/src/channel/session.ts
@@ -25,7 +25,7 @@ import {
type InputResponse,
parseInputResponses,
type StrictInputResponses,
-} from "#runtime/input/types.js";
+} from "#shared/input.js";
import type { JsonObject } from "#shared/json.js";
import { toChannelLocalContinuationToken } from "#shared/continuation-token.js";
diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.ts
index 623f2e907..86db55446 100644
--- a/packages/eve/src/channel/types.ts
+++ b/packages/eve/src/channel/types.ts
@@ -3,8 +3,8 @@ import type { UserContent } from "ai";
import type { MessageStreamEvent, UnstampedMessageStreamEvent } from "#protocol/message.js";
import type { CancelTurnResult as ProtocolCancelTurnResult } from "#protocol/cancel-turn.js";
import type { RunMode } from "#shared/run-mode.js";
-import type { RuntimeSubagentChildResult } from "#runtime/actions/types.js";
-import type { InputRequest, InputResponse } from "#runtime/input/types.js";
+import type { RuntimeSubagentChildResult } from "#shared/action-types.js";
+import type { InputRequest, InputResponse } from "#shared/input.js";
import type { ChannelAdapter } from "#channel/adapter.js";
import type { AgentLimitsDefinition } from "#shared/agent-definition.js";
import type { JsonObject } from "#shared/json.js";
diff --git a/packages/eve/src/cli/banner.ts b/packages/eve/src/cli/banner.ts
index 9f48a8a92..6cb1c5db1 100644
--- a/packages/eve/src/cli/banner.ts
+++ b/packages/eve/src/cli/banner.ts
@@ -1,4 +1,4 @@
-import pc from "picocolors";
+import pc from "#compiled/picocolors/index.js";
import { resolveInstalledPackageInfo } from "#internal/application/package.js";
diff --git a/packages/eve/src/cli/commands/agent-instructions.ts b/packages/eve/src/cli/commands/agent-instructions.ts
index 4ee6f23cd..c8a1577c5 100644
--- a/packages/eve/src/cli/commands/agent-instructions.ts
+++ b/packages/eve/src/cli/commands/agent-instructions.ts
@@ -1,7 +1,7 @@
import { readFileSync } from "node:fs";
import { join } from "node:path";
-import pc from "picocolors";
+import pc from "#compiled/picocolors/index.js";
import { DEFAULT_AGENT_MODEL_ID } from "#shared/default-agent-model.js";
diff --git a/packages/eve/src/cli/commands/channel-add-conflicts.ts b/packages/eve/src/cli/commands/channel-add-conflicts.ts
index bb136cef4..498d73883 100644
--- a/packages/eve/src/cli/commands/channel-add-conflicts.ts
+++ b/packages/eve/src/cli/commands/channel-add-conflicts.ts
@@ -4,6 +4,7 @@ import type { ChannelKind } from "#setup/scaffold/index.js";
import type { DisabledChannelReasons } from "#setup/cli/index.js";
import { compileChannelDefinition } from "#compiler/normalize-channel.js";
+import type { CompiledModuleBinding } from "#compiler/source-graph.js";
import { discoverAgent } from "#discover/discover-agent.js";
import { EVE_SESSION_ROUTE_PATH } from "#protocol/routes.js";
@@ -33,9 +34,21 @@ export async function inspectExistingChannelRegistrations(
const slackOwners = new Set<string>();
for (const source of manifest.channels) {
- const compiled = await compileChannelDefinition(agentRoot, source);
- const definitions = Array.isArray(compiled) ? compiled : [compiled];
- for (const definition of definitions) {
+ const binding: CompiledModuleBinding = {
+ backing: {
+ externalDependencies: [],
+ kind: "filesystem",
+ sourcePath: join(agentRoot, source.logicalPath),
+ },
+ logicalPath: source.logicalPath,
+ owner: { kind: "application" },
+ };
+ const compiled = await compileChannelDefinition(agentRoot, source, {
+ binding,
+ registries: [],
+ });
+ if (compiled.kind !== "channel") continue;
+ for (const definition of compiled.definitions) {
if (definition.kind !== "channel") {
continue;
}
diff --git a/packages/eve/src/cli/commands/extension-build.ts b/packages/eve/src/cli/commands/extension-build.ts
index 1bcc9135e..480560c11 100644
--- a/packages/eve/src/cli/commands/extension-build.ts
+++ b/packages/eve/src/cli/commands/extension-build.ts
@@ -1,4 +1,4 @@
-import pc from "picocolors";
+import pc from "#compiled/picocolors/index.js";
import { createCliTheme, renderCliTaggedLine } from "#cli/ui/output.js";
import { createLogger } from "#internal/logging.js";
diff --git a/packages/eve/src/cli/commands/extension-init.ts b/packages/eve/src/cli/commands/extension-init.ts
index 37c1105b4..d6dbffce0 100644
--- a/packages/eve/src/cli/commands/extension-init.ts
+++ b/packages/eve/src/cli/commands/extension-init.ts
@@ -2,7 +2,7 @@ import { mkdtemp, readdir, rename, rm, stat } from "node:fs/promises";
import { basename, join, resolve } from "node:path";
import { performance } from "node:perf_hooks";
-import pc from "picocolors";
+import pc from "#compiled/picocolors/index.js";
import { isCodingAgentLaunch } from "#cli/agent-detection.js";
import { EVE_WORDMARK } from "#cli/banner.js";
diff --git a/packages/eve/src/cli/commands/info.test.ts b/packages/eve/src/cli/commands/info.test.ts
index 41fc19361..b4338b801 100644
--- a/packages/eve/src/cli/commands/info.test.ts
+++ b/packages/eve/src/cli/commands/info.test.ts
@@ -2,15 +2,9 @@ import { describe, expect, test, vi } from "vitest";
import { COMPILE_METADATA_KIND, COMPILE_METADATA_VERSION } from "#compiler/artifacts.js";
import type { CompileAgentResult } from "#compiler/compile-agent.js";
-import {
- createCompiledAgentManifest,
- createCompiledAgentNodeManifest,
- type CompiledChannelEntry,
- type CompiledInstructionsDefinition,
- type CompiledScheduleDefinition,
- type CompiledSubagentNode,
- ROOT_COMPILED_AGENT_NODE_ID,
-} from "#compiler/manifest.js";
+import { compileFromMemory } from "#compiler/compile-from-memory.js";
+import { defineInstructions } from "#public/definitions/instructions.js";
+import { defineSchedule } from "#public/definitions/schedule.js";
import { getApplicationInfo } from "#internal/application/paths.js";
import { inspectApplication } from "#services/inspect-application.js";
@@ -23,114 +17,41 @@ const MESSAGING = {
sessionMessagesRoutePattern: "/eve/v1/session/:sessionId",
streamRoutePattern: "/eve/v1/session/:sessionId/stream",
};
-
const APP_ROOT = "/virtual/app";
-const AGENT_ROOT = "/virtual/app/agent";
-
-function makeSchedule(name: string): CompiledScheduleDefinition {
- return {
- cron: "0 9 * * *",
- hasRun: false,
- logicalPath: `schedules/${name}.md`,
- markdown: `# ${name}`,
- name,
- sourceId: `schedules/${name}.md`,
- sourceKind: "markdown",
- };
-}
-
-function makeSubagent(name: string): CompiledSubagentNode {
- return {
- agent: createCompiledAgentNodeManifest({
- agentRoot: `${AGENT_ROOT}/subagents/${name}`,
- appRoot: APP_ROOT,
- config: {
- model: {
- id: "anthropic/claude-sonnet-5",
- routing: { kind: "gateway", target: "anthropic" },
- },
- name,
- },
- }),
- description: `${name} subagent description`,
- entryPath: `subagents/${name}/agent.ts`,
- logicalPath: `subagents/${name}`,
- name,
- nodeId: name,
- rootPath: `subagents/${name}`,
- sourceId: `subagents/${name}/agent.ts`,
- sourceKind: "module",
- };
-}
+const AGENT_ROOT = `${APP_ROOT}/agent`;
-function makeCompiledState(
- options: {
- instructions?: CompiledInstructionsDefinition[];
- subagents?: CompiledSubagentNode[];
- schedules?: CompiledScheduleDefinition[];
- } = {},
-): CompileAgentResult {
- const channels: CompiledChannelEntry[] = [
- {
- kind: "channel",
- name: "slack",
- logicalPath: "agent/channels/slack.ts",
- method: "POST",
- urlPath: "/eve/v1/slack",
- sourceId: "memory::slack",
- sourceKind: "module",
- adapterKind: "slack",
- },
- {
- kind: "channel",
- name: "eve",
- logicalPath: "agent/channels/eve.ts",
- method: "POST",
- urlPath: "/eve/v1/session",
- sourceId: "memory::eve",
- sourceKind: "module",
- adapterKind: "http",
- },
- ];
- const manifest = createCompiledAgentManifest({
+async function makeCompiledState(): Promise<CompileAgentResult> {
+ const { manifest } = await compileFromMemory({
agentRoot: AGENT_ROOT,
appRoot: APP_ROOT,
- config: {
- model: {
- id: "anthropic/claude-sonnet-5",
- routing: { kind: "gateway", target: "anthropic" },
+ model: "openai/gpt-5.4",
+ modules: [
+ {
+ loadNamespace: async () => ({
+ default: defineInstructions({ content: "Standing rules.", role: "system" }),
+ }),
+ logicalPath: "instructions/rules.ts",
},
- name: "triage-bot",
- },
- channels,
- instructions: options.instructions ?? [],
- tools: [
{
- description: "Create a triage ticket.",
- inputSchema: null,
- logicalPath: "tools/create_ticket.ts",
- name: "create_ticket",
- sourceId: "memory::create_ticket",
- sourceKind: "module",
+ loadNamespace: async () => ({
+ default: defineSchedule({ cron: "0 9 * * *", markdown: "Run the digest." }),
+ }),
+ logicalPath: "schedules/morning-digest.ts",
},
],
- schedules: options.schedules ?? [],
- subagentEdges: (options.subagents ?? []).map((subagent) => ({
- childNodeId: subagent.nodeId,
- parentNodeId: ROOT_COMPILED_AGENT_NODE_ID,
- })),
- subagents: options.subagents ?? [],
+ name: "triage-bot",
+ tools: [{ description: "Create a triage ticket.", name: "create_ticket" }],
});
- const digest = { path: "x", sha256: "y" };
+ const digest = { path: "x", sha256: "a".repeat(64) };
return {
diagnostics: [],
manifest,
metadata: {
- compile: { moduleMap: digest },
+ compile: { manifest: digest, moduleMap: digest },
discovery: {
diagnostics: digest,
manifest: digest,
- sourceGraphHash: "hash",
+ sourceGraphHash: "a".repeat(64),
summary: { errors: 0, warnings: 0 },
},
generator: { name: "eve", version: "0.0.0-test" },
@@ -153,71 +74,26 @@ function makeCompiledState(
}
describe("buildApplicationInfoJson", () => {
- test("projects a compiled agent into the JSON contract", () => {
+ test("projects the effective compiled graph into the JSON contract", async () => {
const json = buildApplicationInfoJson({
application: getApplicationInfo(APP_ROOT),
- compiledState: makeCompiledState(),
+ compiledState: await makeCompiledState(),
messaging: MESSAGING,
});
- expect(json.status).toBe("ready");
- expect(json.model).toBe("anthropic/claude-sonnet-5");
- expect(json.tools).toEqual(["create_ticket"]);
- expect(json.skills).toEqual([]);
- expect(json.subagents).toEqual([]);
- expect(json.schedules).toEqual([]);
- expect(json.diagnostics).toEqual({ errors: 0, warnings: 0 });
- expect(json.channels).toEqual([
- { name: "slack", kind: "slack", method: "POST", urlPath: "/eve/v1/slack" },
- { name: "eve", kind: "http", method: "POST", urlPath: "/eve/v1/session" },
- ]);
- expect(json.messaging.create).toBe("/eve/v1/session");
- expect(json.artifacts?.compiledManifest).toContain("compiled-agent-manifest.json");
- });
-
- test("projects subagents and schedules into the JSON contract when present", () => {
- const json = buildApplicationInfoJson({
- application: getApplicationInfo(APP_ROOT),
- compiledState: makeCompiledState({
- schedules: [makeSchedule("morning-digest"), makeSchedule("weekly-report")],
- subagents: [makeSubagent("research")],
- }),
- messaging: MESSAGING,
- });
-
- expect(json.subagents).toEqual(["research"]);
- expect(json.schedules).toEqual(["morning-digest", "weekly-report"]);
- });
-
- test("projects ordered instruction paths with their roles", () => {
- const json = buildApplicationInfoJson({
- application: getApplicationInfo(APP_ROOT),
- compiledState: makeCompiledState({
- instructions: [
- {
- content: "Standing rules.",
- logicalPath: "instructions/10-rules.ts",
- name: "instructions/10-rules",
- role: "system",
- sourceId: "instructions/10-rules.ts",
- sourceKind: "module",
- },
- {
- content: "Imported brief.",
- logicalPath: "instructions/20-brief.ts",
- name: "instructions/20-brief",
- role: "user",
- sourceId: "instructions/20-brief.ts",
- sourceKind: "module",
- },
- ],
- }),
- messaging: MESSAGING,
+ expect(json).toMatchObject({
+ diagnostics: { errors: 0, warnings: 0 },
+ instructions: "instructions/rules.ts (system)",
+ model: "openai/gpt-5.4",
+ schedules: ["morning-digest"],
+ status: "ready",
});
-
- expect(json.instructions).toBe(
- "instructions/10-rules.ts (system), instructions/20-brief.ts (user)",
+ expect(json.tools).toContain("create_ticket");
+ expect(json.channels).toContainEqual(
+ expect.objectContaining({ method: "GET", urlPath: "/eve/v1/health" }),
);
+ expect(json.messaging.create).toBe("/eve/v1/session");
+ expect(json.artifacts?.compiledManifest).toContain("compiled-agent-manifest.json");
});
test("reports an unavailable contract when the project is not compiled", () => {
@@ -227,26 +103,24 @@ describe("buildApplicationInfoJson", () => {
messaging: MESSAGING,
});
- expect(json.status).toBe("unavailable");
- expect(json.model).toBeNull();
- expect(json.instructions).toBeNull();
- expect(json.diagnostics).toBeNull();
- expect(json.artifacts).toBeNull();
- expect(json.channels).toEqual([]);
- expect(json.tools).toEqual([]);
- expect(json.skills).toEqual([]);
- expect(json.subagents).toEqual([]);
- expect(json.schedules).toEqual([]);
- expect(json.appRoot).toBe(APP_ROOT);
- expect(json.messaging.stream).toBe("/eve/v1/session/:sessionId/stream");
+ expect(json).toMatchObject({
+ appRoot: APP_ROOT,
+ artifacts: null,
+ channels: [],
+ diagnostics: null,
+ model: null,
+ status: "unavailable",
+ tools: [],
+ });
});
});
describe("printApplicationInfo", () => {
- test("includes the authored tool count in text output", async () => {
+ test("reports the effective compiled tool count", async () => {
+ const compiledState = await makeCompiledState();
vi.mocked(inspectApplication).mockResolvedValue({
application: getApplicationInfo(APP_ROOT),
- compiledState: makeCompiledState(),
+ compiledState,
messaging: MESSAGING,
});
const output: string[] = [];
@@ -254,6 +128,6 @@ describe("printApplicationInfo", () => {
await printApplicationInfo({ log: (message) => output.push(message) }, APP_ROOT);
expect(output).toHaveLength(1);
- expect(output[0]).toMatch(/Tools\s+1 tool/);
+ expect(output[0]).toMatch(new RegExp(`Tools\\s+${compiledState.manifest.tools.length} tools?`));
});
});
diff --git a/packages/eve/src/cli/commands/info.ts b/packages/eve/src/cli/commands/info.ts
index 703666ab6..4b2593d90 100644
--- a/packages/eve/src/cli/commands/info.ts
+++ b/packages/eve/src/cli/commands/info.ts
@@ -69,16 +69,12 @@ export function buildApplicationInfoJson(inspection: ApplicationInspection): App
tools: (compiledState?.manifest.tools ?? []).map((tool) => tool.name),
subagents: (compiledState?.manifest.subagents ?? []).map((subagent) => subagent.name),
schedules: (compiledState?.manifest.schedules ?? []).map((schedule) => schedule.name),
- channels: (compiledState?.manifest.channels ?? []).map((channel) =>
- channel.kind === "channel"
- ? {
- name: channel.name,
- kind: channel.adapterKind ?? null,
- method: channel.method,
- urlPath: channel.urlPath,
- }
- : { name: channel.name, kind: "disabled", method: null, urlPath: null },
- ),
+ channels: (compiledState?.manifest.channelRoutes.effective ?? []).map((channel) => ({
+ name: channel.name,
+ kind: channel.adapterKind ?? null,
+ method: channel.method,
+ urlPath: channel.urlPath,
+ })),
messaging: {
create: messaging.createSessionRoutePath,
messages: messaging.sessionMessagesRoutePattern,
diff --git a/packages/eve/src/cli/commands/init.ts b/packages/eve/src/cli/commands/init.ts
index e10e38392..cd94390e6 100644
--- a/packages/eve/src/cli/commands/init.ts
+++ b/packages/eve/src/cli/commands/init.ts
@@ -2,7 +2,7 @@ import { mkdtemp, readdir, rename, rm } from "node:fs/promises";
import { basename, join, relative, resolve } from "node:path";
import { performance } from "node:perf_hooks";
-import pc from "picocolors";
+import pc from "#compiled/picocolors/index.js";
import { isCodingAgentLaunch } from "#cli/agent-detection.js";
import { EVE_WORDMARK } from "#cli/banner.js";
diff --git a/packages/eve/src/cli/dev/tui/agent-header.test.ts b/packages/eve/src/cli/dev/tui/agent-header.test.ts
index 5f6ecd699..ea700deb2 100644
--- a/packages/eve/src/cli/dev/tui/agent-header.test.ts
+++ b/packages/eve/src/cli/dev/tui/agent-header.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import type { AgentInfoResult, AgentInfoToolEntry } from "#client/index.js";
import { stripAnsi } from "#cli/ui/terminal-text.js";
+import { createTestAgentInfoResult } from "#internal/testing/agent-info-fixture.js";
import { AGENT_HEADER_TIPS, buildAgentHeader, pickAgentHeaderTip } from "./agent-header.js";
import { createTheme } from "./theme.js";
@@ -15,9 +16,8 @@ const FRAMEWORK_TOOL: AgentInfoToolEntry = {
inputSchema: { type: "object" },
logicalPath: "eve:framework/bash",
name: "bash",
- origin: "framework",
+ owner: { feature: "test", kind: "framework" },
outputSchema: { type: "object" },
- replacesFrameworkTool: false,
requiresApproval: false,
sourceId: "eve:bash-tool",
sourceKind: "module",
@@ -32,86 +32,22 @@ const AUTHORED_TOOL: AgentInfoToolEntry = {
inputSchema: { type: "object" },
logicalPath: "agent/tools/get_weather.ts",
name: "get_weather",
- origin: "authored",
+ owner: { kind: "application" },
outputSchema: null,
- replacesFrameworkTool: false,
requiresApproval: false,
+ sourceId: "tools/get_weather.ts",
sourceKind: "module",
};
+const TEST_INFO = createTestAgentInfoResult({
+ agentRoot: "/tmp/weather-agent/agent",
+ appRoot: "/tmp/weather-agent",
+ modelId: "anthropic/claude-opus-4.7",
+ name: "Weather Agent",
+});
const INFO: AgentInfoResult = {
- agent: {
- agentRoot: "/tmp/weather-agent/agent",
- appRoot: "/tmp/weather-agent",
- model: {
- id: "anthropic/claude-opus-4.7",
- routing: { kind: "gateway", target: "anthropic" },
- },
- name: "Weather Agent",
- },
- capabilities: {
- devRoutes: true,
- },
- channels: {
- authored: [],
- available: [],
- disabledFramework: [],
- framework: [],
- },
- connections: [],
- diagnostics: {
- discoveryErrors: 0,
- discoveryWarnings: 0,
- },
- hooks: [],
- instructions: {
- dynamic: [],
- static: [
- {
- content: "You are a weather assistant.",
- logicalPath: "instructions.md",
- name: "instructions",
- role: "system",
- sourceKind: "markdown",
- },
- ],
- },
- kind: "eve-agent-info",
- mode: "development",
- sandbox: null,
- schedules: [],
- skills: {
- dynamic: [],
- static: [],
- },
- subagents: {
- local: [],
- total: 0,
- },
- tools: {
- authored: [AUTHORED_TOOL],
- available: [FRAMEWORK_TOOL, AUTHORED_TOOL],
- disabledFramework: [],
- dynamic: [],
- framework: [
- {
- ...FRAMEWORK_TOOL,
- disabledByAuthor: false,
- replacedByAuthoredTool: false,
- status: "active",
- },
- ],
- reserved: [],
- },
- version: 2,
- workflow: {
- enabled: false,
- toolName: "Workflow",
- },
- workspace: {
- resourceRoot: null,
- rootEntries: [],
- },
+ ...TEST_INFO,
+ tools: { dynamic: [], static: [FRAMEWORK_TOOL, AUTHORED_TOOL] },
};
describe("buildAgentHeader", () => {
diff --git a/packages/eve/src/cli/dev/tui/remote-auth.ts b/packages/eve/src/cli/dev/tui/remote-auth.ts
index b671db3b5..b431d5b62 100644
--- a/packages/eve/src/cli/dev/tui/remote-auth.ts
+++ b/packages/eve/src/cli/dev/tui/remote-auth.ts
@@ -20,7 +20,7 @@ import {
type RemoteAuthPreparation,
} from "./remote-auth-result.js";
import { toErrorMessage } from "#shared/errors.js";
-import pc from "picocolors";
+import pc from "#compiled/picocolors/index.js";
/** Injectable entry point for the remote authentication flow. */
export type RemoteAuthFlow = typeof runRemoteAuthFlow;
diff --git a/packages/eve/src/cli/dev/tui/remote-connection.test.ts b/packages/eve/src/cli/dev/tui/remote-connection.test.ts
index a6a429e93..9a32bec5b 100644
--- a/packages/eve/src/cli/dev/tui/remote-connection.test.ts
+++ b/packages/eve/src/cli/dev/tui/remote-connection.test.ts
@@ -12,6 +12,7 @@ import {
type DevelopmentCredentialGate,
} from "#services/dev-client/credential-gate.js";
import type { VercelDeploymentResolution } from "#setup/vercel-deployment.js";
+import { createTestAgentInfoResult } from "#internal/testing/agent-info-fixture.js";
import type { RemoteAuthPreparation } from "./remote-auth-result.js";
import {
@@ -43,48 +44,12 @@ const NEWER_VERIFIED_TARGET = await resolveTestVercelTarget({
projectName: "inbound-next",
});
-const INFO: AgentInfoResult = {
- agent: {
- agentRoot: "/tmp/weather-agent/agent",
- appRoot: "/tmp/weather-agent",
- model: { id: "gpt-5", routing: { kind: "gateway", target: "openai" } },
- name: "Weather Agent",
- },
- capabilities: { devRoutes: true },
- channels: { authored: [], available: [], disabledFramework: [], framework: [] },
- connections: [],
- diagnostics: { discoveryErrors: 0, discoveryWarnings: 0 },
- hooks: [],
- instructions: {
- dynamic: [],
- static: [
- {
- content: "You are a weather assistant.",
- logicalPath: "agent/instructions.md",
- name: "instructions",
- role: "system",
- sourceKind: "markdown",
- },
- ],
- },
- kind: "eve-agent-info",
- mode: "development",
- sandbox: null,
- schedules: [],
- skills: { dynamic: [], static: [] },
- subagents: { local: [], total: 0 },
- tools: {
- authored: [],
- available: [],
- disabledFramework: [],
- dynamic: [],
- framework: [],
- reserved: [],
- },
- version: 2,
- workflow: { enabled: false, toolName: "Workflow" },
- workspace: { resourceRoot: null, rootEntries: [] },
-};
+const INFO: AgentInfoResult = createTestAgentInfoResult({
+ agentRoot: "/tmp/weather-agent/agent",
+ appRoot: "/tmp/weather-agent",
+ modelId: "gpt-5",
+ name: "Weather Agent",
+});
const VERCEL_SSO_CHALLENGE = `
<title>Authentication Required</title>
diff --git a/packages/eve/src/cli/dev/tui/runner.test.ts b/packages/eve/src/cli/dev/tui/runner.test.ts
index 5f234cedd..3abd65dbc 100644
--- a/packages/eve/src/cli/dev/tui/runner.test.ts
+++ b/packages/eve/src/cli/dev/tui/runner.test.ts
@@ -9,6 +9,7 @@ import {
type MessageStreamEvent,
} from "#client/index.js";
import { stampTestEvent } from "#internal/testing/events.js";
+import { createTestAgentInfoResult } from "#internal/testing/agent-info-fixture.js";
import { resolveTestVercelTarget } from "#internal/testing/verified-vercel-target.js";
import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
import { createDevelopmentCredentialGate } from "#services/dev-client/credential-gate.js";
@@ -98,89 +99,12 @@ function isStamped(event: unknown): event is MessageStreamEvent {
return typeof (event as MessageStreamEvent).meta?.id === "string";
}
-const AGENT_INFO: AgentInfoResult = {
- agent: {
- agentRoot: "/tmp/weather-agent/agent",
- appRoot: "/tmp/weather-agent",
- model: {
- id: "gpt-5",
- routing: { kind: "gateway", target: "openai" },
- },
- name: "Weather Agent",
- },
- capabilities: {
- devRoutes: true,
- },
- channels: {
- authored: [],
- available: [],
- disabledFramework: [],
- framework: [],
- },
- connections: [],
- diagnostics: {
- discoveryErrors: 0,
- discoveryWarnings: 0,
- },
- hooks: [],
- instructions: {
- dynamic: [],
- static: [
- {
- content: "You are a weather assistant.",
- logicalPath: "agent/instructions.md",
- name: "instructions",
- role: "system",
- sourceKind: "markdown",
- },
- ],
- },
- kind: "eve-agent-info",
- mode: "development",
- sandbox: null,
- schedules: [],
- skills: {
- dynamic: [],
- static: [],
- },
- subagents: {
- local: [],
- total: 0,
- },
- tools: {
- authored: [
- {
- description: "Get the weather.",
- hasAuth: false,
- hasExecute: true,
- hasModelOutputProjection: false,
- hasOutputSchema: false,
- inputSchema: { type: "object" },
- logicalPath: "agent/tools/get_weather.ts",
- name: "get_weather",
- origin: "authored",
- outputSchema: null,
- replacesFrameworkTool: false,
- requiresApproval: false,
- sourceKind: "module",
- },
- ],
- available: [],
- disabledFramework: [],
- dynamic: [],
- framework: [],
- reserved: [],
- },
- version: 2,
- workflow: {
- enabled: false,
- toolName: "Workflow",
- },
- workspace: {
- resourceRoot: null,
- rootEntries: [],
- },
-};
+const AGENT_INFO: AgentInfoResult = createTestAgentInfoResult({
+ agentRoot: "/tmp/weather-agent/agent",
+ appRoot: "/tmp/weather-agent",
+ modelId: "gpt-5",
+ name: "Weather Agent",
+});
beforeEach(() => {
// The runner normalizes header endpoints from the real process.env; a
diff --git a/packages/eve/src/cli/dev/tui/setup-issues.integration.test.ts b/packages/eve/src/cli/dev/tui/setup-issues.integration.test.ts
index 8e78abb13..b1ac5ddb3 100644
--- a/packages/eve/src/cli/dev/tui/setup-issues.integration.test.ts
+++ b/packages/eve/src/cli/dev/tui/setup-issues.integration.test.ts
@@ -5,6 +5,7 @@ import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { Client, type AgentInfoResult } from "#client/index.js";
+import { createTestAgentInfoResult } from "#internal/testing/agent-info-fixture.js";
import { EveTUIRunner, type AgentTUIRenderer } from "./runner.js";
import { detectSetupIssues } from "./setup-issues.js";
@@ -14,40 +15,22 @@ afterEach(() => {
vi.unstubAllGlobals();
});
+const BASE_GATEWAY_INFO = createTestAgentInfoResult({
+ agentRoot: "/app/agent",
+ appRoot: "/app",
+ modelId: "openai/gpt-5.5",
+ name: "Agent",
+});
const DISCONNECTED_GATEWAY_INFO: AgentInfoResult = {
+ ...BASE_GATEWAY_INFO,
agent: {
- agentRoot: "/app/agent",
- appRoot: "/app",
+ ...BASE_GATEWAY_INFO.agent,
model: {
endpoint: { kind: "gateway", connected: false },
id: "openai/gpt-5.5",
routing: { kind: "gateway", target: "openai" },
},
- name: "Agent",
- },
- capabilities: { devRoutes: true },
- channels: { authored: [], available: [], disabledFramework: [], framework: [] },
- connections: [],
- diagnostics: { discoveryErrors: 0, discoveryWarnings: 0 },
- hooks: [],
- instructions: { dynamic: [], static: [] },
- kind: "eve-agent-info",
- mode: "development",
- sandbox: null,
- schedules: [],
- skills: { dynamic: [], static: [] },
- subagents: { local: [], total: 0 },
- tools: {
- authored: [],
- available: [],
- disabledFramework: [],
- dynamic: [],
- framework: [],
- reserved: [],
},
- version: 2,
- workflow: { enabled: false, toolName: "Workflow" },
- workspace: { resourceRoot: null, rootEntries: [] },
};
async function linkedAppRoot(): Promise<string> {
diff --git a/packages/eve/src/cli/dev/tui/setup-issues.test.ts b/packages/eve/src/cli/dev/tui/setup-issues.test.ts
index e5cee99b4..488964c5c 100644
--- a/packages/eve/src/cli/dev/tui/setup-issues.test.ts
+++ b/packages/eve/src/cli/dev/tui/setup-issues.test.ts
@@ -10,6 +10,7 @@ import {
normalizeLocalModelEndpoint,
type BootDetectionContext,
} from "./setup-issues.js";
+import { createTestAgentInfoResult } from "#internal/testing/agent-info-fixture.js";
function context(overrides: Partial<BootDetectionContext> = {}): BootDetectionContext {
return { appRoot: "/nonexistent", env: {}, ...overrides };
@@ -29,37 +30,8 @@ function infoWithRouting(
? { id: "m", routing }
: { endpoint, id: "m", routing };
- return {
- agent: {
- agentRoot: "/a",
- appRoot: "/a",
- model,
- name: "Agent",
- },
- capabilities: { devRoutes: true },
- channels: { authored: [], available: [], disabledFramework: [], framework: [] },
- connections: [],
- diagnostics: { discoveryErrors: 0, discoveryWarnings: 0 },
- hooks: [],
- instructions: { dynamic: [], static: [] },
- kind: "eve-agent-info",
- mode: "development",
- sandbox: null,
- schedules: [],
- skills: { dynamic: [], static: [] },
- subagents: { local: [], total: 0 },
- tools: {
- authored: [],
- available: [],
- disabledFramework: [],
- dynamic: [],
- framework: [],
- reserved: [],
- },
- version: 2,
- workflow: { enabled: false, toolName: "Workflow" },
- workspace: { resourceRoot: null, rootEntries: [] },
- };
+ const info = createTestAgentInfoResult({ agentRoot: "/a/agent", appRoot: "/a", name: "Agent" });
+ return { ...info, agent: { ...info.agent, model } };
}
describe("BOOT_DETECTIONS", () => {
diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts
index 8f801e92c..f02a2952a 100644
--- a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts
+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vitest";
import type { AgentInfoResult } from "#client/index.js";
import type { LogRecord } from "#internal/logging.js";
+import { createTestAgentInfoResult } from "#internal/testing/agent-info-fixture.js";
import type { DevDiagnostics } from "../diagnostics.js";
import { searchActionValue } from "#setup/cli/select-state.js";
import {
@@ -85,65 +86,17 @@ function agentInfoWithModel(
endpoint?: StaticAgentInfoModel["endpoint"],
extras?: Partial<StaticAgentInfoModel>,
): AgentInfoResult {
+ const info = createTestAgentInfoResult({ modelId, name: "Weather Agent" });
return {
+ ...info,
agent: {
- agentRoot: "/tmp/weather-agent/agent",
- appRoot: "/tmp/weather-agent",
+ ...info.agent,
model: {
id: modelId,
endpoint,
routing: { kind: "gateway" as const, target: modelId.split("/")[0] ?? "openai" },
...extras,
},
- name: "Weather Agent",
- },
- capabilities: {
- devRoutes: true,
- },
- channels: {
- authored: [],
- available: [],
- disabledFramework: [],
- framework: [],
- },
- connections: [],
- diagnostics: {
- discoveryErrors: 0,
- discoveryWarnings: 0,
- },
- hooks: [],
- instructions: {
- dynamic: [],
- static: [],
- },
- kind: "eve-agent-info",
- mode: "development",
- sandbox: null,
- schedules: [],
- skills: {
- dynamic: [],
- static: [],
- },
- subagents: {
- local: [],
- total: 0,
- },
- tools: {
- authored: [],
- available: [],
- disabledFramework: [],
- dynamic: [],
- framework: [],
- reserved: [],
- },
- version: 2,
- workflow: {
- enabled: false,
- toolName: "Workflow",
- },
- workspace: {
- resourceRoot: null,
- rootEntries: [],
},
};
}
diff --git a/packages/eve/src/cli/dev/tui/tool-presentation.test.ts b/packages/eve/src/cli/dev/tui/tool-presentation.test.ts
index 553ab7357..52f839761 100644
--- a/packages/eve/src/cli/dev/tui/tool-presentation.test.ts
+++ b/packages/eve/src/cli/dev/tui/tool-presentation.test.ts
@@ -1,7 +1,5 @@
import { describe, expect, it } from "vitest";
-import { getAllFrameworkToolNames } from "#runtime/framework-tools/index.js";
-
import { presentPreparingTool, presentTool } from "./tool-presentation.js";
describe("presentPreparingTool", () => {
@@ -169,7 +167,7 @@ describe("presentTool", () => {
expect(presentTool("final_output", { anything: true }).title).toBe("Return final output");
});
- it("covers every framework builtin with semantic copy", () => {
+ it("covers the builtin presentation table with semantic copy", () => {
const representativeInputs: Record<string, unknown> = {
agent: { message: "audit the auth flow" },
ask_question: { prompt: "Which environment?" },
@@ -186,12 +184,7 @@ describe("presentTool", () => {
write_file: { filePath: "/workspace/a.ts", content: "x" },
};
- for (const name of getAllFrameworkToolNames()) {
- const input = representativeInputs[name];
- expect(
- input,
- `framework tool "${name}" has no representative input — add semantic copy for it in tool-presentation.ts and cover it here`,
- ).toBeDefined();
+ for (const [name, input] of Object.entries(representativeInputs)) {
expect(presentTool(name, input).title, name).not.toBe(name);
}
});
diff --git a/packages/eve/src/cli/ui/live-row.ts b/packages/eve/src/cli/ui/live-row.ts
index 41a407472..48ecd41fb 100644
--- a/packages/eve/src/cli/ui/live-row.ts
+++ b/packages/eve/src/cli/ui/live-row.ts
@@ -1,4 +1,4 @@
-import pc from "picocolors";
+import pc from "#compiled/picocolors/index.js";
import { sliceVisible, visibleLength } from "#cli/ui/terminal-text.js";
import { LiveRegion } from "#cli/ui/live-region.js";
diff --git a/packages/eve/src/client/agent-info-schema.ts b/packages/eve/src/client/agent-info-schema.ts
index abd7038b4..af86761d8 100644
--- a/packages/eve/src/client/agent-info-schema.ts
+++ b/packages/eve/src/client/agent-info-schema.ts
@@ -1,38 +1,95 @@
import { z } from "#compiled/zod/index.js";
-const source = z.object({
- exportName: z.string().optional(),
- logicalPath: z.string(),
- sourceId: z.string().optional(),
- sourceKind: z.string(),
-});
+const owner = z.discriminatedUnion("kind", [
+ z.object({ kind: z.literal("application") }).strict(),
+ z.object({ feature: z.string(), kind: z.literal("framework") }).strict(),
+ z
+ .object({ kind: z.literal("extension"), namespace: z.string(), packageName: z.string() })
+ .strict(),
+]);
+
+const moduleBacking = z.discriminatedUnion("kind", [
+ z
+ .object({
+ externalDependencies: z.array(z.string()),
+ extensionScope: z
+ .object({ namespace: z.string(), sourceRoot: z.string() })
+ .strict()
+ .optional(),
+ kind: z.literal("filesystem"),
+ sourcePath: z.string(),
+ })
+ .strict(),
+ z
+ .object({
+ kind: z.literal("programmatic"),
+ moduleId: z.string(),
+ registryId: z.string(),
+ revision: z.string(),
+ semanticRevision: z.string().optional(),
+ })
+ .strict(),
+]);
+
+const binding = z
+ .object({
+ backing: moduleBacking,
+ logicalPath: z.string(),
+ owner,
+ })
+ .strict();
-const entry = source.extend({ name: z.string() });
+const source = z
+ .object({
+ binding: binding.optional(),
+ exportName: z.string().optional(),
+ logicalPath: z.string(),
+ owner,
+ sourceId: z.string(),
+ sourceKind: z.enum(["markdown", "module", "skill-package"]),
+ })
+ .strict();
+
+type ParsedAgentInfoSource = z.output<typeof source>;
+
+const entry = source.extend({ name: z.string() }).strict();
+
+const dynamicResolver = source
+ .extend({
+ eventNames: z.array(z.string()),
+ slug: z.string(),
+ })
+ .strict();
const modelRouting = z.discriminatedUnion("kind", [
- z.object({ kind: z.literal("gateway"), target: z.string(), byok: z.string().optional() }),
- z.object({ kind: z.literal("external"), provider: z.string() }),
+ z
+ .object({ kind: z.literal("gateway"), target: z.string(), byok: z.string().optional() })
+ .strict(),
+ z.object({ kind: z.literal("external"), provider: z.string() }).strict(),
]);
const modelEndpoint = z.union([
- z.object({ kind: z.literal("external"), provider: z.string() }),
- z.object({
- kind: z.literal("chatgpt"),
- state: z.enum(["checking", "ready", "signed-out", "reauth-required", "unavailable"]),
- accountLabel: z.string().optional(),
- }),
- z.object({
- kind: z.literal("gateway"),
- connected: z.literal(true),
- credential: z.enum(["api-key", "oidc"]),
- }),
- z.object({ kind: z.literal("gateway"), connected: z.literal(false) }),
+ z.object({ kind: z.literal("external"), provider: z.string() }).strict(),
+ z
+ .object({
+ kind: z.literal("chatgpt"),
+ state: z.enum(["checking", "ready", "signed-out", "reauth-required", "unavailable"]),
+ accountLabel: z.string().optional(),
+ })
+ .strict(),
+ z
+ .object({
+ kind: z.literal("gateway"),
+ connected: z.literal(true),
+ credential: z.enum(["api-key", "oidc"]),
+ })
+ .strict(),
+ z.object({ kind: z.literal("gateway"), connected: z.literal(false) }).strict(),
]);
-const agentModelBaseFields = {
+const modelBaseFields = {
contextWindowTokens: z.number().optional(),
providerOptions: z.unknown().optional(),
- // An unrecognized future effort level degrades to absent, not a parse failure.
reasoning: z
.enum(["provider-default", "none", "minimal", "low", "medium", "high", "xhigh"])
.optional()
@@ -43,177 +100,362 @@ const agentModelBaseFields = {
const agentModel = z.union([
z
.object({
- ...agentModelBaseFields,
+ ...modelBaseFields,
+ endpoint: modelEndpoint.optional(),
id: z.string(),
routing: modelRouting,
- endpoint: modelEndpoint.optional(),
})
.strict(),
z
.object({
- ...agentModelBaseFields,
+ ...modelBaseFields,
endpoint: z.never().optional(),
id: z.never().optional(),
- routing: z.object({ kind: z.literal("dynamic") }).strict(),
+ routing: z.object({ kind: z.literal("dynamic"), resolver: dynamicResolver }).strict(),
})
.strict(),
]);
-const tool = entry.extend({
- description: z.string(),
- hasAuth: z.boolean(),
- hasExecute: z.boolean(),
- hasModelOutputProjection: z.boolean(),
- hasOutputSchema: z.boolean(),
- inputSchema: z.unknown(),
- origin: z.enum(["authored", "framework"]),
- outputSchema: z.unknown().optional(),
- replacesFrameworkTool: z.boolean(),
- requiresApproval: z.boolean(),
-});
-
-const frameworkTool = tool.extend({
- disabledByAuthor: z.boolean(),
- replacedByAuthoredTool: z.boolean(),
- status: z.enum(["active", "disabled", "opt-in", "replaced"]),
-});
-
-const dynamicResolver = source.extend({
- eventNames: z.array(z.string()),
- origin: z.enum(["authored", "framework"]),
- slug: z.string(),
-});
-
-const skill = entry.extend({
- description: z.string(),
- license: z.string().optional(),
- markdown: z.string(),
- metadata: z.record(z.string(), z.string()).optional(),
-});
-
-const instructions = entry.extend({
- content: z.string(),
- role: z.enum(["system", "user"]),
-});
-
-const schedule = entry.extend({
- cron: z.string(),
- hasRun: z.boolean(),
- markdown: z.string().optional(),
-});
-
-const subagent = entry.extend({
- description: z.string().optional(),
- entryPath: z.string(),
- nodeId: z.string(),
- rootPath: z.string(),
- summary: z.object({
- channels: z.number(),
- connections: z.number(),
- hooks: z.number(),
- instructions: z.boolean(),
- schedules: z.number(),
- skills: z.number(),
- tools: z.number(),
- }),
-});
-
-const channel = entry.extend({
- adapterKind: z.string().optional(),
- method: z.string(),
- origin: z.enum(["authored", "framework"]),
- urlPath: z.string(),
-});
-
-const frameworkChannel = channel.extend({
- disabledByAuthor: z.boolean(),
- replacedByAuthoredChannel: z.boolean(),
- status: z.enum(["active", "disabled", "replaced"]),
-});
-
-const connection = source.extend({
- connectionName: z.string(),
- description: z.string(),
- hasApproval: z.boolean(),
- hasAuthorization: z.boolean(),
- hasHeaders: z.boolean(),
- protocol: z.string(),
- toolFilter: z.unknown().optional(),
- url: z.string(),
-});
-
-const hook = source.extend({
- eventNames: z.array(z.string()),
- slug: z.string(),
-});
-
-const sandbox = source.extend({
- backendKind: z.string().optional(),
- description: z.string().optional(),
- hasBootstrap: z.boolean(),
- hasOnSession: z.boolean(),
- revalidationKey: z.string().optional(),
- sourceHash: z.string().optional(),
-});
-
-/** Runtime contract for the complete `/eve/v1/info` response. */
-export const AgentInfoResultSchema = z.object({
- agent: z.object({
- agentRoot: z.string(),
- appRoot: z.string(),
- configSource: source.optional(),
- description: z.string().optional(),
- model: agentModel,
- name: z.string(),
+const tool = entry
+ .extend({
+ description: z.string(),
+ hasAuth: z.boolean(),
+ hasExecute: z.boolean(),
+ hasModelOutputProjection: z.boolean(),
+ hasOutputSchema: z.boolean(),
+ inputSchema: z.unknown(),
outputSchema: z.unknown().optional(),
- }),
- capabilities: z.object({ devRoutes: z.boolean() }),
- channels: z.object({
- authored: z.array(channel),
- available: z.array(channel),
- disabledFramework: z.array(z.string()),
- framework: z.array(frameworkChannel),
- }),
- connections: z.array(connection),
- diagnostics: z.object({
- discoveryErrors: z.number(),
- discoveryWarnings: z.number(),
- }),
- hooks: z.array(hook),
- instructions: z.object({
- dynamic: z.array(dynamicResolver),
- static: z.array(instructions),
- }),
- kind: z.literal("eve-agent-info"),
- mode: z.enum(["development", "production"]),
- sandbox: sandbox.nullable(),
- schedules: z.array(schedule),
- skills: z.object({
- dynamic: z.array(dynamicResolver),
- static: z.array(skill),
- }),
- subagents: z.object({
- local: z.array(subagent),
- total: z.number(),
- }),
- tools: z.object({
- authored: z.array(tool),
- available: z.array(tool),
- disabledFramework: z.array(z.string()),
- dynamic: z.array(dynamicResolver),
- framework: z.array(frameworkTool),
- reserved: z.array(z.string()),
- }),
- version: z.literal(2),
- workflow: z.object({
- enabled: z.boolean(),
- toolName: z.string(),
- }),
- workspace: z.object({
- resourceRoot: z.unknown(),
- rootEntries: z.array(z.string()),
- }),
-});
+ requiresApproval: z.boolean(),
+ })
+ .strict();
+
+const skill = entry
+ .extend({
+ description: z.string(),
+ license: z.string().optional(),
+ markdown: z.string(),
+ metadata: z.record(z.string(), z.string()).optional(),
+ })
+ .strict();
+
+const instructions = entry
+ .extend({ content: z.string(), role: z.enum(["system", "user"]) })
+ .strict();
+
+const schedule = entry
+ .extend({ cron: z.string(), hasRun: z.boolean(), markdown: z.string().optional() })
+ .strict();
+
+const channelMethod = z.enum([
+ "GET",
+ "HEAD",
+ "POST",
+ "PUT",
+ "PATCH",
+ "DELETE",
+ "OPTIONS",
+ "WEBSOCKET",
+]);
+
+const channelRoute = entry
+ .extend({ adapterKind: z.string().optional(), method: channelMethod, urlPath: z.string() })
+ .strict();
+
+const sourceDescriptor = z
+ .object({
+ backing: z.union([
+ moduleBacking,
+ z.object({ kind: z.literal("resource"), sourcePath: z.string() }).strict(),
+ ]),
+ layer: z.enum(["framework-default", "extension-package", "extension-override", "application"]),
+ logicalPath: z.string(),
+ owner,
+ sourceId: z.string(),
+ })
+ .strict();
+
+const shadowedChannelRoute = z
+ .object({
+ method: channelMethod,
+ source: sourceDescriptor,
+ urlPath: z.string(),
+ winnerSourceId: z.string(),
+ })
+ .strict();
+
+const connection = source
+ .extend({
+ connectionName: z.string(),
+ description: z.string(),
+ hasApproval: z.boolean(),
+ hasAuthorization: z.boolean(),
+ hasHeaders: z.boolean(),
+ protocol: z.string(),
+ toolFilter: z.unknown().optional(),
+ url: z.string(),
+ })
+ .strict();
+
+const hook = source.extend({ eventNames: z.array(z.string()), slug: z.string() }).strict();
+
+const sandbox = source
+ .extend({
+ backendKind: z.string().optional(),
+ description: z.string().optional(),
+ hasBootstrap: z.boolean(),
+ hasOnSession: z.boolean(),
+ revalidationKey: z.string().optional(),
+ sourceHash: z.string().optional(),
+ })
+ .strict();
+
+const subagent = entry
+ .extend({
+ configResolver: dynamicResolver.optional(),
+ description: z.string().optional(),
+ entryPath: z.string(),
+ nodeId: z.string(),
+ parentNodeId: z.string(),
+ rootPath: z.string(),
+ summary: z
+ .object({
+ channels: z.number(),
+ connections: z.number(),
+ hooks: z.number(),
+ instructions: z.number(),
+ schedules: z.number(),
+ skills: z.number(),
+ tools: z.number(),
+ })
+ .strict(),
+ })
+ .strict();
+
+const remoteAgent = entry
+ .extend({
+ description: z.string(),
+ nodeId: z.string(),
+ parentNodeId: z.string(),
+ url: z.string().optional(),
+ })
+ .strict();
+
+const kernelEffect = z
+ .object({
+ action: z.enum(["subagent-call", "task-update", "task-cancel"]).optional(),
+ audience: z.array(
+ z.enum([
+ "root-session",
+ "delegated-task-child",
+ "requires-request-input",
+ "requires-loadable-skill",
+ "below-subagent-depth",
+ ]),
+ ),
+ kind: z.enum(["request-input", "dispatch", "provider-tool"]),
+ sourceId: z.string(),
+ })
+ .strict();
+
+const compositionDiagnostic = z
+ .object({
+ kind: z.enum(["disabled", "shadowed"]),
+ logicalPath: z.string(),
+ owner,
+ sourceId: z.string(),
+ winnerSourceId: z.string().optional(),
+ })
+ .strict();
+
+const workflow = z.discriminatedUnion("enabled", [
+ z.object({ enabled: z.literal(false), toolName: z.string() }).strict(),
+ z.object({ enabled: z.literal(true), source, toolName: z.string() }).strict(),
+]);
+
+/** Runtime contract for the authoritative `/eve/v1/info` v3 response. */
+export const AgentInfoResultSchema = z
+ .object({
+ agent: z
+ .object({
+ agentRoot: z.string(),
+ appRoot: z.string(),
+ config: source.extend({ binding }).strict(),
+ description: z.string().optional(),
+ model: agentModel,
+ name: z.string(),
+ nodeId: z.string(),
+ outputSchema: z.unknown().optional(),
+ })
+ .strict(),
+ capabilities: z.object({ devRoutes: z.boolean() }).strict(),
+ channels: z
+ .object({ routes: z.array(channelRoute), shadowed: z.array(shadowedChannelRoute) })
+ .strict(),
+ composition: z
+ .object({
+ disabled: z.array(compositionDiagnostic),
+ shadowed: z.array(compositionDiagnostic),
+ })
+ .strict(),
+ connections: z.array(connection),
+ diagnostics: z.object({ discoveryErrors: z.number(), discoveryWarnings: z.number() }).strict(),
+ hooks: z.array(hook),
+ instructions: z
+ .object({ dynamic: z.array(dynamicResolver), static: z.array(instructions) })
+ .strict(),
+ instrumentation: source.optional(),
+ kernelEffects: z.array(kernelEffect),
+ kind: z.literal("eve-agent-info"),
+ mode: z.enum(["development", "production"]),
+ remoteAgents: z.object({ entries: z.array(remoteAgent), total: z.number() }).strict(),
+ sandbox,
+ schedules: z.array(schedule),
+ skills: z.object({ dynamic: z.array(dynamicResolver), static: z.array(skill) }).strict(),
+ subagents: z.object({ local: z.array(subagent), total: z.number() }).strict(),
+ tools: z.object({ dynamic: z.array(dynamicResolver), static: z.array(tool) }).strict(),
+ version: z.literal(3),
+ workflow,
+ workspace: z.object({ resourceRoot: z.unknown(), rootEntries: z.array(z.string()) }).strict(),
+ })
+ .strict()
+ .superRefine((value, context) => {
+ const assertUnique = <Entry>(
+ entries: readonly Entry[],
+ identity: (entry: Entry) => string,
+ path: readonly (string | number)[],
+ ) => {
+ const seen = new Set<string>();
+ entries.forEach((entry, index) => {
+ const key = identity(entry);
+ if (seen.has(key)) {
+ context.addIssue({
+ code: "custom",
+ message: `Duplicate public identity "${key}".`,
+ path: [...path, index],
+ });
+ }
+ seen.add(key);
+ });
+ };
+ const assertTotal = (
+ total: number,
+ entries: readonly unknown[],
+ path: readonly (string | number)[],
+ ) => {
+ if (!Number.isSafeInteger(total) || total < 0 || total !== entries.length) {
+ context.addIssue({
+ code: "custom",
+ message: `Expected total ${entries.length}, received ${total}.`,
+ path: [...path],
+ });
+ }
+ };
+
+ assertUnique(value.tools.static, (entry) => entry.name, ["tools", "static"]);
+ assertUnique(value.tools.dynamic, (entry) => entry.slug, ["tools", "dynamic"]);
+ assertUnique(value.skills.static, (entry) => entry.name, ["skills", "static"]);
+ assertUnique(value.skills.dynamic, (entry) => entry.slug, ["skills", "dynamic"]);
+ assertUnique(value.instructions.static, (entry) => entry.name, ["instructions", "static"]);
+ assertUnique(value.instructions.dynamic, (entry) => entry.slug, ["instructions", "dynamic"]);
+ assertUnique(value.schedules, (entry) => entry.name, ["schedules"]);
+ assertUnique(value.connections, (entry) => entry.connectionName, ["connections"]);
+ assertUnique(value.hooks, (entry) => entry.slug, ["hooks"]);
+ assertUnique(
+ value.channels.routes,
+ (entry) => `${entry.method} ${normalizeRoutePattern(entry.urlPath)}`,
+ ["channels", "routes"],
+ );
+ assertUnique(value.subagents.local, (entry) => entry.nodeId, ["subagents", "local"]);
+ assertUnique(value.remoteAgents.entries, (entry) => entry.nodeId, ["remoteAgents", "entries"]);
+ assertTotal(value.subagents.total, value.subagents.local, ["subagents", "total"]);
+ assertTotal(value.remoteAgents.total, value.remoteAgents.entries, ["remoteAgents", "total"]);
+
+ const boundSources: ReadonlyArray<
+ readonly [ParsedAgentInfoSource, readonly (string | number)[]]
+ > = [
+ [value.agent.config, ["agent", "config"]],
+ ...(value.agent.model.source === undefined
+ ? []
+ : ([[value.agent.model.source, ["agent", "model", "source"]]] as const)),
+ ...(value.agent.model.routing.kind === "dynamic"
+ ? ([
+ [value.agent.model.routing.resolver, ["agent", "model", "routing", "resolver"]],
+ ] as const)
+ : []),
+ ...value.channels.routes.map(
+ (entry, index) => [entry, ["channels", "routes", index]] as const,
+ ),
+ ...value.connections.map((entry, index) => [entry, ["connections", index]] as const),
+ ...value.hooks.map((entry, index) => [entry, ["hooks", index]] as const),
+ ...value.instructions.dynamic.map(
+ (entry, index) => [entry, ["instructions", "dynamic", index]] as const,
+ ),
+ ...value.instructions.static.map(
+ (entry, index) => [entry, ["instructions", "static", index]] as const,
+ ),
+ ...(value.instrumentation === undefined
+ ? []
+ : ([[value.instrumentation, ["instrumentation"]]] as const)),
+ ...value.remoteAgents.entries.map(
+ (entry, index) => [entry, ["remoteAgents", "entries", index]] as const,
+ ),
+ ...value.schedules.map((entry, index) => [entry, ["schedules", index]] as const),
+ ...value.skills.dynamic.map((entry, index) => [entry, ["skills", "dynamic", index]] as const),
+ ...value.skills.static.map((entry, index) => [entry, ["skills", "static", index]] as const),
+ ...value.subagents.local.flatMap((entry, index) =>
+ entry.configResolver === undefined
+ ? []
+ : ([[entry.configResolver, ["subagents", "local", index, "configResolver"]]] as const),
+ ),
+ ...value.tools.dynamic.map((entry, index) => [entry, ["tools", "dynamic", index]] as const),
+ ...value.tools.static.map((entry, index) => [entry, ["tools", "static", index]] as const),
+ ...(value.workflow.enabled
+ ? ([[value.workflow.source, ["workflow", "source"]]] as const)
+ : []),
+ [value.sandbox, ["sandbox"]],
+ ];
+ for (const [entry, path] of boundSources) {
+ if (entry.sourceKind === "module" && entry.binding === undefined) {
+ context.addIssue({
+ code: "custom",
+ message: "Module source is missing its compiled binding.",
+ path: [...path, "binding"],
+ });
+ continue;
+ }
+ if (entry.sourceKind !== "module" && entry.binding !== undefined) {
+ context.addIssue({
+ code: "custom",
+ message: `${entry.sourceKind} source cannot carry a module binding.`,
+ path: [...path, "binding"],
+ });
+ continue;
+ }
+ if (entry.binding === undefined) continue;
+ if (entry.binding.logicalPath !== entry.logicalPath) {
+ context.addIssue({
+ code: "custom",
+ message: "Source and binding logical paths do not match.",
+ path: [...path, "binding", "logicalPath"],
+ });
+ }
+ if (JSON.stringify(entry.binding.owner) !== JSON.stringify(entry.owner)) {
+ context.addIssue({
+ code: "custom",
+ message: "Source and binding owners do not match.",
+ path: [...path, "binding", "owner"],
+ });
+ }
+ }
+ });
+
+function normalizeRoutePattern(path: string): string {
+ return path
+ .replace(/^\/+|\/+$/g, "")
+ .split("/")
+ .map((segment) => (segment.startsWith(":") || /^\[[^\]]+\]$/.test(segment) ? ":" : segment))
+ .join("/");
+}
type ReadonlyDeep<T> = T extends readonly (infer Item)[]
? readonly ReadonlyDeep<Item>[]
@@ -221,10 +463,10 @@ type ReadonlyDeep<T> = T extends readonly (infer Item)[]
? { readonly [Key in keyof T]: ReadonlyDeep<T[Key]> }
: T;
+export type AgentInfoResult = ReadonlyDeep<z.output<typeof AgentInfoResultSchema>>;
export type AgentInfoSource = ReadonlyDeep<z.output<typeof source>>;
export type AgentInfoEntry = ReadonlyDeep<z.output<typeof entry>>;
export type AgentInfoToolEntry = ReadonlyDeep<z.output<typeof tool>>;
-export type AgentInfoFrameworkToolEntry = ReadonlyDeep<z.output<typeof frameworkTool>>;
export type AgentInfoDynamicResolverEntry = ReadonlyDeep<z.output<typeof dynamicResolver>>;
export type AgentInfoTools = AgentInfoResult["tools"];
export type AgentInfoSkillEntry = ReadonlyDeep<z.output<typeof skill>>;
@@ -232,10 +474,9 @@ export type AgentInfoInstructionsEntry = ReadonlyDeep<z.output<typeof instructio
export type AgentInfoInstructions = AgentInfoResult["instructions"];
export type AgentInfoScheduleEntry = ReadonlyDeep<z.output<typeof schedule>>;
export type AgentInfoSubagentEntry = ReadonlyDeep<z.output<typeof subagent>>;
-export type AgentInfoChannelEntry = ReadonlyDeep<z.output<typeof channel>>;
-export type AgentInfoFrameworkChannelEntry = ReadonlyDeep<z.output<typeof frameworkChannel>>;
+export type AgentInfoRemoteAgentEntry = ReadonlyDeep<z.output<typeof remoteAgent>>;
+export type AgentInfoChannelEntry = ReadonlyDeep<z.output<typeof channelRoute>>;
export type AgentInfoChannels = AgentInfoResult["channels"];
export type AgentInfoConnectionEntry = ReadonlyDeep<z.output<typeof connection>>;
export type AgentInfoHookEntry = ReadonlyDeep<z.output<typeof hook>>;
export type AgentInfoSandboxEntry = ReadonlyDeep<z.output<typeof sandbox>>;
-export type AgentInfoResult = ReadonlyDeep<z.output<typeof AgentInfoResultSchema>>;
diff --git a/packages/eve/src/client/client.test.ts b/packages/eve/src/client/client.test.ts
index f0c6fe337..70a8069ff 100644
--- a/packages/eve/src/client/client.test.ts
+++ b/packages/eve/src/client/client.test.ts
@@ -3,42 +3,34 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { AgentInfoResponseError } from "#client/agent-info-error.js";
import { Client } from "#client/client.js";
import { ClientError } from "#client/client-error.js";
-import type { AgentInfoResult } from "#client/types.js";
+import { HealthResponseError } from "#client/health-response-error.js";
+import { createTestAgentInfoResult } from "#internal/testing/agent-info-fixture.js";
import { resolveTestVercelTarget } from "#internal/testing/verified-vercel-target.js";
import { resolveRemoteDevelopmentClientOptions } from "#services/dev-client/client-options.js";
import { createDevelopmentCredentialGate } from "#services/dev-client/credential-gate.js";
-const AGENT_INFO: AgentInfoResult = {
- agent: {
- agentRoot: "/tmp/weather-agent/agent",
- appRoot: "/tmp/weather-agent",
- model: { id: "openai/gpt-5.5", routing: { kind: "gateway", target: "openai" } },
- name: "Weather Agent",
- },
- capabilities: { devRoutes: true },
- channels: { authored: [], available: [], disabledFramework: [], framework: [] },
- connections: [],
- diagnostics: { discoveryErrors: 0, discoveryWarnings: 0 },
- hooks: [],
- instructions: { dynamic: [], static: [] },
- kind: "eve-agent-info",
- mode: "development",
- sandbox: null,
- schedules: [],
- skills: { dynamic: [], static: [] },
- subagents: { local: [], total: 0 },
- tools: {
- authored: [],
- available: [],
- disabledFramework: [],
- dynamic: [],
- framework: [],
- reserved: [],
- },
- version: 2,
- workflow: { enabled: false, toolName: "Workflow" },
- workspace: { resourceRoot: null, rootEntries: [] },
-};
+const AGENT_INFO = createTestAgentInfoResult({
+ agentRoot: "/tmp/weather-agent/agent",
+ appRoot: "/tmp/weather-agent",
+ name: "Weather Agent",
+});
+
+function testBinding(
+ logicalPath: string,
+ owner:
+ | { readonly kind: "application" }
+ | { readonly feature: string; readonly kind: "framework" },
+) {
+ return {
+ backing: {
+ externalDependencies: [],
+ kind: "filesystem" as const,
+ sourcePath: `/tmp/weather-agent/agent/${logicalPath}`,
+ },
+ logicalPath,
+ owner,
+ };
+}
afterEach(() => {
vi.restoreAllMocks();
@@ -46,6 +38,16 @@ afterEach(() => {
});
describe("Client request policy", () => {
+ it("rejects malformed health payloads", async () => {
+ vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(
+ Response.json({ ok: true, status: "ready", workflowId: "wf", extra: true }),
+ );
+
+ const client = new Client({ host: "https://eve.test" });
+
+ await expect(client.health()).rejects.toThrow(HealthResponseError);
+ });
+
it("includes host query parameters on every agent request", async () => {
const fetchMock = vi
.spyOn(globalThis, "fetch")
@@ -187,18 +189,20 @@ describe("Client request policy", () => {
});
it("accepts a tool whose undefined output schema was omitted during JSON serialization", async () => {
+ const owner = { feature: "eve:defaults", kind: "framework" as const };
const toolWithoutOutputSchema = {
+ binding: testBinding("tools/web_search.ts", owner),
description: "Search the web",
hasAuth: false,
hasExecute: false,
hasModelOutputProjection: false,
hasOutputSchema: false,
inputSchema: null,
- logicalPath: "eve:framework/web-search",
+ logicalPath: "tools/web_search.ts",
name: "web_search",
- origin: "framework",
- replacesFrameworkTool: false,
+ owner,
requiresApproval: false,
+ sourceId: "eve:defaults:tools/web_search.ts",
sourceKind: "module",
};
vi.spyOn(globalThis, "fetch").mockResolvedValue(
@@ -206,7 +210,7 @@ describe("Client request policy", () => {
...AGENT_INFO,
tools: {
...AGENT_INFO.tools,
- available: [toolWithoutOutputSchema],
+ static: [toolWithoutOutputSchema],
},
}),
);
@@ -214,22 +218,119 @@ describe("Client request policy", () => {
const info = await client.info();
- expect(info.tools.available[0]).toMatchObject({
+ expect(info.tools.static[0]).toMatchObject({
hasOutputSchema: false,
name: "web_search",
});
- expect(info.tools.available[0]).not.toHaveProperty("outputSchema");
+ expect(info.tools.static[0]).not.toHaveProperty("outputSchema");
});
- it("returns the parsed agent info payload", async () => {
+ it("rejects unknown fields in the agent info payload", async () => {
vi.spyOn(globalThis, "fetch").mockResolvedValue(
Response.json({ ...AGENT_INFO, ignoredByClient: true }),
);
const client = new Client({ host: "https://eve.test" });
- const info = await client.info();
+ await expect(client.info()).rejects.toThrow(AgentInfoResponseError);
+ });
+
+ it("rejects duplicate public identities in the agent info payload", async () => {
+ const owner = { kind: "application" as const };
+ const tool = {
+ binding: testBinding("tools/weather.ts", owner),
+ description: "Gets weather.",
+ hasAuth: false,
+ hasExecute: true,
+ hasModelOutputProjection: false,
+ hasOutputSchema: false,
+ inputSchema: { type: "object" },
+ logicalPath: "tools/weather.ts",
+ name: "weather",
+ owner,
+ requiresApproval: false,
+ sourceId: "tools/weather.ts",
+ sourceKind: "module",
+ };
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ Response.json({
+ ...AGENT_INFO,
+ tools: {
+ ...AGENT_INFO.tools,
+ static: [
+ tool,
+ {
+ ...tool,
+ binding: testBinding("tools/forecast.ts", owner),
+ logicalPath: "tools/forecast.ts",
+ sourceId: "tools/forecast.ts",
+ },
+ ],
+ },
+ }),
+ );
+ const client = new Client({ host: "https://eve.test" });
+
+ await expect(client.info()).rejects.toThrow(AgentInfoResponseError);
+ });
+
+ it("rejects normalized channel-route collisions in the agent info payload", async () => {
+ const owner = { kind: "application" as const };
+ const route = {
+ binding: testBinding("channels/users.ts", owner),
+ logicalPath: "channels/users.ts",
+ method: "GET" as const,
+ name: "users",
+ owner,
+ sourceId: "channels/users.ts",
+ sourceKind: "module",
+ urlPath: "/users/:id",
+ };
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ Response.json({
+ ...AGENT_INFO,
+ channels: {
+ ...AGENT_INFO.channels,
+ routes: [
+ route,
+ {
+ ...route,
+ binding: testBinding("channels/profiles.ts", owner),
+ logicalPath: "channels/profiles.ts",
+ name: "profiles",
+ sourceId: "channels/profiles.ts",
+ urlPath: "/users/[profile]",
+ },
+ ],
+ },
+ }),
+ );
+ const client = new Client({ host: "https://eve.test" });
+
+ await expect(client.info()).rejects.toThrow(AgentInfoResponseError);
+ });
+
+ it("rejects source provenance that disagrees with its compiled binding", async () => {
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ Response.json({
+ ...AGENT_INFO,
+ sandbox: {
+ ...AGENT_INFO.sandbox,
+ binding: { ...AGENT_INFO.sandbox.binding, logicalPath: "sandbox/other.ts" },
+ },
+ }),
+ );
+ const client = new Client({ host: "https://eve.test" });
- expect(info).not.toHaveProperty("ignoredByClient");
+ await expect(client.info()).rejects.toThrow(AgentInfoResponseError);
+ });
+
+ it("rejects collection totals that disagree with their entries", async () => {
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ Response.json({ ...AGENT_INFO, subagents: { local: [], total: 1 } }),
+ );
+ const client = new Client({ host: "https://eve.test" });
+
+ await expect(client.info()).rejects.toThrow(AgentInfoResponseError);
});
it("rejects a non-Eve response from the agent info route", async () => {
diff --git a/packages/eve/src/client/client.ts b/packages/eve/src/client/client.ts
index ae178dc35..2c52c4fbf 100644
--- a/packages/eve/src/client/client.ts
+++ b/packages/eve/src/client/client.ts
@@ -1,5 +1,7 @@
import { EVE_HEALTH_ROUTE_PATH, EVE_INFO_ROUTE_PATH } from "#protocol/routes.js";
import { AgentInfoResponseError } from "#client/agent-info-error.js";
+import { HealthResponseError } from "#client/health-response-error.js";
+import { HealthResultSchema } from "#client/health-schema.js";
import { encodeBasicCredentials } from "#internal/http/basic-auth.js";
import { AgentInfoResultSchema } from "#client/agent-info-schema.js";
import { ClientError } from "#client/client-error.js";
@@ -58,7 +60,23 @@ export class Client {
throw new ClientError(response.status, body, response.headers);
}
- return (await response.json()) as HealthResult;
+ let payload: unknown;
+ try {
+ payload = await response.json();
+ } catch {
+ throw new HealthResponseError();
+ }
+
+ const result = HealthResultSchema.safeParse(payload);
+ if (!result.success) {
+ throw new HealthResponseError(
+ result.error.issues.slice(0, 5).map((issue) => {
+ const path = issue.path.join(".");
+ return path.length === 0 ? issue.message : `${path}: ${issue.message}`;
+ }),
+ );
+ }
+ return result.data;
}
/**
diff --git a/packages/eve/src/client/health-response-error.ts b/packages/eve/src/client/health-response-error.ts
new file mode 100644
index 000000000..3d8f2467f
--- /dev/null
+++ b/packages/eve/src/client/health-response-error.ts
@@ -0,0 +1,11 @@
+/** A successful health request returned an unusable payload. */
+export class HealthResponseError extends Error {
+ readonly issues: readonly string[];
+
+ constructor(issues: readonly string[] = []) {
+ const detail = issues.length === 0 ? "" : ` (${issues.join("; ")})`;
+ super(`The server returned an unrecognized eve health response.${detail}`);
+ this.name = "HealthResponseError";
+ this.issues = issues;
+ }
+}
diff --git a/packages/eve/src/client/health-schema.ts b/packages/eve/src/client/health-schema.ts
new file mode 100644
index 000000000..9eb61abb3
--- /dev/null
+++ b/packages/eve/src/client/health-schema.ts
@@ -0,0 +1,11 @@
+import { z } from "#compiled/zod/index.js";
+
+export const HealthResultSchema = z
+ .object({
+ ok: z.literal(true),
+ status: z.literal("ready"),
+ workflowId: z.string().min(1),
+ })
+ .strict();
+
+export type HealthResult = z.infer<typeof HealthResultSchema>;
diff --git a/packages/eve/src/client/index.ts b/packages/eve/src/client/index.ts
index 505c46807..894fc6340 100644
--- a/packages/eve/src/client/index.ts
+++ b/packages/eve/src/client/index.ts
@@ -5,6 +5,9 @@
export { EveAgentStore } from "#client/eve-agent-store.js";
export { Client } from "#client/client.js";
export { AgentInfoResponseError } from "#client/agent-info-error.js";
+export { AgentInfoResultSchema } from "#client/agent-info-schema.js";
+export { HealthResponseError } from "#client/health-response-error.js";
+export { HealthResultSchema } from "#client/health-schema.js";
export { ClientError } from "#client/client-error.js";
export { defaultMessageReducer } from "#client/message-reducer.js";
export { createDataUrlFilePart, createTextWithFileContent } from "#client/file-parts.js";
@@ -30,12 +33,11 @@ export type {
AgentInfoChannels,
AgentInfoConnectionEntry,
AgentInfoDynamicResolverEntry,
- AgentInfoFrameworkChannelEntry,
- AgentInfoFrameworkToolEntry,
AgentInfoHookEntry,
AgentInfoInstructions,
AgentInfoInstructionsEntry,
AgentInfoResult,
+ AgentInfoRemoteAgentEntry,
AgentInfoSandboxEntry,
AgentInfoScheduleEntry,
AgentInfoSkillEntry,
@@ -137,12 +139,7 @@ export type {
export { isCurrentTurnBoundaryEvent, isTurnFailureEvent } from "#protocol/message.js";
-export type {
- InputOption,
- InputRequest,
- InputRequestKind,
- InputResponse,
-} from "#runtime/input/types.js";
+export type { InputOption, InputRequest, InputRequestKind, InputResponse } from "#shared/input.js";
export {
inputOptionSchema,
inputRequestKindSchema,
@@ -152,6 +149,6 @@ export {
isInputResponse,
parseInputResponse,
parseInputResponses,
-} from "#runtime/input/types.js";
+} from "#shared/input.js";
export { resolveTextToResponse, resolveTextToResponses } from "#channel/resolve-text.js";
diff --git a/packages/eve/src/client/message-action-parts.ts b/packages/eve/src/client/message-action-parts.ts
index 14d21fa55..27c95a5c2 100644
--- a/packages/eve/src/client/message-action-parts.ts
+++ b/packages/eve/src/client/message-action-parts.ts
@@ -1,5 +1,5 @@
-import type { RuntimeActionRequest, RuntimeActionResult } from "#runtime/actions/types.js";
-import type { InputRequest } from "#runtime/input/types.js";
+import type { RuntimeActionRequest, RuntimeActionResult } from "#shared/action-types.js";
+import type { InputRequest } from "#shared/input.js";
import type {
EveDynamicToolPart,
EveMessageInputRequest,
diff --git a/packages/eve/src/client/message-reducer-types.ts b/packages/eve/src/client/message-reducer-types.ts
index 34d1be798..2fa6e34a8 100644
--- a/packages/eve/src/client/message-reducer-types.ts
+++ b/packages/eve/src/client/message-reducer-types.ts
@@ -1,4 +1,4 @@
-import type { InputRequest, InputResponse } from "#runtime/input/types.js";
+import type { InputRequest, InputResponse } from "#shared/input.js";
import type { AuthorizationOutcome } from "#protocol/message.js";
/**
diff --git a/packages/eve/src/client/message-reducer.ts b/packages/eve/src/client/message-reducer.ts
index 0c7616568..d3ab55254 100644
--- a/packages/eve/src/client/message-reducer.ts
+++ b/packages/eve/src/client/message-reducer.ts
@@ -20,7 +20,7 @@ import {
stringifyUnknown,
toMessageInputRequest,
} from "#client/message-action-parts.js";
-import type { InputResponse } from "#runtime/input/types.js";
+import type { InputResponse } from "#shared/input.js";
import type {
AuthorizationCompletedStreamEvent,
InputResolution,
diff --git a/packages/eve/src/client/reducer.ts b/packages/eve/src/client/reducer.ts
index 1318cb588..529368613 100644
--- a/packages/eve/src/client/reducer.ts
+++ b/packages/eve/src/client/reducer.ts
@@ -1,5 +1,5 @@
import type { MessageStreamEvent } from "#protocol/message.js";
-import type { InputResponse } from "#runtime/input/types.js";
+import type { InputResponse } from "#shared/input.js";
/**
* Client-side reducer event emitted before eve confirms a submitted user
diff --git a/packages/eve/src/client/session-utils.ts b/packages/eve/src/client/session-utils.ts
index 7878003e6..e72d5b1e6 100644
--- a/packages/eve/src/client/session-utils.ts
+++ b/packages/eve/src/client/session-utils.ts
@@ -5,7 +5,7 @@ import type {
UnstampedMessageStreamEvent,
} from "#protocol/message.js";
import { isCurrentTurnBoundaryEvent, isTurnFailureEvent } from "#protocol/message.js";
-import type { InputRequest } from "#runtime/input/types.js";
+import type { InputRequest } from "#shared/input.js";
/** A connection authorization challenge that remains unresolved at a turn boundary. */
export interface PendingAuthorization {
diff --git a/packages/eve/src/client/session.ts b/packages/eve/src/client/session.ts
index 3099112b5..f43df30bc 100644
--- a/packages/eve/src/client/session.ts
+++ b/packages/eve/src/client/session.ts
@@ -12,7 +12,7 @@ import {
} from "#client/session-controls.js";
import { serializeOutputSchema } from "#shared/tool-schema.js";
import { createClientUrl } from "#client/url.js";
-import type { InputResponse } from "#runtime/input/types.js";
+import type { InputResponse } from "#shared/input.js";
import type {
CancelSessionResult,
ClearResult,
diff --git a/packages/eve/src/client/types.ts b/packages/eve/src/client/types.ts
index 8de10cf37..ec140d4cb 100644
--- a/packages/eve/src/client/types.ts
+++ b/packages/eve/src/client/types.ts
@@ -7,8 +7,9 @@ import type { ClearStatus } from "#protocol/clear-session.js";
import type { CompactStatus } from "#protocol/compact-session.js";
import type { ResetStatus } from "#protocol/reset-session.js";
import type { TurnPolicy } from "#channel/types.js";
-import type { InputRequest, InputResponse } from "#runtime/input/types.js";
+import type { InputRequest, InputResponse } from "#shared/input.js";
import type { JsonObject } from "#shared/json.js";
+export type { HealthResult } from "#client/health-schema.js";
export type {
AgentInfoChannelEntry,
@@ -16,12 +17,11 @@ export type {
AgentInfoConnectionEntry,
AgentInfoDynamicResolverEntry,
AgentInfoEntry,
- AgentInfoFrameworkChannelEntry,
- AgentInfoFrameworkToolEntry,
AgentInfoHookEntry,
AgentInfoInstructions,
AgentInfoInstructionsEntry,
AgentInfoResult,
+ AgentInfoRemoteAgentEntry,
AgentInfoSandboxEntry,
AgentInfoScheduleEntry,
AgentInfoSkillEntry,
@@ -308,12 +308,6 @@ export interface MessageResult<TOutput = unknown> {
/**
* Response from the health endpoint.
*/
-export interface HealthResult {
- readonly ok: true;
- readonly status: "ready";
- readonly workflowId: string;
-}
-
/**
* Serializable cursor for one fixed, ID-addressed client session.
*/
diff --git a/packages/eve/src/compiler/artifacts.ts b/packages/eve/src/compiler/artifacts.ts
index 6efa715b7..4bdc3887f 100644
--- a/packages/eve/src/compiler/artifacts.ts
+++ b/packages/eve/src/compiler/artifacts.ts
@@ -2,12 +2,23 @@ import { createHash } from "node:crypto";
import { mkdir, writeFile } from "node:fs/promises";
import { join, relative, resolve } from "node:path";
-import type { DiscoverDiagnostic, DiscoverDiagnosticsSummary } from "#discover/diagnostics.js";
-import { summarizeDiscoverDiagnostics } from "#discover/diagnostics.js";
+import { z } from "#compiled/zod/index.js";
+import {
+ discoverDiagnosticsSummarySchema,
+ type DiscoverDiagnostic,
+ type DiscoverDiagnosticsSummary,
+} from "#discover/diagnostics.js";
import { normalizeLogicalPath } from "#discover/filesystem.js";
import type { AgentSourceManifest } from "#discover/manifest.js";
import { resolveInstalledPackageInfo } from "#internal/application/package.js";
import type { CompiledAgentManifest } from "#compiler/manifest.js";
+import { ROOT_COMPILED_AGENT_NODE_ID } from "#compiler/manifest.js";
+import {
+ compilerDiagnosticSchema,
+ projectDiscoverDiagnostic,
+ summarizeCompilerDiagnostics,
+ type CompilerDiagnostic,
+} from "#compiler/diagnostics.js";
import { createCompiledModuleMapSource } from "#compiler/module-map.js";
import { compileAgentManifest } from "#compiler/normalize-manifest.js";
import { materializeWorkspaceResources } from "#compiler/workspace-resources.js";
@@ -15,12 +26,12 @@ import { materializeWorkspaceResources } from "#compiler/workspace-resources.js"
/**
* Stable diagnostics artifact kind emitted by the compiler.
*/
-const DISCOVERY_DIAGNOSTICS_ARTIFACT_KIND = "eve-discovery-diagnostics";
+export const COMPILER_DIAGNOSTICS_ARTIFACT_KIND = "eve-compiler-diagnostics";
/**
* Current diagnostics artifact schema version.
*/
-const DISCOVERY_DIAGNOSTICS_ARTIFACT_VERSION = 1;
+export const COMPILER_DIAGNOSTICS_ARTIFACT_VERSION = 2;
/**
* Stable compile metadata artifact kind emitted by the compiler.
@@ -30,7 +41,7 @@ export const COMPILE_METADATA_KIND = "eve-compile-metadata";
/**
* Current compile metadata schema version.
*/
-export const COMPILE_METADATA_VERSION = 5;
+export const COMPILE_METADATA_VERSION = 6;
/**
* Structured paths for compiler-owned artifacts under `.eve/`.
@@ -47,15 +58,24 @@ export interface CompilerArtifactPaths {
}
/**
- * Machine-readable discovery diagnostics artifact written by the compiler.
+ * Machine-readable compiler diagnostics artifact written by the compiler.
*/
-interface DiscoveryDiagnosticsArtifact {
- diagnostics: DiscoverDiagnostic[];
- kind: typeof DISCOVERY_DIAGNOSTICS_ARTIFACT_KIND;
+export interface CompilerDiagnosticsArtifact {
+ diagnostics: CompilerDiagnostic[];
+ kind: typeof COMPILER_DIAGNOSTICS_ARTIFACT_KIND;
summary: DiscoverDiagnosticsSummary;
- version: typeof DISCOVERY_DIAGNOSTICS_ARTIFACT_VERSION;
+ version: typeof COMPILER_DIAGNOSTICS_ARTIFACT_VERSION;
}
+export const compilerDiagnosticsArtifactSchema = z
+ .object({
+ diagnostics: z.array(compilerDiagnosticSchema),
+ kind: z.literal(COMPILER_DIAGNOSTICS_ARTIFACT_KIND),
+ summary: discoverDiagnosticsSummarySchema,
+ version: z.literal(COMPILER_DIAGNOSTICS_ARTIFACT_VERSION),
+ })
+ .strict();
+
/**
* One artifact digest recorded in compile metadata.
*/
@@ -69,6 +89,7 @@ interface CompileArtifactDigest {
*/
export interface CompileMetadata {
compile: {
+ manifest: CompileArtifactDigest;
moduleMap: CompileArtifactDigest;
};
discovery: {
@@ -92,7 +113,7 @@ export interface CompilerArtifactLocations {
}
/**
- * Input for writing compiler-owned discovery artifacts.
+ * Input for writing compiler-owned source and diagnostic artifacts.
*/
interface WriteCompilerArtifactsInput {
appRoot: string;
@@ -106,7 +127,7 @@ interface WriteCompilerArtifactsInput {
*/
interface WriteCompilerArtifactsResult {
compiledManifest: CompiledAgentManifest;
- diagnosticsArtifact: DiscoveryDiagnosticsArtifact;
+ diagnosticsArtifact: CompilerDiagnosticsArtifact;
metadata: CompileMetadata;
moduleMapSource: string;
paths: CompilerArtifactPaths;
@@ -139,16 +160,16 @@ function resolveCompilerArtifactPathsAt(
}
/**
- * Creates the diagnostics artifact written alongside the source manifest.
+ * Creates the compiler diagnostics artifact written alongside the source manifest.
*/
-function createDiscoveryDiagnosticsArtifact(
- diagnostics: readonly DiscoverDiagnostic[],
-): DiscoveryDiagnosticsArtifact {
+function createCompilerDiagnosticsArtifact(
+ diagnostics: readonly CompilerDiagnostic[],
+): CompilerDiagnosticsArtifact {
return {
diagnostics: [...diagnostics],
- kind: DISCOVERY_DIAGNOSTICS_ARTIFACT_KIND,
- summary: summarizeDiscoverDiagnostics(diagnostics),
- version: DISCOVERY_DIAGNOSTICS_ARTIFACT_VERSION,
+ kind: COMPILER_DIAGNOSTICS_ARTIFACT_KIND,
+ summary: summarizeCompilerDiagnostics(diagnostics),
+ version: COMPILER_DIAGNOSTICS_ARTIFACT_VERSION,
};
}
@@ -158,6 +179,7 @@ function createDiscoveryDiagnosticsArtifact(
*/
export function createCompileMetadata(input: {
appRoot: string;
+ compiledManifestJson: string;
diagnosticsArtifactJson: string;
diagnosticsSummary: DiscoverDiagnosticsSummary;
discoveryManifestJson: string;
@@ -165,12 +187,17 @@ export function createCompileMetadata(input: {
paths: CompilerArtifactPaths;
}): CompileMetadata {
const generator = resolveInstalledPackageInfo();
- const manifestHash = createContentHash(input.discoveryManifestJson);
+ const compiledManifestHash = createContentHash(input.compiledManifestJson);
+ const discoveryManifestHash = createContentHash(input.discoveryManifestJson);
const diagnosticsHash = createContentHash(input.diagnosticsArtifactJson);
const moduleMapHash = createContentHash(input.moduleMapSource);
return {
compile: {
+ manifest: {
+ path: toArtifactRelativePath(input.appRoot, input.paths.compiledManifestPath),
+ sha256: compiledManifestHash,
+ },
moduleMap: {
path: toArtifactRelativePath(input.appRoot, input.paths.moduleMapPath),
sha256: moduleMapHash,
@@ -183,9 +210,11 @@ export function createCompileMetadata(input: {
},
manifest: {
path: toArtifactRelativePath(input.appRoot, input.paths.discoveryManifestPath),
- sha256: manifestHash,
+ sha256: discoveryManifestHash,
},
- sourceGraphHash: createContentHash(`${manifestHash}:${diagnosticsHash}:${moduleMapHash}`),
+ sourceGraphHash: createContentHash(
+ `${compiledManifestHash}:${discoveryManifestHash}:${diagnosticsHash}:${moduleMapHash}`,
+ ),
summary: input.diagnosticsSummary,
},
generator: {
@@ -207,11 +236,14 @@ export async function writeCompilerArtifacts(
input.appRoot,
input.artifactLocations.publishedRoot,
);
- const diagnosticsArtifact = createDiscoveryDiagnosticsArtifact(input.diagnostics);
+ const diagnostics = input.diagnostics.map((diagnostic) =>
+ projectDiscoverDiagnostic(diagnostic, ROOT_COMPILED_AGENT_NODE_ID),
+ );
const compiledManifest = await materializeWorkspaceResources({
compileDirectoryPath: paths.compileDirectoryPath,
- manifest: await compileAgentManifest(input.manifest),
+ manifest: await compileAgentManifest(input.manifest, { diagnostics }),
});
+ const diagnosticsArtifact = createCompilerDiagnosticsArtifact(diagnostics);
const compiledManifestJson = serializeArtifactJson(compiledManifest);
const discoveryManifestJson = serializeArtifactJson(input.manifest);
const diagnosticsArtifactJson = serializeArtifactJson(diagnosticsArtifact);
@@ -221,6 +253,7 @@ export async function writeCompilerArtifacts(
});
const metadata = createCompileMetadata({
appRoot: input.appRoot,
+ compiledManifestJson,
diagnosticsArtifactJson,
diagnosticsSummary: diagnosticsArtifact.summary,
discoveryManifestJson,
diff --git a/packages/eve/src/compiler/channel-route-plan.ts b/packages/eve/src/compiler/channel-route-plan.ts
new file mode 100644
index 000000000..dc68946a7
--- /dev/null
+++ b/packages/eve/src/compiler/channel-route-plan.ts
@@ -0,0 +1,166 @@
+import type {
+ CompiledChannelDefinition,
+ CompiledChannelPreflightDefinition,
+ CompiledChannelRoutePlan,
+ CompiledShadowedChannelRoute,
+} from "#compiler/manifest.js";
+import type { AgentSourceDescriptor, CompiledModuleBinding } from "#compiler/source-graph.js";
+import {
+ createChannelRouteShadowedDiagnostic,
+ type CompilerDiagnostic,
+} from "#compiler/diagnostics.js";
+import { HOST_HTTP_INVENTORY } from "#framework/host-inventory.js";
+
+export function createCompiledChannelRoutePlan(input: {
+ readonly bindings: Readonly<Record<string, CompiledModuleBinding>>;
+ readonly channels: readonly CompiledChannelDefinition[];
+ readonly diagnostics?: CompilerDiagnostic[];
+ readonly nodeId: string;
+ readonly sources: Readonly<Record<string, AgentSourceDescriptor>>;
+}): CompiledChannelRoutePlan {
+ const effective: CompiledChannelDefinition[] = [];
+ const shadowed: CompiledShadowedChannelRoute[] = [];
+
+ for (const channel of input.channels) {
+ const reserved = HOST_HTTP_INVENTORY.find((host) => routesOverlap(channel, host));
+ if (reserved !== undefined) {
+ throw new Error(
+ `compile/reserved-route-collision: ${channel.method} ${channel.urlPath} overlaps reserved ${reserved.method} ${reserved.path}.`,
+ );
+ }
+ const winner = effective.find((candidate) => routesOverlap(channel, candidate));
+ if (winner === undefined) {
+ effective.push(channel);
+ continue;
+ }
+ if (winner.sourceId === channel.sourceId) {
+ throw new Error(
+ `compile/channel-route-duplicate: source "${channel.sourceId}" emits ${channel.method} ${channel.urlPath} more than once.`,
+ );
+ }
+ const binding = input.bindings[channel.sourceId];
+ const source = input.sources[channel.sourceId];
+ const winnerSource = input.sources[winner.sourceId];
+ if (binding === undefined || source === undefined || winnerSource === undefined) {
+ throw new Error(`Channel source "${channel.sourceId}" has no compiled binding.`);
+ }
+ shadowed.push({
+ method: channel.method,
+ source,
+ urlPath: channel.urlPath,
+ winnerSourceId: winner.sourceId,
+ });
+ input.diagnostics?.push(
+ createChannelRouteShadowedDiagnostic({
+ loser: source,
+ method: channel.method,
+ nodeId: input.nodeId,
+ urlPath: channel.urlPath,
+ winner: winnerSource,
+ }),
+ );
+ }
+
+ const preflight = derivePreflights(effective);
+ return {
+ effective: Object.freeze(effective),
+ preflight: Object.freeze(preflight),
+ shadowed: Object.freeze(shadowed),
+ };
+}
+
+function derivePreflights(
+ effective: readonly CompiledChannelDefinition[],
+): CompiledChannelPreflightDefinition[] {
+ const corsRoutes = effective.filter(
+ (channel) => channel.method !== "WEBSOCKET" && channel.cors !== undefined,
+ );
+ for (const [index, route] of corsRoutes.entries()) {
+ const conflict = corsRoutes
+ .slice(index + 1)
+ .find(
+ (candidate) =>
+ routePatternsOverlap(route.urlPath, candidate.urlPath) &&
+ JSON.stringify(route.cors) !== JSON.stringify(candidate.cors),
+ );
+ if (conflict !== undefined) {
+ throw new Error(
+ `compile/channel-cors-conflict: overlapping routes at "${route.urlPath}" and "${conflict.urlPath}" declare different CORS policies.`,
+ );
+ }
+ }
+
+ const byPath = new Map<string, CompiledChannelDefinition[]>();
+ for (const channel of corsRoutes) {
+ const identity = normalizeRoutePattern(channel.urlPath);
+ const routes = byPath.get(identity) ?? [];
+ routes.push(channel);
+ byPath.set(identity, routes);
+ }
+ const preflights: CompiledChannelPreflightDefinition[] = [];
+ for (const routes of byPath.values()) {
+ const first = routes[0]!;
+ const normalizedCors = JSON.stringify(first.cors);
+ if (routes.some((route) => JSON.stringify(route.cors) !== normalizedCors)) {
+ throw new Error(
+ `compile/channel-cors-conflict: routes at "${first.urlPath}" declare different CORS policies.`,
+ );
+ }
+ if (
+ effective.some(
+ (route) => route.method === "OPTIONS" && routePatternsOverlap(route.urlPath, first.urlPath),
+ )
+ ) {
+ throw new Error(
+ `compile/channel-preflight-collision: explicit OPTIONS route overlaps generated preflight at "${first.urlPath}".`,
+ );
+ }
+ preflights.push({
+ cors: first.cors!,
+ method: "OPTIONS",
+ sourceIds: [...new Set(routes.map((route) => route.sourceId))],
+ urlPath: first.urlPath,
+ });
+ }
+ return preflights;
+}
+
+function routesOverlap(
+ left: { readonly method: string; readonly urlPath: string },
+ right: { readonly method: string; readonly path?: string; readonly urlPath?: string },
+): boolean {
+ return (
+ methodsOverlap(left.method, right.method) &&
+ routePatternsOverlap(left.urlPath, right.path ?? right.urlPath!)
+ );
+}
+
+function methodsOverlap(left: string, right: string): boolean {
+ return left === "ALL" || right === "ALL" || left === right;
+}
+
+function routePatternsOverlap(left: string, right: string): boolean {
+ const leftSegments = splitRoute(left);
+ const rightSegments = splitRoute(right);
+ if (leftSegments.length !== rightSegments.length) return false;
+ return leftSegments.every(
+ (segment, index) =>
+ isParameter(segment) ||
+ isParameter(rightSegments[index]!) ||
+ segment === rightSegments[index],
+ );
+}
+
+function normalizeRoutePattern(path: string): string {
+ return splitRoute(path)
+ .map((segment) => (isParameter(segment) ? ":" : segment))
+ .join("/");
+}
+
+function splitRoute(path: string): string[] {
+ return path.replace(/^\/+|\/+$/g, "").split("/");
+}
+
+function isParameter(segment: string): boolean {
+ return segment.startsWith(":") || /^\[[^\]]+\]$/.test(segment);
+}
diff --git a/packages/eve/src/compiler/compile-agent.ts b/packages/eve/src/compiler/compile-agent.ts
index 0b4d61489..dfbb2de59 100644
--- a/packages/eve/src/compiler/compile-agent.ts
+++ b/packages/eve/src/compiler/compile-agent.ts
@@ -1,7 +1,6 @@
import { join } from "node:path";
import type { DiscoverDiagnostic } from "#discover/diagnostics.js";
-import { hasDiscoverErrors, summarizeDiscoverDiagnostics } from "#discover/diagnostics.js";
import { discoverAgent } from "#discover/discover-agent.js";
import type { ResolvedDiscoveryProject } from "#discover/project.js";
import { resolveDiscoveryProject } from "#discover/project.js";
@@ -14,6 +13,7 @@ import {
writeCompilerArtifacts,
} from "#compiler/artifacts.js";
import type { CompiledAgentManifest } from "#compiler/manifest.js";
+import { summarizeCompilerDiagnostics, type CompilerDiagnostic } from "#compiler/diagnostics.js";
/**
* Input for compiling the current authored agent into framework-owned
@@ -33,7 +33,7 @@ export interface CompileAgentInput {
* artifacts.
*/
export interface CompileAgentResult {
- diagnostics: DiscoverDiagnostic[];
+ diagnostics: CompilerDiagnostic[];
manifest: CompiledAgentManifest;
metadata: CompileMetadata;
paths: CompilerArtifactPaths;
@@ -131,7 +131,7 @@ async function writeAgentCompilation(
});
return {
- diagnostics: discovered.diagnostics,
+ diagnostics: writtenArtifacts.diagnosticsArtifact.diagnostics,
manifest: writtenArtifacts.compiledManifest,
metadata: writtenArtifacts.metadata,
paths: writtenArtifacts.paths,
@@ -143,7 +143,7 @@ function finishAgentCompilation(
result: CompileAgentResult,
createError: (result: CompileAgentResult) => CompileAgentError,
): CompileAgentResult {
- if (hasDiscoverErrors(result.diagnostics)) {
+ if (result.diagnostics.some((diagnostic) => diagnostic.severity === "error")) {
throw createError(result);
}
@@ -152,7 +152,7 @@ function finishAgentCompilation(
return result;
}
-function reportDiscoverWarnings(diagnostics: readonly DiscoverDiagnostic[]): void {
+function reportDiscoverWarnings(diagnostics: readonly CompilerDiagnostic[]): void {
const warnings = diagnostics.filter((diagnostic) => diagnostic.severity === "warning");
if (warnings.length === 0) {
@@ -160,12 +160,14 @@ function reportDiscoverWarnings(diagnostics: readonly DiscoverDiagnostic[]): voi
}
for (const warning of warnings) {
- console.warn(`Warning [${warning.code}]: ${warning.message}\n source: ${warning.sourcePath}`);
+ console.warn(
+ `Warning [${warning.code}]: ${warning.message}\n source: ${formatDiagnosticSources(warning)}`,
+ );
}
}
-function formatCompileAgentErrorLines(diagnostics: readonly DiscoverDiagnostic[]): string[] {
- const summary = summarizeDiscoverDiagnostics(diagnostics);
+function formatCompileAgentErrorLines(diagnostics: readonly CompilerDiagnostic[]): string[] {
+ const summary = summarizeCompilerDiagnostics(diagnostics);
const lines: string[] = [
`Discovery failed with ${summary.errors} error(s) and ${summary.warnings} warning(s).`,
];
@@ -178,12 +180,18 @@ function formatCompileAgentErrorLines(diagnostics: readonly DiscoverDiagnostic[]
for (const diagnostic of diagnostics) {
lines.push(`- ${formatDiagnosticSeverity(diagnostic.severity)}: ${diagnostic.message}`);
- lines.push(` source: ${diagnostic.sourcePath}`);
+ lines.push(` source: ${formatDiagnosticSources(diagnostic)}`);
}
return lines;
}
+function formatDiagnosticSources(diagnostic: CompilerDiagnostic): string {
+ return diagnostic.sources
+ .map((source) => source.sourcePath ?? source.logicalPath ?? source.sourceId ?? source.nodeId)
+ .join(", ");
+}
+
function formatDiagnosticSeverity(severity: DiscoverDiagnostic["severity"]): string {
return severity === "error" ? "Error" : "Warning";
}
diff --git a/packages/eve/src/compiler/compile-from-memory.test.ts b/packages/eve/src/compiler/compile-from-memory.test.ts
index 90a648895..836a5310f 100644
--- a/packages/eve/src/compiler/compile-from-memory.test.ts
+++ b/packages/eve/src/compiler/compile-from-memory.test.ts
@@ -1,87 +1,127 @@
import { describe, expect, it } from "vitest";
+import { compileFromMemory } from "#compiler/compile-from-memory.js";
import {
COMPILED_AGENT_MANIFEST_KIND,
COMPILED_AGENT_MANIFEST_VERSION,
compiledAgentManifestSchema,
ROOT_COMPILED_AGENT_NODE_ID,
} from "#compiler/manifest.js";
-import { compileFromMemory } from "#compiler/compile-from-memory.js";
+import { validateCompiledModuleMap } from "#compiler/validate-artifact.js";
+import { defineInstrumentation } from "#public/instrumentation/index.js";
describe("compileFromMemory", () => {
- it("produces a manifest and module map with minimal input", () => {
- const { manifest, moduleMap } = compileFromMemory({ model: "openai/gpt-5.4" });
-
- expect(manifest.kind).toBe(COMPILED_AGENT_MANIFEST_KIND);
- expect(manifest.version).toBe(COMPILED_AGENT_MANIFEST_VERSION);
- expect(manifest.config.name).toBe("memory-agent");
- expect(manifest.config.model?.id).toBe("openai/gpt-5.4");
- expect(manifest.tools).toEqual([]);
- expect(manifest.skills).toEqual([]);
- expect(manifest.subagents).toEqual([]);
- expect(moduleMap.nodes[ROOT_COMPILED_AGENT_NODE_ID]?.modules).toEqual({});
- });
-
- it("honours descriptor overrides for name, model, and roots", () => {
- const { manifest } = compileFromMemory({
- name: "custom-agent",
- model: "mock/custom",
- appRoot: "/app",
- agentRoot: "/app/agent",
+ it("uses the ordinary source compiler for defaults and authored config", async () => {
+ const { manifest, moduleMap } = await compileFromMemory({
+ model: "openai/gpt-5.4",
});
- expect(manifest.config.name).toBe("custom-agent");
- expect(manifest.config.model?.id).toBe("mock/custom");
- expect(manifest.appRoot).toBe("/app");
- expect(manifest.agentRoot).toBe("/app/agent");
+ expect(manifest).toMatchObject({
+ kind: COMPILED_AGENT_MANIFEST_KIND,
+ version: COMPILED_AGENT_MANIFEST_VERSION,
+ config: {
+ model: { id: "openai/gpt-5.4" },
+ name: "memory-agent",
+ source: { logicalPath: "agent.ts", sourceKind: "module" },
+ },
+ sandbox: { logicalPath: "sandbox.ts" },
+ });
+ expect(manifest.bindings[manifest.config.source.sourceId]?.owner).toEqual({
+ kind: "application",
+ });
+ expect(manifest.sourceComposition.entries).toContainEqual(
+ expect.objectContaining({
+ kind: "shadowed",
+ source: expect.objectContaining({
+ logicalPath: "agent.ts",
+ owner: expect.objectContaining({ kind: "framework" }),
+ }),
+ winnerSourceId: manifest.config.source.sourceId,
+ }),
+ );
+ expect(moduleMap.nodes[ROOT_COMPILED_AGENT_NODE_ID]).toBeDefined();
+ expect(() => validateCompiledModuleMap(manifest, moduleMap)).not.toThrow();
});
- it("projects authored tools into the manifest and module map", () => {
- const { manifest, moduleMap } = compileFromMemory({
+ it("projects authored tools and skills as selected programmatic modules", async () => {
+ const execute = () => ({ ok: true });
+ const { manifest, moduleMap } = await compileFromMemory({
model: "openai/gpt-5.4",
tools: [
- { name: "weather", description: "Gets the weather.", inputSchema: { kind: "object" } },
- { name: "echo", outputSchema: { type: "string" } },
+ {
+ name: "weather",
+ description: "Gets the weather.",
+ execute,
+ inputSchema: { type: "object" },
+ outputSchema: { type: "object" },
+ },
],
+ skills: [{ name: "greetings", description: "Say hi", markdown: "# greet\n" }],
});
- expect(manifest.tools).toHaveLength(2);
- const [weather, echo] = manifest.tools;
- expect(weather?.name).toBe("weather");
- expect(weather?.description).toBe("Gets the weather.");
- expect(weather?.inputSchema).toEqual({ kind: "object" });
- expect(weather?.logicalPath).toBe("tools/weather.ts");
- expect(echo?.description).toBe("echo test tool.");
- expect(echo?.outputSchema).toEqual({ type: "string" });
+ const weather = manifest.tools.find((tool) => tool.name === "weather");
+ expect(weather).toMatchObject({
+ description: "Gets the weather.",
+ hasExecute: true,
+ logicalPath: "tools/weather.ts",
+ outputSchema: { type: "object" },
+ });
+ expect(manifest.bindings[weather!.sourceId]?.owner).toEqual({ kind: "application" });
+ expect(moduleMap.nodes[ROOT_COMPILED_AGENT_NODE_ID]?.modules[weather!.sourceId]).toBeDefined();
- const rootModules = moduleMap.nodes[ROOT_COMPILED_AGENT_NODE_ID]?.modules ?? {};
- expect(Object.keys(rootModules)).toHaveLength(2);
- expect(rootModules[weather?.sourceId ?? ""]).toBeDefined();
+ const skill = manifest.skills.find((entry) => entry.name === "greetings");
+ expect(skill).toMatchObject({
+ description: "Say hi",
+ logicalPath: "skills/greetings.ts",
+ markdown: "# greet\n",
+ name: "greetings",
+ sourceKind: "module",
+ });
+ expect(skill).not.toHaveProperty("owner");
+ expect(manifest.bindings[skill!.sourceId]?.owner).toEqual({ kind: "application" });
});
- it("projects markdown skills into the manifest", () => {
- const { manifest } = compileFromMemory({
+ it("preserves roots and passes the serialized v42 schema", async () => {
+ const { manifest } = await compileFromMemory({
+ agentRoot: "/app/agent",
+ appRoot: "/app",
model: "openai/gpt-5.4",
- skills: [{ name: "greetings", description: "Say hi", markdown: "# greet\n" }],
+ name: "custom-agent",
});
- expect(manifest.skills).toHaveLength(1);
- const [skill] = manifest.skills;
- expect(skill?.name).toBe("greetings");
- expect(skill?.description).toBe("Say hi");
- expect(skill?.markdown).toBe("# greet\n");
- expect(skill?.sourceKind).toBe("markdown");
- expect(skill?.logicalPath).toBe("skills/greetings.md");
+ expect(manifest).toMatchObject({
+ agentRoot: "/app/agent",
+ appRoot: "/app",
+ config: { name: "custom-agent" },
+ });
+ expect(
+ compiledAgentManifestSchema.safeParse(JSON.parse(JSON.stringify(manifest))).success,
+ ).toBe(true);
});
- it("produces a manifest that passes the versioned schema validation", () => {
- const { manifest } = compileFromMemory({
+ it("binds instrumentation as an ordinary programmatic module slot", async () => {
+ const instrumentation = defineInstrumentation({ recordInputs: true });
+ const { manifest, moduleMap } = await compileFromMemory({
model: "openai/gpt-5.4",
- tools: [{ name: "ping" }],
- skills: [{ name: "hello", description: "Greet" }],
+ modules: [
+ {
+ loadNamespace: async () => ({ default: instrumentation }),
+ logicalPath: "instrumentation.ts",
+ },
+ ],
});
- const parsed = compiledAgentManifestSchema.safeParse(manifest);
- expect(parsed.success).toBe(true);
+ expect(manifest.instrumentation).toMatchObject({
+ logicalPath: "instrumentation.ts",
+ sourceKind: "module",
+ });
+ const sourceId = manifest.instrumentation!.sourceId;
+ expect(manifest.bindings[sourceId]).toMatchObject({
+ backing: { kind: "programmatic", moduleId: "instrumentation.ts" },
+ owner: { kind: "application" },
+ });
+ expect(moduleMap.nodes[ROOT_COMPILED_AGENT_NODE_ID]?.modules[sourceId]?.default).toBe(
+ instrumentation,
+ );
});
});
diff --git a/packages/eve/src/compiler/compile-from-memory.ts b/packages/eve/src/compiler/compile-from-memory.ts
index da9ccfaf9..47aa6f89c 100644
--- a/packages/eve/src/compiler/compile-from-memory.ts
+++ b/packages/eve/src/compiler/compile-from-memory.ts
@@ -1,159 +1,130 @@
+import { randomUUID } from "node:crypto";
+
import type { JsonObject } from "#shared/json.js";
-import { classifyModelRouting } from "#internal/classify-model-routing.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 type { CompiledAgentManifest } from "#compiler/manifest.js";
+import {
+ createProgrammaticCompiledModuleMap,
+ type CompiledModuleMap,
+} from "#compiler/module-map.js";
+import { compileAgentManifest } from "#compiler/normalize-manifest.js";
import {
- type CompiledAgentDefinition,
- type CompiledAgentManifest,
- type CompiledSkillDefinition,
- type CompiledToolDefinition,
- createCompiledAgentManifest,
- ROOT_COMPILED_AGENT_NODE_ID,
-} from "#compiler/manifest.js";
-import type { CompiledModuleMap } from "#compiler/module-map.js";
+ createAgentSourceRegistry,
+ defineProgrammaticAgentSource,
+ type ProgrammaticAgentModule,
+} from "#compiler/source-graph.js";
+import { frameworkAgentSourceRegistry } from "#framework/sources/registry.js";
-/**
- * Declarative description of an in-memory authored agent used by the test
- * harness.
- */
export interface CompileFromMemoryInput {
- /** Identifies this synthetic agent in manifest metadata and error output. */
+ readonly agent?: AgentDefinition;
readonly name?: string;
- /**
- * Virtual app root used in manifest paths. The directory does not need to
- * exist on disk; discovery never runs against it.
- */
readonly appRoot?: string;
- /**
- * Virtual agent root. Defaults to `<appRoot>/agent`.
- */
readonly agentRoot?: string;
- /** Model id assigned to the synthetic agent config. */
readonly model: string;
- /** Session token limits assigned to the synthetic agent config. */
readonly limits?: {
readonly maxInputTokensPerSession?: number | false;
readonly maxOutputTokensPerSession?: number | false;
readonly sessionTimeoutMs?: number | false;
};
readonly outputSchema?: JsonObject;
- /**
- * Authored tools to project into the compiled manifest and module map.
- *
- * Each entry corresponds to a single module-backed tool. The harness does
- * not load the tool module from disk — its runtime behaviour is injected
- * separately via the AppHarness `mockTool` API.
- */
+ readonly revision?: string;
+ readonly modules?: readonly ProgrammaticAgentModule[];
readonly tools?: readonly CompileFromMemoryToolInput[];
- /**
- * Authored markdown skills to include in the manifest.
- */
readonly skills?: readonly CompileFromMemorySkillInput[];
}
-/**
- * Per-tool descriptor entry consumed by {@link compileFromMemory}.
- */
export interface CompileFromMemoryToolInput {
- /** Model-facing tool name; must match the slot name in the module map. */
readonly name: string;
- /** Human-readable description propagated to the compiled manifest. */
readonly description?: string;
- /**
- * JSON-schema-like object describing the tool input. Passed through as-is
- * (lowered to `null` when omitted).
- */
readonly inputSchema?: JsonObject | null;
- /** JSON-schema-like object describing the tool output. */
readonly outputSchema?: JsonObject;
+ readonly execute?: ToolDefinition["execute"];
+ readonly approval?: ToolDefinition["approval"];
+ readonly toModelOutput?: ToolDefinition["toModelOutput"];
}
-/**
- * Per-skill descriptor entry consumed by {@link compileFromMemory}.
- */
export interface CompileFromMemorySkillInput {
readonly name: string;
readonly description: string;
readonly markdown?: string;
}
-/**
- * Result produced by {@link compileFromMemory}. Shaped to match the subset
- * of `CompileAgentResult` that the runtime and harness need.
- */
export interface CompileFromMemoryResult {
readonly manifest: CompiledAgentManifest;
readonly moduleMap: CompiledModuleMap;
}
-/**
- * Builds a compiled manifest and matching module map directly from an
- * in-memory descriptor, bypassing discovery and bundling entirely.
- *
- * Intended for integration tests that want to exercise runtime behaviour
- * without the cost of real compilation. Production code must continue to
- * use {@link compileAgent}.
- */
-export function compileFromMemory(input: CompileFromMemoryInput): CompileFromMemoryResult {
+/** Compiles a synthetic application by registering one ordinary programmatic source. */
+export async function compileFromMemory(
+ input: CompileFromMemoryInput,
+): Promise<CompileFromMemoryResult> {
const appRoot = input.appRoot ?? "/virtual/eve-memory-app";
const agentRoot = input.agentRoot ?? `${appRoot}/agent`;
- const agentName = input.name ?? "memory-agent";
-
- const config: CompiledAgentDefinition = {
- model: { id: input.model, routing: classifyModelRouting(input.model) },
- name: agentName,
- };
- if (input.limits !== undefined) {
- config.limits = input.limits;
- }
- if (input.outputSchema !== undefined) {
- config.outputSchema = input.outputSchema;
- }
-
- const tools: CompiledToolDefinition[] = (input.tools ?? []).map((toolInput) => ({
- description: toolInput.description ?? `${toolInput.name} test tool.`,
- inputSchema: toolInput.inputSchema ?? null,
- logicalPath: `tools/${toolInput.name}.ts`,
- name: toolInput.name,
- outputSchema: toolInput.outputSchema,
- sourceId: createMemorySourceId(`tools/${toolInput.name}.ts`),
- sourceKind: "module",
- }));
-
- const skills: CompiledSkillDefinition[] = (input.skills ?? []).map((skillInput) => ({
- description: skillInput.description,
- logicalPath: `skills/${skillInput.name}.md`,
- markdown: skillInput.markdown ?? `# ${skillInput.name}\n`,
- name: skillInput.name,
- sourceId: createMemorySourceId(`skills/${skillInput.name}.md`),
- sourceKind: "markdown",
- }));
-
- const manifest = createCompiledAgentManifest({
+ const sourceId = `memory:${input.name ?? "memory-agent"}`;
+ const config = defineAgent(
+ input.agent ?? {
+ limits: input.limits,
+ model: input.model,
+ outputSchema: input.outputSchema,
+ },
+ );
+ const modules = [
+ {
+ loadNamespace: async () => ({ default: config }),
+ logicalPath: "agent.ts",
+ },
+ ...(input.modules ?? []),
+ ...(input.tools ?? []).map((tool) => ({
+ loadNamespace: async () => ({ default: createMemoryToolDefinition(tool) }),
+ logicalPath: `tools/${tool.name}.ts`,
+ })),
+ ...(input.skills ?? []).map((skill) => ({
+ loadNamespace: async () => ({
+ default: defineSkill({
+ description: skill.description,
+ markdown: skill.markdown ?? `# ${skill.name}\n`,
+ }),
+ }),
+ logicalPath: `skills/${skill.name}.ts`,
+ })),
+ ];
+ const registry = createAgentSourceRegistry([
+ {
+ applyTo: "root",
+ source: defineProgrammaticAgentSource({
+ id: sourceId,
+ modules,
+ revision: input.revision ?? `memory-generation:${randomUUID()}`,
+ }),
+ },
+ ]);
+ const discovered = createAgentSourceManifest({
+ agentId: input.name ?? "memory-agent",
agentRoot,
appRoot,
- config,
- skills,
- tools,
});
-
- const moduleMap: CompiledModuleMap = {
- nodes: {
- [ROOT_COMPILED_AGENT_NODE_ID]: {
- modules: Object.fromEntries(
- tools.map((tool) => [tool.sourceId, Object.freeze({}) as Record<string, unknown>]),
- ),
- },
- },
- };
-
- return {
- manifest,
- moduleMap,
- };
+ const manifest = await compileAgentManifest(discovered, { sourceRegistries: [registry] });
+ const moduleMap = await createProgrammaticCompiledModuleMap(manifest, [
+ frameworkAgentSourceRegistry,
+ registry,
+ ]);
+ return { manifest, moduleMap };
}
-function createMemorySourceId(logicalPath: string): string {
- // A deterministic, stable id per logical path. The runtime only requires
- // these to be unique within the module map, so a prefix + the path is
- // sufficient — no hashing needed.
- return `memory::${logicalPath}`;
+function createMemoryToolDefinition(input: CompileFromMemoryToolInput): ToolDefinition {
+ return defineTool({
+ approval: input.approval,
+ description: input.description ?? `${input.name} test tool.`,
+ execute:
+ input.execute ??
+ (() => {
+ throw new Error(`Memory tool "${input.name}" has no installed executor.`);
+ }),
+ inputSchema: input.inputSchema ?? { additionalProperties: true, type: "object" },
+ outputSchema: input.outputSchema,
+ toModelOutput: input.toModelOutput,
+ });
}
diff --git a/packages/eve/src/compiler/diagnostics.ts b/packages/eve/src/compiler/diagnostics.ts
new file mode 100644
index 000000000..60f19923c
--- /dev/null
+++ b/packages/eve/src/compiler/diagnostics.ts
@@ -0,0 +1,93 @@
+import { z } from "#compiled/zod/index.js";
+
+import type { DiscoverDiagnostic, DiscoverDiagnosticsSummary } from "#discover/diagnostics.js";
+import type { AgentSourceDescriptor } from "#compiler/source-graph.js";
+
+export const compilerDiagnosticSeveritySchema = z.enum(["error", "warning"]);
+
+export const compilerDiagnosticSourceSchema = z
+ .object({
+ logicalPath: z.string().optional(),
+ nodeId: z.string().min(1),
+ sourceId: z.string().optional(),
+ sourcePath: z.string().optional(),
+ })
+ .strict()
+ .refine(
+ (source) =>
+ source.logicalPath !== undefined ||
+ source.sourceId !== undefined ||
+ source.sourcePath !== undefined,
+ "Compiler diagnostic source must identify a logical, compiled, or physical source.",
+ );
+
+export type CompilerDiagnosticSource = z.infer<typeof compilerDiagnosticSourceSchema>;
+
+export const compilerDiagnosticSchema = z
+ .object({
+ code: z.string().min(1),
+ message: z.string().min(1),
+ severity: compilerDiagnosticSeveritySchema,
+ sources: z.array(compilerDiagnosticSourceSchema).min(1).readonly(),
+ })
+ .strict();
+
+export type CompilerDiagnostic = z.infer<typeof compilerDiagnosticSchema>;
+
+export function projectDiscoverDiagnostic(
+ diagnostic: DiscoverDiagnostic,
+ nodeId: string,
+): CompilerDiagnostic {
+ return {
+ code: diagnostic.code,
+ message: diagnostic.message,
+ severity: diagnostic.severity,
+ sources: [{ nodeId, sourcePath: diagnostic.sourcePath }],
+ };
+}
+
+export function createChannelRouteShadowedDiagnostic(input: {
+ readonly loser: AgentSourceDescriptor;
+ readonly method: string;
+ readonly nodeId: string;
+ readonly urlPath: string;
+ readonly winner: AgentSourceDescriptor;
+}): CompilerDiagnostic {
+ return {
+ code: "compile/channel-route-shadowed",
+ message:
+ `${input.method} ${input.urlPath} from "${input.loser.logicalPath}" is shadowed by ` +
+ `"${input.winner.logicalPath}".`,
+ severity: "warning",
+ sources: [
+ toDiagnosticSource(input.nodeId, input.loser),
+ toDiagnosticSource(input.nodeId, input.winner),
+ ],
+ };
+}
+
+export function summarizeCompilerDiagnostics(
+ diagnostics: readonly CompilerDiagnostic[],
+): DiscoverDiagnosticsSummary {
+ let errors = 0;
+ let warnings = 0;
+ for (const diagnostic of diagnostics) {
+ if (diagnostic.severity === "error") errors += 1;
+ else warnings += 1;
+ }
+ return { errors, warnings };
+}
+
+function toDiagnosticSource(
+ nodeId: string,
+ source: AgentSourceDescriptor,
+): CompilerDiagnosticSource {
+ return {
+ logicalPath: source.logicalPath,
+ nodeId,
+ sourceId: source.sourceId,
+ ...(source.backing.kind === "filesystem" || source.backing.kind === "resource"
+ ? { sourcePath: source.backing.sourcePath }
+ : {}),
+ };
+}
diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.ts
index c99ab22d6..dd7ab7218 100644
--- a/packages/eve/src/compiler/extension-compatibility.ts
+++ b/packages/eve/src/compiler/extension-compatibility.ts
@@ -31,7 +31,7 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18],
dropped: {},
},
- channel: { current: 8, supported: [1, 2, 3, 4, 5, 6, 7, 8], 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: {} },
diff --git a/packages/eve/src/compiler/manifest.test.ts b/packages/eve/src/compiler/manifest.test.ts
index 5ad6394a4..6f566db51 100644
--- a/packages/eve/src/compiler/manifest.test.ts
+++ b/packages/eve/src/compiler/manifest.test.ts
@@ -1,305 +1,123 @@
import { describe, expect, it } from "vitest";
+import { compileFromMemory } from "#compiler/compile-from-memory.js";
import {
+ COMPILED_AGENT_MANIFEST_VERSION,
compiledAgentManifestSchema,
- createCompiledAgentResources,
- createCompiledAgentManifest,
createCompiledAgentNodeManifest,
} from "#compiler/manifest.js";
-import { classifyModelRouting } from "#internal/classify-model-routing.js";
-
-describe("compiledAgentManifestSchema", () => {
- it("accepts authored HEAD and OPTIONS channel routes", () => {
- const channel = {
- adapterKind: "mcp",
- kind: "channel" as const,
- logicalPath: "channels/mcp.ts",
- name: "mcp",
- sourceId: "channel-mcp",
- sourceKind: "module" as const,
- urlPath: "/.well-known/oauth-protected-resource",
- };
- const manifest = createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- channels: [
- { ...channel, method: "HEAD" },
- { ...channel, method: "OPTIONS" },
- ],
- config: {
- model: { id: "openai/gpt-5.5", routing: classifyModelRouting("openai/gpt-5.5") },
- name: "app",
- },
- });
-
- const parsed = compiledAgentManifestSchema.parse(manifest);
- expect(
- parsed.channels.map((entry) => (entry.kind === "channel" ? entry.method : null)),
- ).toEqual(["HEAD", "OPTIONS"]);
- });
-
- it("requires exactly one static description or dynamic resolver for each subagent", () => {
- const manifest = createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- model: { id: "openai/gpt-5.5", routing: classifyModelRouting("openai/gpt-5.5") },
- name: "app",
- },
- });
- const subagent = {
- agent: createCompiledAgentNodeManifest({
- agentRoot: "/app/agent/subagents/research",
- appRoot: "/app",
- config: {
- model: { id: "openai/gpt-5.5", routing: classifyModelRouting("openai/gpt-5.5") },
- name: "research",
- },
- }),
- entryPath: "subagents/research/agent.ts",
- logicalPath: "subagents/research",
- name: "research",
- nodeId: "research",
- rootPath: "/app/agent/subagents/research",
- sourceId: "subagents/research/agent.ts",
- sourceKind: "module",
- } as const;
- const parses = (variant: Readonly<Record<string, unknown>>): boolean =>
- compiledAgentManifestSchema.safeParse({
- ...manifest,
- subagents: [{ ...subagent, ...variant }],
- }).success;
-
- expect(parses({ description: "Research requests." })).toBe(true);
- expect(
- parses({
- agent: createCompiledAgentResources({
- agentRoot: "/app/agent/subagents/research",
- appRoot: "/app",
- }),
- configResolver: {
- eventNames: ["session.started"],
- logicalPath: "agent.ts",
- sourceId: "agent.ts",
- sourceKind: "module",
- },
- }),
- ).toBe(true);
- expect(parses({})).toBe(false);
- expect(
- parses({
- description: "Research requests.",
- configResolver: {
- eventNames: ["session.started"],
- logicalPath: "agent.ts",
- sourceId: "agent.ts",
- sourceKind: "module",
- },
- }),
- ).toBe(false);
- });
-
- it("preserves reasoning configuration", () => {
- const manifest = createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- model: { id: "openai/gpt-5.5", routing: classifyModelRouting("openai/gpt-5.5") },
- name: "app",
- reasoning: "high",
- },
+import {
+ validateCompiledAgentManifest,
+ validateCompiledModuleMap,
+} from "#compiler/validate-artifact.js";
+
+describe("compiled agent manifest v42", () => {
+ it("round-trips a real compiled graph through the serialized schema", async () => {
+ const { manifest } = await compileFromMemory({
+ model: "openai/gpt-5.4",
+ tools: [{ name: "weather" }],
});
- const parsed = compiledAgentManifestSchema.parse(manifest);
-
- expect(parsed.config.reasoning).toBe("high");
+ const parsed = compiledAgentManifestSchema.parse(JSON.parse(JSON.stringify(manifest)));
+ expect(parsed.version).toBe(COMPILED_AGENT_MANIFEST_VERSION);
+ expect(() => validateCompiledAgentManifest(parsed)).not.toThrow();
});
- it("preserves runtime limits configuration", () => {
- const manifest = createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- limits: {
- maxInputTokensPerSession: 200_000,
- maxOutputTokensPerSession: 20_000,
- sessionTimeoutMs: 86_400_000,
- },
- model: { id: "openai/gpt-5.5", routing: classifyModelRouting("openai/gpt-5.5") },
- name: "app",
- },
+ it("rejects a missing required binding", async () => {
+ const { manifest } = await compileFromMemory({
+ model: "openai/gpt-5.4",
+ tools: [{ name: "weather" }],
});
+ const weather = manifest.tools.find((tool) => tool.name === "weather")!;
+ const bindings = { ...manifest.bindings };
+ delete bindings[weather.sourceId];
- const parsed = compiledAgentManifestSchema.parse(manifest);
-
- expect(parsed.config.limits).toEqual({
- maxInputTokensPerSession: 200_000,
- maxOutputTokensPerSession: 20_000,
- sessionTimeoutMs: 86_400_000,
- });
+ expect(() => validateCompiledAgentManifest({ ...manifest, bindings })).toThrow(
+ "has no compiled binding",
+ );
});
- it("rejects the removed maxSubagentDepth limit", () => {
- const manifest = createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- model: { id: "openai/gpt-5.5", routing: classifyModelRouting("openai/gpt-5.5") },
- name: "app",
- },
- });
+ it("rejects unreferenced bindings and invalid route provenance", async () => {
+ const { manifest } = await compileFromMemory({ model: "openai/gpt-5.4" });
+ const configBinding = manifest.bindings[manifest.config.source.sourceId]!;
expect(() =>
- compiledAgentManifestSchema.parse({
+ validateCompiledAgentManifest({
...manifest,
- config: { ...manifest.config, limits: { maxSubagentDepth: 4 } },
+ bindings: { ...manifest.bindings, orphan: configBinding },
}),
- ).toThrow();
- });
-
- it("rejects the removed agent-level maxSubagents limit", () => {
- const manifest = createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- model: { id: "openai/gpt-5.5", routing: classifyModelRouting("openai/gpt-5.5") },
- name: "app",
- },
- });
+ ).toThrow("is not referenced");
expect(() =>
- compiledAgentManifestSchema.parse({
+ validateCompiledAgentManifest({
...manifest,
- config: { ...manifest.config, limits: { maxSubagents: 4 } },
+ channelRoutes: {
+ ...manifest.channelRoutes,
+ shadowed: [
+ {
+ method: "GET",
+ source: {
+ backing: { kind: "resource", sourcePath: "/virtual/channels/loser.ts" },
+ layer: "application",
+ logicalPath: "channels/loser.ts",
+ owner: { kind: "application" },
+ sourceId: "loser",
+ },
+ urlPath: "/loser",
+ winnerSourceId: "missing",
+ },
+ ],
+ },
}),
- ).toThrow();
+ ).toThrow("dangling winner");
});
- it("preserves experimental Workflow tool configuration", () => {
- const manifest = createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- model: { id: "openai/gpt-5.5", routing: classifyModelRouting("openai/gpt-5.5") },
- name: "app",
- },
- workflowTool: { maxSubagents: 6 },
- });
+ it("rejects module maps whose keys diverge from total bindings", async () => {
+ const { manifest, moduleMap } = await compileFromMemory({ model: "openai/gpt-5.4" });
+ const root = moduleMap.nodes.__root__!;
- const parsed = compiledAgentManifestSchema.parse(manifest);
-
- expect(parsed.workflowTool).toEqual({ maxSubagents: 6 });
- });
-
- it("preserves web search provider configuration", () => {
- const manifest = createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- model: { id: "openai/gpt-5.5", routing: classifyModelRouting("openai/gpt-5.5") },
- name: "app",
- },
- webSearchProvider: "exa",
- });
-
- const parsed = compiledAgentManifestSchema.parse(manifest);
-
- expect(parsed.webSearchProvider).toBe("exa");
- });
-
- it("preserves dynamic model resolver source", () => {
- const manifest = createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- dynamicModel: {
- eventNames: ["session.started"],
- logicalPath: "agent.ts",
- sourceId: "agent-config",
- sourceKind: "module",
- },
- name: "app",
- },
- });
-
- const parsed = compiledAgentManifestSchema.parse(manifest);
-
- expect(parsed.config.dynamicModel).toEqual({
- eventNames: ["session.started"],
- logicalPath: "agent.ts",
- sourceId: "agent-config",
- sourceKind: "module",
- });
- expect(parsed.config.model).toBeUndefined();
- });
-
- it("rejects compiled configs with both static and dynamic models", () => {
expect(() =>
- compiledAgentManifestSchema.parse({
- ...createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- model: { id: "openai/gpt-5.5", routing: classifyModelRouting("openai/gpt-5.5") },
- name: "app",
- },
- }),
- config: {
- dynamicModel: {
- eventNames: ["session.started"],
- logicalPath: "agent.ts",
- sourceId: "agent-config",
- sourceKind: "module",
- },
- model: { id: "openai/gpt-5.5", routing: classifyModelRouting("openai/gpt-5.5") },
- name: "app",
- },
+ validateCompiledModuleMap(manifest, {
+ nodes: { ...moduleMap.nodes, __root__: { modules: { ...root.modules, orphan: {} } } },
}),
- ).toThrow();
- });
-
- it("preserves uncapped (false) session token limits", () => {
- const manifest = createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- limits: {
- maxInputTokensPerSession: false,
- maxOutputTokensPerSession: false,
- sessionTimeoutMs: false,
- },
- model: { id: "openai/gpt-5.5", routing: classifyModelRouting("openai/gpt-5.5") },
- name: "app",
- },
- });
-
- const parsed = compiledAgentManifestSchema.parse(manifest);
-
- expect(parsed.config.limits).toEqual({
- maxInputTokensPerSession: false,
- maxOutputTokensPerSession: false,
- sessionTimeoutMs: false,
- });
+ ).toThrow("do not match its bindings");
});
- it("accepts compiled workflow world configuration", () => {
- const manifest = createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- model: { id: "openai/gpt-5.5", routing: classifyModelRouting("openai/gpt-5.5") },
- name: "app",
- experimental: {
- workflow: {
- world: "@acme/eve-world",
- },
- },
- },
+ it("rejects a disconnected subagent parent cycle", async () => {
+ const { manifest } = await compileFromMemory({ model: "openai/gpt-5.4" });
+ const agent = createCompiledAgentNodeManifest(manifest);
+ const parent = {
+ agent,
+ backing: { kind: "resource" as const, sourcePath: "/virtual/subagents/parent" },
+ description: "Parent agent.",
+ entryPath: "/virtual/subagents/parent",
+ logicalPath: "subagents/parent",
+ name: "parent",
+ nodeId: "parent-node",
+ owner: { kind: "application" as const },
+ parentNodeId: "child-node",
+ rootPath: "/virtual/subagents/parent",
+ sourceId: "parent-source",
+ sourceKind: "module" as const,
+ };
+ const child = {
+ ...parent,
+ description: "Child agent.",
+ entryPath: "/virtual/subagents/parent/subagents/child",
+ logicalPath: "subagents/child",
+ name: "child",
+ nodeId: "child-node",
+ parentNodeId: parent.nodeId,
+ rootPath: "/virtual/subagents/parent/subagents/child",
+ sourceId: "child-source",
+ };
+ const corrupted = compiledAgentManifestSchema.parse({
+ ...manifest,
+ subagents: [parent, child],
});
- const parsed = compiledAgentManifestSchema.safeParse(manifest);
-
- expect(parsed.success).toBe(true);
- expect(manifest.config.experimental?.workflow).toEqual({ world: "@acme/eve-world" });
+ expect(() => validateCompiledAgentManifest(corrupted)).toThrow(
+ "subagent graph contains a cycle",
+ );
});
});
diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.ts
index e6d32d2de..bb3769fe4 100644
--- a/packages/eve/src/compiler/manifest.ts
+++ b/packages/eve/src/compiler/manifest.ts
@@ -29,6 +29,17 @@ import type {
} from "#shared/agent-definition.js";
import type { InternalToolDefinition } from "#shared/tool-definition.js";
import type { WebSearchProvider } from "#shared/web-search.js";
+import type {
+ AgentModuleBacking,
+ AgentSourceComposition,
+ AgentSourceDescriptor,
+ AgentSourceOwner,
+ CompiledModuleBinding,
+} from "#compiler/source-graph.js";
+import {
+ validateCompiledAgentManifest,
+ validateCompiledAgentResources,
+} from "#compiler/validate-artifact.js";
/**
* Stable manifest kind emitted by the compiler for runtime loading.
@@ -43,12 +54,12 @@ export const ROOT_COMPILED_AGENT_NODE_ID = "__root__";
/**
* Current compiled manifest schema version.
*/
-export const COMPILED_AGENT_MANIFEST_VERSION = 41;
+export const COMPILED_AGENT_MANIFEST_VERSION = 42;
/**
* Compiled channel entry preserved in the compiled manifest.
*/
-export type CompiledChannelEntry = CompiledChannelDefinition | DisabledCompiledChannelEntry;
+export type CompiledChannelEntry = CompiledChannelDefinition;
/**
* Active compiled channel entry — backed by an authored `Channel` module.
@@ -83,10 +94,24 @@ export interface CompiledChannelDefinition {
* Disabled compiled channel entry — marker that an authored file at this
* slug exported `disableRoute()` to remove the matching framework default.
*/
-interface DisabledCompiledChannelEntry {
- readonly kind: "disabled";
- readonly name: string;
- readonly logicalPath: string;
+export interface CompiledChannelPreflightDefinition {
+ readonly cors: NormalizedChannelCorsOptions;
+ readonly method: "OPTIONS";
+ readonly sourceIds: readonly string[];
+ readonly urlPath: string;
+}
+
+export interface CompiledShadowedChannelRoute {
+ readonly method: ChannelRouteMethod;
+ readonly source: AgentSourceDescriptor;
+ readonly urlPath: string;
+ readonly winnerSourceId: string;
+}
+
+export interface CompiledChannelRoutePlan {
+ readonly effective: readonly CompiledChannelDefinition[];
+ readonly preflight: readonly CompiledChannelPreflightDefinition[];
+ readonly shadowed: readonly CompiledShadowedChannelRoute[];
}
/**
@@ -127,6 +152,7 @@ type CompiledAgentCompactionDefinition = Omit<InternalAgentCompactionDefinition,
*/
type CompiledAgentDefinitionBase = Omit<InternalAgentDefinition, "model" | "compaction"> & {
compaction?: CompiledAgentCompactionDefinition;
+ source: ModuleSourceRef;
};
export type CompiledAgentDefinition = CompiledAgentDefinitionBase &
@@ -146,13 +172,24 @@ export type CompiledAgentDefinition = CompiledAgentDefinitionBase &
* manifest.
*/
export type CompiledInstructionsDefinition = InternalInstructionsDefinition &
- (Omit<MarkdownSourceRef<undefined>, "definition"> | Omit<ModuleSourceRef, "exportName">);
+ (
+ | (Omit<MarkdownSourceRef<undefined>, "definition"> & {
+ readonly owner: AgentSourceOwner;
+ })
+ | Omit<ModuleSourceRef, "exportName">
+ );
/**
* Normalized authored skill preserved in the compiled manifest.
*/
export type CompiledSkillDefinition = NamedSkillDefinition &
- (Omit<MarkdownSourceRef<undefined>, "definition"> | ModuleSourceRef | SkillPackageSourceRef);
+ (
+ | (Omit<MarkdownSourceRef<undefined>, "definition"> & {
+ readonly owner: AgentSourceOwner;
+ })
+ | ModuleSourceRef
+ | (SkillPackageSourceRef & { readonly owner: AgentSourceOwner })
+ );
/**
* Normalized authored schedule preserved in the compiled manifest.
@@ -186,12 +223,17 @@ export type CompiledConnectionDefinition = z.infer<typeof compiledConnectionDefi
/**
* Normalized authored tool metadata preserved in the compiled manifest.
*/
-export type CompiledToolDefinition = InternalToolDefinition & ModuleSourceRef;
+export type CompiledToolDefinition = InternalToolDefinition &
+ ModuleSourceRef & {
+ readonly hasExecute: boolean;
+ readonly hasModelOutputProjection: boolean;
+ readonly requiresApproval: boolean;
+ };
/**
* Serializable configuration for the experimental framework `Workflow` tool.
*/
-export interface CompiledWorkflowToolDefinition {
+export interface CompiledWorkflowToolDefinition extends ModuleSourceRef {
readonly maxSubagents?: number;
}
@@ -244,6 +286,7 @@ export interface CompiledDynamicInstructionsDefinition extends ModuleSourceRef {
* resolution happens at runtime via {@link resolveHookDefinition}.
*/
export interface CompiledHookDefinition extends ModuleSourceRef {
+ readonly eventNames: readonly string[];
/**
* Path-relative slug used for diagnostics and ordering. Derived from
* the authored file's logical path
@@ -263,8 +306,11 @@ export type CompiledAgentResources = z.infer<typeof compiledAgentResourcesSchema
export type CompiledSubagentNode = Readonly<
ModuleSourceRef &
Node & {
+ backing: { readonly kind: "resource"; readonly sourcePath: string };
entryPath: string;
name: string;
+ owner: AgentSourceOwner;
+ parentNodeId: string;
rootPath: string;
} & (
| {
@@ -282,19 +328,23 @@ export type CompiledSubagentNode = Readonly<
export type { CompiledRemoteAgentNode } from "#compiler/remote-agent-node.js";
-/**
- * Parent-child edge connecting two compiled agent nodes.
- */
-export interface CompiledSubagentEdge {
- readonly childNodeId: string;
- readonly parentNodeId: string;
-}
-
/**
* Versioned compiled manifest emitted by the compiler and loaded by runtime.
*/
export type CompiledAgentManifest = z.infer<typeof compiledAgentManifestSchema>;
+const agentSourceOwnerSchema: z.ZodType<AgentSourceOwner> = z.discriminatedUnion("kind", [
+ z.object({ kind: z.literal("application") }).strict(),
+ z.object({ feature: z.string().min(1), kind: z.literal("framework") }).strict(),
+ z
+ .object({
+ kind: z.literal("extension"),
+ namespace: z.string().min(1),
+ packageName: z.string().min(1),
+ })
+ .strict(),
+]);
+
const moduleSourceRefSchema: z.ZodType<ModuleSourceRef> = z
.object({
exportName: z.string().optional(),
@@ -304,6 +354,80 @@ const moduleSourceRefSchema: z.ZodType<ModuleSourceRef> = z
})
.strict();
+const filesystemModuleBackingSchema = z
+ .object({
+ externalDependencies: z.array(z.string()).readonly(),
+ extensionScope: z.object({ namespace: z.string(), sourceRoot: z.string() }).strict().optional(),
+ kind: z.literal("filesystem"),
+ sourcePath: z.string(),
+ })
+ .strict();
+
+const programmaticModuleBackingSchema = z
+ .object({
+ kind: z.literal("programmatic"),
+ moduleId: z.string(),
+ registryId: z.string(),
+ revision: z.string(),
+ semanticRevision: z.string().optional(),
+ })
+ .strict();
+
+const resourceSourceBackingSchema = z
+ .object({ kind: z.literal("resource"), sourcePath: z.string() })
+ .strict();
+
+const agentModuleBackingSchema: z.ZodType<AgentModuleBacking> = z.discriminatedUnion("kind", [
+ filesystemModuleBackingSchema,
+ programmaticModuleBackingSchema,
+]);
+
+const compiledModuleBindingSchema: z.ZodType<CompiledModuleBinding> = z
+ .object({
+ backing: agentModuleBackingSchema,
+ logicalPath: z.string(),
+ owner: agentSourceOwnerSchema,
+ })
+ .strict();
+
+const agentSourceDescriptorSchema: z.ZodType<AgentSourceDescriptor> = z
+ .object({
+ backing: z.discriminatedUnion("kind", [
+ filesystemModuleBackingSchema,
+ programmaticModuleBackingSchema,
+ resourceSourceBackingSchema,
+ ]),
+ layer: z.enum(["framework-default", "extension-package", "extension-override", "application"]),
+ logicalPath: z.string(),
+ owner: agentSourceOwnerSchema,
+ sourceId: z.string(),
+ })
+ .strict();
+
+const agentSourceCompositionSchema: z.ZodType<AgentSourceComposition> = z
+ .object({
+ entries: z
+ .array(
+ z.discriminatedUnion("kind", [
+ z
+ .object({
+ kind: z.literal("shadowed"),
+ source: agentSourceDescriptorSchema,
+ winnerSourceId: z.string(),
+ })
+ .strict(),
+ z
+ .object({
+ kind: z.literal("disabled"),
+ source: agentSourceDescriptorSchema,
+ })
+ .strict(),
+ ]),
+ )
+ .readonly(),
+ })
+ .strict();
+
const compiledDynamicModelDefinitionSchema: z.ZodType<CompiledDynamicModelDefinition> = z
.object({
eventNames: z.array(z.string()).readonly(),
@@ -357,18 +481,31 @@ const compiledChannelDefinitionSchema = z
})
.strict();
-const disabledCompiledChannelEntrySchema = z
+const compiledChannelPreflightDefinitionSchema: z.ZodType<CompiledChannelPreflightDefinition> = z
.object({
- kind: z.literal("disabled"),
- name: z.string(),
- logicalPath: z.string(),
+ cors: compiledChannelCorsSchema,
+ method: z.literal("OPTIONS"),
+ sourceIds: z.array(z.string()).readonly(),
+ urlPath: z.string(),
})
.strict();
-const compiledChannelEntrySchema = z.union([
- compiledChannelDefinitionSchema,
- disabledCompiledChannelEntrySchema,
-]) as unknown as z.ZodType<CompiledChannelEntry>;
+const compiledShadowedChannelRouteSchema: z.ZodType<CompiledShadowedChannelRoute> = z
+ .object({
+ method: channelMethodSchema,
+ source: agentSourceDescriptorSchema,
+ urlPath: z.string(),
+ winnerSourceId: z.string(),
+ })
+ .strict();
+
+const compiledChannelRoutePlanSchema: z.ZodType<CompiledChannelRoutePlan> = z
+ .object({
+ effective: z.array(compiledChannelDefinitionSchema).readonly(),
+ preflight: z.array(compiledChannelPreflightDefinitionSchema).readonly(),
+ shadowed: z.array(compiledShadowedChannelRouteSchema).readonly(),
+ })
+ .strict();
const modelRoutingSchema = z.union([
z
@@ -431,7 +568,11 @@ const compiledAgentLimitsDefinitionSchema = z
const compiledWorkflowToolDefinitionSchema: z.ZodType<CompiledWorkflowToolDefinition> = z
.object({
+ exportName: z.string().optional(),
+ logicalPath: z.string(),
maxSubagents: z.number().int().positive().optional(),
+ sourceId: z.string(),
+ sourceKind: z.literal("module"),
})
.strict();
@@ -453,7 +594,7 @@ const compiledAgentConfigBaseFields = {
reasoning: z
.enum(["provider-default", "none", "minimal", "low", "medium", "high", "xhigh"])
.optional(),
- source: moduleSourceRefSchema.optional(),
+ source: moduleSourceRefSchema,
limits: compiledAgentLimitsDefinitionSchema.optional(),
};
@@ -472,16 +613,32 @@ const compiledAgentConfigSchema: z.ZodType<CompiledAgentDefinition> = z.union([
.strict(),
]);
-const compiledInstructionsSchema: z.ZodType<CompiledInstructionsDefinition> = z
- .object({
- content: z.string(),
- name: z.string(),
- logicalPath: z.string(),
- role: z.enum(["system", "user"]),
- sourceId: z.string(),
- sourceKind: z.union([z.literal("markdown"), z.literal("module")]),
- })
- .strict();
+const compiledInstructionsBaseFields = {
+ content: z.string(),
+ name: z.string(),
+ logicalPath: z.string(),
+ role: z.enum(["system", "user"]),
+ sourceId: z.string(),
+};
+
+const compiledInstructionsSchema: z.ZodType<CompiledInstructionsDefinition> = z.discriminatedUnion(
+ "sourceKind",
+ [
+ z
+ .object({
+ ...compiledInstructionsBaseFields,
+ owner: agentSourceOwnerSchema,
+ sourceKind: z.literal("markdown"),
+ })
+ .strict(),
+ z
+ .object({
+ ...compiledInstructionsBaseFields,
+ sourceKind: z.literal("module"),
+ })
+ .strict(),
+ ],
+);
const compiledSkillBaseFields = {
name: z.string(),
@@ -499,6 +656,7 @@ const compiledSkillSourceSchema: z.ZodType<CompiledSkillDefinition> = z.discrimi
z
.object({
...compiledSkillBaseFields,
+ owner: agentSourceOwnerSchema,
sourceKind: z.literal("markdown"),
})
.strict(),
@@ -512,6 +670,7 @@ const compiledSkillSourceSchema: z.ZodType<CompiledSkillDefinition> = z.discrimi
z
.object({
...compiledSkillBaseFields,
+ owner: agentSourceOwnerSchema,
sourceKind: z.literal("skill-package"),
skillId: z.string(),
skillFilePath: z.string(),
@@ -524,17 +683,30 @@ const compiledSkillSourceSchema: z.ZodType<CompiledSkillDefinition> = z.discrimi
],
);
-const compiledScheduleDefinitionSchema = z
- .object({
- cron: z.string(),
- hasRun: z.boolean(),
- name: z.string(),
- logicalPath: z.string(),
- markdown: z.string().optional(),
- sourceId: z.string(),
- sourceKind: z.union([z.literal("markdown"), z.literal("module")]),
- })
- .strict();
+const compiledScheduleBaseFields = {
+ cron: z.string(),
+ hasRun: z.boolean(),
+ name: z.string(),
+ logicalPath: z.string(),
+ markdown: z.string().optional(),
+ sourceId: z.string(),
+};
+
+const compiledScheduleDefinitionSchema = z.discriminatedUnion("sourceKind", [
+ z
+ .object({
+ ...compiledScheduleBaseFields,
+ owner: agentSourceOwnerSchema,
+ sourceKind: z.literal("markdown"),
+ })
+ .strict(),
+ z
+ .object({
+ ...compiledScheduleBaseFields,
+ sourceKind: z.literal("module"),
+ })
+ .strict(),
+]);
const compiledSandboxDefinitionSchema = z
.object({
@@ -616,10 +788,13 @@ const compiledToolDefinitionSchema = z
description: z.string(),
execution: z.literal("background").optional(),
exportName: z.string().optional(),
+ hasExecute: z.boolean(),
+ hasModelOutputProjection: z.boolean(),
inputSchema: jsonObjectSchema.nullable(),
logicalPath: z.string(),
name: z.string(),
outputSchema: jsonObjectSchema.optional(),
+ requiresApproval: z.boolean(),
sourceId: z.string(),
sourceKind: z.literal("module"),
})
@@ -663,6 +838,7 @@ const compiledDynamicInstructionsDefinitionSchema: z.ZodType<CompiledDynamicInst
const compiledHookDefinitionSchema: z.ZodType<CompiledHookDefinition> = z
.object({
+ eventNames: z.array(z.string()).readonly(),
exportName: z.string().optional(),
logicalPath: z.string(),
slug: z.string(),
@@ -689,10 +865,11 @@ const compiledExtensionMountSchema: z.ZodType<CompiledExtensionMount> = z
const compiledAgentResourceFields = {
agentRoot: z.string(),
appRoot: z.string(),
- channels: z.array(compiledChannelEntrySchema),
+ bindings: z.record(z.string(), compiledModuleBindingSchema),
+ channelRoutes: compiledChannelRoutePlanSchema,
connections: z.array(compiledConnectionDefinitionSchema),
diagnosticsSummary: discoverDiagnosticsSummarySchema,
- disabledFrameworkTools: z.array(z.string()).readonly(),
+ sourceComposition: agentSourceCompositionSchema,
workflowTool: compiledWorkflowToolDefinitionSchema.optional(),
webSearchProvider: z.enum(["exa", "parallel"]).optional(),
dynamicInstructions: z.array(compiledDynamicInstructionsDefinitionSchema).default([]),
@@ -700,12 +877,13 @@ const compiledAgentResourceFields = {
dynamicTools: z.array(compiledDynamicToolDefinitionSchema).default([]),
extensionMounts: z.array(compiledExtensionMountSchema).default([]),
hooks: z.array(compiledHookDefinitionSchema),
- sandbox: compiledSandboxDefinitionSchema.nullable(),
+ sandbox: compiledSandboxDefinitionSchema,
sandboxWorkspaces: z.array(compiledSandboxWorkspaceSchema),
schedules: z.array(compiledScheduleDefinitionSchema),
remoteAgents: z.array(compiledRemoteAgentNodeSchema),
skills: z.array(compiledSkillSourceSchema).readonly(),
instructions: z.array(compiledInstructionsSchema).readonly().default([]),
+ instrumentation: moduleSourceRefSchema.optional(),
tools: z.array(compiledToolDefinitionSchema),
workspaceResourceRoot: compiledWorkspaceResourceRootSchema,
};
@@ -720,10 +898,13 @@ const compiledAgentNodeManifestSchema = z
.strict();
const compiledSubagentNodeBaseFields = {
+ backing: resourceSourceBackingSchema,
entryPath: z.string(),
logicalPath: z.string(),
name: z.string(),
nodeId: z.string(),
+ owner: agentSourceOwnerSchema,
+ parentNodeId: z.string(),
rootPath: z.string(),
sourceId: z.string(),
sourceKind: z.literal("module"),
@@ -756,13 +937,6 @@ const compiledSubagentNodeSchema: z.ZodType<CompiledSubagentNode> = z.union([
.strict(),
]);
-const compiledSubagentEdgeSchema: z.ZodType<CompiledSubagentEdge> = z
- .object({
- childNodeId: z.string(),
- parentNodeId: z.string(),
- })
- .strict();
-
/**
* One mounted extension recorded on a compiled agent manifest. The runtime
* evaluates {@link mountLogicalPath} at module-map load so the mount's factory
@@ -797,12 +971,13 @@ export const compiledAgentManifestSchema = z
.object({
agentRoot: z.string(),
appRoot: z.string(),
+ bindings: z.record(z.string(), compiledModuleBindingSchema),
extensionMounts: z.array(compiledExtensionMountSchema).default([]),
- channels: z.array(compiledChannelEntrySchema),
+ channelRoutes: compiledChannelRoutePlanSchema,
config: compiledAgentConfigSchema,
connections: z.array(compiledConnectionDefinitionSchema),
diagnosticsSummary: discoverDiagnosticsSummarySchema,
- disabledFrameworkTools: z.array(z.string()).readonly(),
+ sourceComposition: agentSourceCompositionSchema,
workflowTool: compiledWorkflowToolDefinitionSchema.optional(),
webSearchProvider: z.enum(["exa", "parallel"]).optional(),
dynamicInstructions: z.array(compiledDynamicInstructionsDefinitionSchema).default([]),
@@ -811,13 +986,13 @@ export const compiledAgentManifestSchema = z
hooks: z.array(compiledHookDefinitionSchema),
kind: z.literal(COMPILED_AGENT_MANIFEST_KIND),
remoteAgents: z.array(compiledRemoteAgentNodeSchema),
- sandbox: compiledSandboxDefinitionSchema.nullable(),
+ sandbox: compiledSandboxDefinitionSchema,
sandboxWorkspaces: z.array(compiledSandboxWorkspaceSchema),
schedules: z.array(compiledScheduleDefinitionSchema),
skills: z.array(compiledSkillSourceSchema).readonly(),
- subagentEdges: z.array(compiledSubagentEdgeSchema),
subagents: z.array(compiledSubagentNodeSchema),
instructions: z.array(compiledInstructionsSchema).readonly().default([]),
+ instrumentation: moduleSourceRefSchema.optional(),
tools: z.array(compiledToolDefinitionSchema),
version: z.literal(COMPILED_AGENT_MANIFEST_VERSION),
workspaceResourceRoot: compiledWorkspaceResourceRootSchema,
@@ -827,10 +1002,11 @@ export const compiledAgentManifestSchema = z
export interface CreateCompiledAgentResourcesInput {
readonly agentRoot: string;
readonly appRoot: string;
- readonly channels?: readonly CompiledChannelEntry[];
+ readonly bindings: Readonly<Record<string, CompiledModuleBinding>>;
+ readonly channelRoutes: CompiledChannelRoutePlan;
readonly connections?: readonly CompiledConnectionDefinition[];
readonly diagnosticsSummary?: DiscoverDiagnosticsSummary;
- readonly disabledFrameworkTools?: readonly string[];
+ readonly sourceComposition: AgentSourceComposition;
readonly workflowTool?: CompiledWorkflowToolDefinition;
readonly webSearchProvider?: WebSearchProvider;
readonly dynamicInstructions?: readonly CompiledDynamicInstructionsDefinition[];
@@ -839,11 +1015,12 @@ export interface CreateCompiledAgentResourcesInput {
readonly extensionMounts?: readonly CompiledExtensionMount[];
readonly hooks?: readonly CompiledHookDefinition[];
readonly remoteAgents?: readonly CompiledRemoteAgentNode[];
- readonly sandbox?: CompiledSandboxDefinition | null;
+ readonly sandbox: CompiledSandboxDefinition;
readonly sandboxWorkspaces?: readonly CompiledSandboxWorkspace[];
readonly schedules?: readonly CompiledScheduleDefinition[];
readonly skills?: readonly CompiledSkillDefinition[];
readonly instructions?: readonly CompiledInstructionsDefinition[];
+ readonly instrumentation?: ModuleSourceRef;
readonly tools?: readonly CompiledToolDefinition[];
readonly workspaceResourceRoot?: CompiledWorkspaceResourceRoot;
}
@@ -855,17 +1032,21 @@ export function createCompiledAgentResources(
const resources: CompiledAgentResources = {
agentRoot: input.agentRoot,
appRoot: input.appRoot,
- channels: [...(input.channels ?? [])],
+ bindings: { ...input.bindings },
+ channelRoutes: {
+ effective: [...input.channelRoutes.effective],
+ preflight: [...input.channelRoutes.preflight],
+ shadowed: [...input.channelRoutes.shadowed],
+ },
connections: [...(input.connections ?? [])],
diagnosticsSummary: input.diagnosticsSummary ?? {
errors: 0,
warnings: 0,
},
- disabledFrameworkTools: [...(input.disabledFrameworkTools ?? [])],
- workflowTool:
- input.workflowTool === undefined
- ? undefined
- : { maxSubagents: input.workflowTool.maxSubagents },
+ sourceComposition: {
+ entries: [...input.sourceComposition.entries],
+ },
+ workflowTool: input.workflowTool === undefined ? undefined : { ...input.workflowTool },
webSearchProvider: input.webSearchProvider,
dynamicInstructions: [...(input.dynamicInstructions ?? [])],
dynamicSkills: [...(input.dynamicSkills ?? [])],
@@ -873,8 +1054,9 @@ export function createCompiledAgentResources(
extensionMounts: [...(input.extensionMounts ?? [])],
hooks: [...(input.hooks ?? [])],
instructions: [...(input.instructions ?? [])],
+ instrumentation: input.instrumentation === undefined ? undefined : { ...input.instrumentation },
remoteAgents: [...(input.remoteAgents ?? [])],
- sandbox: input.sandbox ?? null,
+ sandbox: input.sandbox,
sandboxWorkspaces: [...(input.sandboxWorkspaces ?? [])],
schedules: [...(input.schedules ?? [])],
skills: [...(input.skills ?? [])],
@@ -895,10 +1077,12 @@ export function createCompiledAgentResources(
export function createCompiledAgentNodeManifest(
input: CreateCompiledAgentResourcesInput & { readonly config: CompiledAgentDefinition },
): CompiledAgentNodeManifest {
- return {
+ const manifest = {
...createCompiledAgentResources(input),
config: cloneCompiledAgentDefinition(input.config),
};
+ validateCompiledAgentResources(manifest, { allowUnknownResourceWinners: true });
+ return manifest;
}
function cloneCompiledAgentDefinition(config: CompiledAgentDefinition): CompiledAgentDefinition {
@@ -945,12 +1129,7 @@ function cloneCompiledAgentDefinition(config: CompiledAgentDefinition): Compiled
maxOutputTokensPerSession: config.limits.maxOutputTokensPerSession,
sessionTimeoutMs: config.limits.sessionTimeoutMs,
},
- source:
- config.source === undefined
- ? undefined
- : {
- ...config.source,
- },
+ source: { ...config.source },
};
if (config.dynamicModel !== undefined) {
@@ -1007,35 +1186,39 @@ export function createCompiledSubagentNodeId(parentNodeId: string, sourceId: str
export function createCompiledAgentManifest(input: {
readonly agentRoot: string;
readonly appRoot: string;
- readonly channels?: readonly CompiledChannelEntry[];
+ readonly bindings: Readonly<Record<string, CompiledModuleBinding>>;
+ readonly channelRoutes: CompiledChannelRoutePlan;
readonly config: CompiledAgentDefinition;
readonly connections?: readonly CompiledConnectionDefinition[];
readonly diagnosticsSummary?: DiscoverDiagnosticsSummary;
- readonly disabledFrameworkTools?: readonly string[];
+ readonly sourceComposition: AgentSourceComposition;
readonly workflowTool?: CompiledWorkflowToolDefinition;
readonly webSearchProvider?: WebSearchProvider;
+ readonly dynamicInstructions?: readonly CompiledDynamicInstructionsDefinition[];
readonly dynamicSkills?: readonly CompiledDynamicSkillDefinition[];
readonly dynamicTools?: readonly CompiledDynamicToolDefinition[];
readonly hooks?: readonly CompiledHookDefinition[];
readonly remoteAgents?: readonly CompiledRemoteAgentNode[];
- readonly sandbox?: CompiledSandboxDefinition | null;
+ readonly sandbox: CompiledSandboxDefinition;
readonly sandboxWorkspaces?: readonly CompiledSandboxWorkspace[];
readonly schedules?: readonly CompiledScheduleDefinition[];
readonly skills?: readonly CompiledSkillDefinition[];
- readonly subagentEdges?: readonly CompiledSubagentEdge[];
readonly subagents?: readonly CompiledSubagentNode[];
readonly instructions?: readonly CompiledInstructionsDefinition[];
+ readonly instrumentation?: ModuleSourceRef;
readonly tools?: readonly CompiledToolDefinition[];
readonly extensionMounts?: readonly CompiledExtensionMount[];
+ readonly workspaceResourceRoot?: CompiledWorkspaceResourceRoot;
}): CompiledAgentManifest {
- return {
+ const manifest: CompiledAgentManifest = {
...createCompiledAgentNodeManifest(input),
kind: COMPILED_AGENT_MANIFEST_KIND,
extensionMounts: [...(input.extensionMounts ?? [])],
- subagentEdges: [...(input.subagentEdges ?? [])],
subagents: [...(input.subagents ?? [])],
version: COMPILED_AGENT_MANIFEST_VERSION,
};
+ validateCompiledAgentManifest(manifest);
+ return manifest;
}
function cloneCompiledRuntimeModelReference(
diff --git a/packages/eve/src/compiler/module-map.test.ts b/packages/eve/src/compiler/module-map.test.ts
index e459b312c..f47b1fe89 100644
--- a/packages/eve/src/compiler/module-map.test.ts
+++ b/packages/eve/src/compiler/module-map.test.ts
@@ -1,216 +1,113 @@
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
-import type { CompiledAgentManifest } from "./manifest.js";
+import { compileFromMemory } from "#compiler/compile-from-memory.js";
import {
- COMPILED_AGENT_MANIFEST_VERSION,
- createCompiledAgentResources,
- ROOT_COMPILED_AGENT_NODE_ID,
-} from "./manifest.js";
-import { collectModuleRefsForManifest, createCompiledModuleMapSource } from "./module-map.js";
-
-function createManifestWithTool(agentRoot: string): CompiledAgentManifest {
- return {
- agentRoot,
- appRoot: agentRoot,
- config: {
- compaction: {},
- model: {
- contextWindowTokens: 128_000,
- id: "openai/gpt-5.4-mini",
- routing: { kind: "gateway", target: "openai" },
- },
- name: "kitchen-sink-fixture",
- },
- connections: [],
- diagnosticsSummary: {
- errors: 0,
- warnings: 0,
- },
- extensionMounts: [],
- disabledFrameworkTools: [],
- dynamicInstructions: [],
- dynamicSkills: [],
- dynamicTools: [],
- hooks: [],
- instructions: [],
- kind: "eve-agent-compiled-manifest",
- remoteAgents: [],
- schedules: [],
- sandbox: null,
- sandboxWorkspaces: [],
- skills: [],
- subagentEdges: [],
- channels: [],
- subagents: [],
- tools: [
- {
- description: "Echoes input.",
- exportName: "default",
- inputSchema: {},
- logicalPath: "tools/echo.ts",
- name: "echo",
- sourceId: "tools/echo.ts",
- sourceKind: "module",
+ collectModuleBindingsForManifest,
+ createCompiledModuleMapSource,
+ createProgrammaticCompiledModuleMap,
+} from "#compiler/module-map.js";
+
+const mocks = vi.hoisted(() => ({
+ loadAuthoredModuleNamespace: vi.fn(
+ async (
+ _sourcePath: string,
+ _options: {
+ readonly externalDependencies: readonly string[];
+ readonly extensionScopeNamespace?: string;
},
- ],
- version: COMPILED_AGENT_MANIFEST_VERSION,
- workspaceResourceRoot: {
- logicalPath: "",
- rootEntries: [],
- },
- };
-}
-
-describe("createCompiledModuleMapSource", () => {
- it("emits ESM-safe file URLs for Windows absolute imports", () => {
+ ) => ({}),
+ ),
+}));
+
+vi.mock("#internal/authored-module-loader.js", () => ({
+ loadAuthoredModuleNamespace: mocks.loadAuthoredModuleNamespace,
+}));
+
+describe("compiled module maps", () => {
+ it("renders every selected binding and no shadowed source", async () => {
+ const { manifest } = await compileFromMemory({
+ model: "openai/gpt-5.4",
+ tools: [{ name: "weather" }],
+ });
const source = createCompiledModuleMapSource({
- importSpecifierStyle: "absolute",
- manifest: createManifestWithTool(
- "G:\\projects\\eve\\apps\\fixtures\\kitchen-sink-fixture\\agent",
- ),
- moduleMapPath:
- "G:\\projects\\eve\\apps\\fixtures\\kitchen-sink-fixture\\.eve\\compile\\module-map.mjs",
+ manifest,
+ moduleMapPath: "/app/.eve/compile/module-map.mjs",
});
- expect(source).toContain(
- 'import * as module_0 from "file:///G:/projects/eve/apps/fixtures/kitchen-sink-fixture/agent/tools/echo.ts";',
- );
- expect(source).not.toContain(
- '"G:/projects/eve/apps/fixtures/kitchen-sink-fixture/agent/tools/echo.ts"',
- );
- expect(source).toContain(`"${ROOT_COMPILED_AGENT_NODE_ID}"`);
+ for (const sourceId of Object.keys(manifest.bindings)) {
+ expect(source).toContain(JSON.stringify(sourceId));
+ }
+ for (const entry of manifest.sourceComposition.entries) {
+ if (entry.kind === "shadowed") {
+ expect(source).not.toContain(JSON.stringify(entry.source.sourceId));
+ }
+ }
+ expect(source).toContain("loadFrameworkProgrammaticModule");
});
- it("imports a dynamic subagent config resolver relative to the child agent root", () => {
- const manifest: CompiledAgentManifest = {
- ...createManifestWithTool("/agent"),
- subagents: [
- {
- agent: createCompiledAgentResources({
- agentRoot: "/agent/subagents/researcher",
- appRoot: "/agent",
- }),
- configResolver: {
- eventNames: ["turn.started"],
- logicalPath: "agent.ts",
- sourceId: "agent.ts",
- sourceKind: "module",
- },
- entryPath: "/agent/subagents/researcher/agent.ts",
- logicalPath: "subagents/researcher",
- name: "researcher",
- nodeId: "subagents/researcher",
- rootPath: "/agent/subagents/researcher",
- sourceId: "subagents/researcher",
- sourceKind: "module",
- },
- ],
- };
-
- const source = createCompiledModuleMapSource({
- manifest,
- moduleMapPath: "/agent/.eve/compile/module-map.mjs",
+ it("collects exactly the node binding table plus explicit remote bindings", async () => {
+ const { manifest } = await compileFromMemory({
+ model: "openai/gpt-5.4",
+ tools: [{ name: "weather" }, { name: "echo" }],
});
- expect(source).toContain('from "../../subagents/researcher/agent.ts";');
- expect(source).not.toContain("subagents/researcher/subagents/researcher");
+ expect(collectModuleBindingsForManifest(manifest).map((entry) => entry.sourceId)).toEqual(
+ Object.keys(manifest.bindings).sort(),
+ );
});
-});
-
-describe("collectModuleRefsForManifest", () => {
- it("includes module-sourced schedules with run() so the dispatcher can load the handler", () => {
- const manifest = createManifestWithTool("/agent");
- const manifestWithSchedule: CompiledAgentManifest = {
- ...manifest,
- schedules: [
- {
- cron: "0 9 * * 1-5",
- hasRun: true,
- logicalPath: "schedules/daily-digest.ts",
- name: "daily-digest",
- sourceId: "schedules/daily-digest.ts",
- sourceKind: "module",
- },
- ],
- };
- const refs = collectModuleRefsForManifest(manifestWithSchedule);
+ it("uses the selected semantic revision in generated programmatic loads", async () => {
+ const { manifest } = await compileFromMemory({ model: "openai/gpt-5.4" });
+ const sandboxBinding = manifest.bindings[manifest.sandbox.sourceId]!;
+ const source = createCompiledModuleMapSource({
+ manifest,
+ moduleMapPath: "/app/.eve/compile/module-map.mjs",
+ });
- expect(refs).toContainEqual({
- sourceKind: "module",
- logicalPath: "schedules/daily-digest.ts",
- sourceId: "schedules/daily-digest.ts",
+ expect(sandboxBinding.backing).toMatchObject({
+ kind: "programmatic",
+ semanticRevision: "eve:default-sandbox:v1",
});
+ expect(source).toContain("eve:default-sandbox:v1");
});
- it("omits markdown schedules from the module map", () => {
- const manifest = createManifestWithTool("/agent");
- const manifestWithSchedule: CompiledAgentManifest = {
- ...manifest,
- schedules: [
- {
- cron: "0 0 * * 0",
- hasRun: false,
- logicalPath: "schedules/cleanup.md",
- name: "cleanup",
- sourceId: "schedules/cleanup.md",
- sourceKind: "markdown",
- markdown: "Clean up stale data.",
- },
- ],
+ it("loads extension bindings with their stable package namespace", async () => {
+ const { manifest } = await compileFromMemory({ model: "openai/gpt-5.4" });
+ const [extensionSourceId, ...applicationSourceIds] = Object.keys(manifest.bindings).sort();
+ if (extensionSourceId === undefined) throw new Error("Expected at least one module binding.");
+ manifest.bindings[extensionSourceId] = {
+ backing: {
+ externalDependencies: [],
+ extensionScope: { namespace: "renamed-mount", sourceRoot: "/extension" },
+ kind: "filesystem",
+ sourcePath: "/extension/tool.ts",
+ },
+ logicalPath: "tools/renamed-mount__tool.ts",
+ owner: { kind: "extension", namespace: "renamed-mount", packageName: "@acme/crm" },
};
-
- const refs = collectModuleRefsForManifest(manifestWithSchedule);
-
- expect(refs.some((ref) => ref.sourceId === "schedules/cleanup.md")).toBe(false);
- });
-
- it("omits module-sourced schedules that only carry markdown (no run handler)", () => {
- const manifest = createManifestWithTool("/agent");
- const manifestWithSchedule: CompiledAgentManifest = {
- ...manifest,
- schedules: [
- {
- cron: "0 8 * * *",
- hasRun: false,
- logicalPath: "schedules/daily-digest.mjs",
- name: "daily-digest",
- markdown: "Send a weather digest.",
- sourceId: "schedules/daily-digest.mjs",
- sourceKind: "module",
+ for (const sourceId of applicationSourceIds) {
+ manifest.bindings[sourceId] = {
+ backing: {
+ externalDependencies: [],
+ kind: "filesystem",
+ sourcePath: `/application/${sourceId}.ts`,
},
- ],
- };
-
- const refs = collectModuleRefsForManifest(manifestWithSchedule);
+ logicalPath: manifest.bindings[sourceId]!.logicalPath,
+ owner: { kind: "application" },
+ };
+ }
+ mocks.loadAuthoredModuleNamespace.mockClear();
- expect(refs.some((ref) => ref.sourceId === "schedules/daily-digest.mjs")).toBe(false);
- });
-
- it("includes remote agents from the node manifest without an extra module-ref side channel", () => {
- const manifest = createManifestWithTool("/agent");
- const refs = collectModuleRefsForManifest({
- ...manifest,
- remoteAgents: [
- {
- description: "Answer weather questions remotely.",
- entryPath: "/agent/subagents/weather.ts",
- logicalPath: "subagents/weather.ts",
- name: "weather",
- nodeId: "subagents/weather.ts",
- path: "/eve/v1/session",
- rootPath: "/agent",
- sourceId: "subagents/weather.ts",
- sourceKind: "module",
- url: "https://weather.example.com",
- },
- ],
- });
+ await createProgrammaticCompiledModuleMap(manifest, []);
- expect(refs).toContainEqual({
- sourceKind: "module",
- logicalPath: "subagents/weather.ts",
- sourceId: "subagents/weather.ts",
+ expect(mocks.loadAuthoredModuleNamespace).toHaveBeenCalledWith("/extension/tool.ts", {
+ externalDependencies: [],
+ extensionScopeNamespace: "acme-crm",
});
+ expect(
+ mocks.loadAuthoredModuleNamespace.mock.calls
+ .filter(([sourcePath]) => sourcePath.startsWith("/application/"))
+ .every(([, options]) => options.extensionScopeNamespace === undefined),
+ ).toBe(true);
});
});
diff --git a/packages/eve/src/compiler/module-map.ts b/packages/eve/src/compiler/module-map.ts
index a5bef96d0..5929cf224 100644
--- a/packages/eve/src/compiler/module-map.ts
+++ b/packages/eve/src/compiler/module-map.ts
@@ -1,304 +1,182 @@
import { z } from "#compiled/zod/index.js";
-import type { ModuleSourceRef } from "#shared/source-ref.js";
import type {
CompiledAgentManifest,
CompiledAgentNodeManifest,
CompiledAgentResources,
- CompiledExtensionMount,
} from "#compiler/manifest.js";
import { ROOT_COMPILED_AGENT_NODE_ID } from "#compiler/manifest.js";
+import { packageStateNamespace } from "#discover/extensions.js";
+import {
+ loadProgrammaticModuleNamespace,
+ type AgentSourceRegistry,
+ type CompiledModuleBinding,
+ type ProgrammaticModuleNamespace,
+} from "#compiler/source-graph.js";
import { normalizeEsmImportSpecifier } from "#internal/application/import-specifier.js";
+import { loadAuthoredModuleNamespace } from "#internal/authored-module-loader.js";
-/**
- * Compiled module ownership for one runtime graph node.
- */
export type CompiledModuleNodeScope = z.infer<typeof compiledModuleNodeScopeSchema>;
-
-/**
- * Flattened compiled authored module map keyed by stable node ids.
- */
export type CompiledModuleMap = z.infer<typeof compiledModuleMapSchema>;
const compiledModuleNodeScopeSchema = z
- .object({
- modules: z.record(z.string(), z.object({}).passthrough()),
- })
+ .object({ modules: z.record(z.string(), z.object({}).passthrough()) })
.strict();
-/**
- * Zod schema for the flattened compiled authored module map.
- */
export const compiledModuleMapSchema = z
- .object({
- nodes: z.record(z.string(), compiledModuleNodeScopeSchema),
- })
+ .object({ nodes: z.record(z.string(), compiledModuleNodeScopeSchema) })
.strict();
-/**
- * Input for generating the compiled authored module map artifact.
- */
export interface CreateCompiledModuleMapSourceInput {
- /**
- * Controls how generated authored-module imports are written. Relative
- * specifiers are the compiler default; absolute specifiers are useful when a
- * bundler consumes the module map from a virtual module id.
- */
importSpecifierStyle?: "absolute" | "relative";
manifest: CompiledAgentManifest;
moduleMapPath: string;
+ programmaticLoaderImportSpecifier?: string;
+}
+
+interface BoundModule {
+ readonly binding: CompiledModuleBinding;
+ readonly sourceId: string;
}
-interface CollectedModuleImport {
+interface BoundNodeScope {
+ readonly modules: readonly BoundModule[];
+ readonly nodeId: string;
+}
+
+interface RenderedModule {
readonly bindingName: string;
- readonly importSpecifier: string;
+ readonly initializer?: string;
+ readonly importSpecifier?: string;
readonly sourceId: string;
}
-interface CollectedModuleNodeScope {
- readonly modules: readonly CollectedModuleImport[];
+interface RenderedNodeScope {
+ readonly modules: readonly RenderedModule[];
readonly nodeId: string;
}
-/**
- * Generates the compiler-owned module map artifact that statically imports
- * every module-backed authored source.
- */
+/** Generates the authoritative module-map artifact from required bindings. */
export function createCompiledModuleMapSource(input: CreateCompiledModuleMapSourceInput): string {
const moduleMapDirectory = dirnameFilesystemPath(input.moduleMapPath);
const importSpecifierStyle = input.importSpecifierStyle ?? "relative";
- let nextBindingIndex = 0;
- const collectedScopes: CollectedModuleNodeScope[] = [
- collectModuleNodeScope({
- agentRoot: input.manifest.agentRoot,
- importSpecifierStyle,
- manifest: input.manifest,
- moduleMapDirectory,
- nextBindingName() {
- return `module_${nextBindingIndex++}`;
- },
- nodeId: ROOT_COMPILED_AGENT_NODE_ID,
+ let index = 0;
+ let usesProgrammaticLoader = false;
+ const scopes: RenderedNodeScope[] = collectBoundNodeScopes(input.manifest).map((scope) => ({
+ modules: scope.modules.map(({ binding, sourceId }) => {
+ const bindingName = `module_${index++}`;
+ if (binding.backing.kind === "filesystem") {
+ return {
+ bindingName,
+ importSpecifier: createImportSpecifier({
+ fromDirectory: moduleMapDirectory,
+ importSpecifierStyle,
+ targetPath: binding.backing.sourcePath,
+ }),
+ sourceId,
+ };
+ }
+ usesProgrammaticLoader = true;
+ return {
+ bindingName,
+ initializer: `await loadProgrammaticModule(${JSON.stringify(binding.backing)})`,
+ sourceId,
+ };
}),
- ...[...input.manifest.subagents]
- .sort((left, right) => left.nodeId.localeCompare(right.nodeId))
- .map((subagent) =>
- collectModuleNodeScope({
- agentRoot: subagent.agent.agentRoot,
- importSpecifierStyle,
- manifest: subagent.agent,
- additionalModuleRef: subagent.configResolver,
- moduleMapDirectory,
- nextBindingName() {
- return `module_${nextBindingIndex++}`;
- },
- nodeId: subagent.nodeId,
- }),
- ),
- ];
- const allModules = collectedScopes.flatMap((scope) => scope.modules);
-
- const staticImports = allModules.map(
- (moduleImport) =>
- `import * as ${moduleImport.bindingName} from ${JSON.stringify(moduleImport.importSpecifier)};`,
+ nodeId: scope.nodeId,
+ }));
+ const modules = scopes.flatMap((scope) => scope.modules);
+ const imports = modules.flatMap((module) =>
+ module.importSpecifier === undefined
+ ? []
+ : [`import * as ${module.bindingName} from ${JSON.stringify(module.importSpecifier)};`],
+ );
+ const initializers = modules.flatMap((module) =>
+ module.initializer === undefined
+ ? []
+ : [`const ${module.bindingName} = ${module.initializer};`],
);
return [
"// Generated by eve. Do not edit by hand.",
- "",
- ...staticImports,
- ...(staticImports.length > 0 ? [""] : []),
- `export const moduleMap = ${renderModuleMap(collectedScopes)};`,
+ ...(usesProgrammaticLoader
+ ? [
+ `import { loadFrameworkProgrammaticModule as loadProgrammaticModule } from ${JSON.stringify(normalizeEsmImportSpecifier(input.programmaticLoaderImportSpecifier ?? "eve/internal/programmatic-source-loader"))};`,
+ ]
+ : []),
+ ...imports,
+ ...(usesProgrammaticLoader || imports.length > 0 ? [""] : []),
+ ...initializers,
+ ...(initializers.length > 0 ? [""] : []),
+ `export const moduleMap = ${renderModuleMap(scopes)};`,
"",
"export default moduleMap;",
"",
].join("\n");
}
-function collectModuleNodeScope(input: {
- readonly additionalModuleRef?: ModuleSourceRef;
- readonly agentRoot: string;
- readonly importSpecifierStyle: "absolute" | "relative";
- readonly manifest: CompiledAgentNodeManifest | CompiledAgentResources;
- readonly moduleMapDirectory: string;
- readonly nextBindingName: () => string;
- readonly nodeId: string;
-}): CollectedModuleNodeScope {
- return {
- modules: [
- ...collectModuleRefsForManifest(input.manifest),
- ...(input.additionalModuleRef === undefined ? [] : [input.additionalModuleRef]),
- ]
- .sort((left, right) => left.sourceId.localeCompare(right.sourceId))
- .map((moduleSourceRef) => ({
- bindingName: input.nextBindingName(),
- importSpecifier: createImportSpecifier({
- fromDirectory: input.moduleMapDirectory,
- importSpecifierStyle: input.importSpecifierStyle,
- targetPath: joinFilesystemPath(input.agentRoot, moduleSourceRef.logicalPath),
- }),
- sourceId: moduleSourceRef.sourceId,
- })),
- nodeId: input.nodeId,
- };
-}
-
-/**
- * Collects every module-backed source reference from a single compiled
- * agent node manifest. Used by both the compiler (to generate the static
- * module-map artifact) and the runtime loader (to hydrate a module map
- * from the manifest when the pre-built artifact is unavailable).
- */
-export function collectModuleRefsForManifest(
- manifest: CompiledAgentNodeManifest | CompiledAgentResources,
-): ModuleSourceRef[] {
- const moduleSourceRefs = new Map<string, ModuleSourceRef>();
-
- if ("config" in manifest && manifest.config.source !== undefined) {
- moduleSourceRefs.set(manifest.config.source.sourceId, manifest.config.source);
- }
-
- if ("config" in manifest && manifest.config.model?.source !== undefined) {
- moduleSourceRefs.set(manifest.config.model.source.sourceId, manifest.config.model.source);
- }
-
- for (const channel of manifest.channels) {
- // Disabled channel entries don't have a source module — they're a
- // marker that the matching framework default should be removed.
- if (channel.kind === "disabled") {
- continue;
+/** Loads the same binding set used by generated maps without fabricating descriptors. */
+export async function createProgrammaticCompiledModuleMap(
+ manifest: CompiledAgentManifest,
+ registries: readonly AgentSourceRegistry[],
+): Promise<CompiledModuleMap> {
+ const nodes: CompiledModuleMap["nodes"] = {};
+ for (const scope of collectBoundNodeScopes(manifest)) {
+ const modules: Record<string, ProgrammaticModuleNamespace> = {};
+ for (const { binding, sourceId } of scope.modules) {
+ modules[sourceId] =
+ binding.backing.kind === "filesystem"
+ ? await loadAuthoredModuleNamespace(binding.backing.sourcePath, {
+ externalDependencies: binding.backing.externalDependencies,
+ extensionScopeNamespace: resolveCompiledModuleExtensionScopeNamespace(binding),
+ })
+ : await loadProgrammaticModuleNamespace({ backing: binding.backing, registries });
}
- moduleSourceRefs.set(channel.sourceId, {
- exportName: channel.exportName,
- sourceKind: "module",
- logicalPath: channel.logicalPath,
- sourceId: channel.sourceId,
- });
- }
-
- for (const connection of manifest.connections) {
- moduleSourceRefs.set(connection.sourceId, {
- exportName: connection.exportName,
- sourceKind: "module",
- logicalPath: connection.logicalPath,
- sourceId: connection.sourceId,
- });
- }
-
- for (const tool of manifest.tools) {
- moduleSourceRefs.set(tool.sourceId, {
- exportName: tool.exportName,
- sourceKind: "module",
- logicalPath: tool.logicalPath,
- sourceId: tool.sourceId,
- });
- }
-
- for (const dynamicInstruction of manifest.dynamicInstructions) {
- moduleSourceRefs.set(dynamicInstruction.sourceId, {
- exportName: dynamicInstruction.exportName,
- sourceKind: "module",
- logicalPath: dynamicInstruction.logicalPath,
- sourceId: dynamicInstruction.sourceId,
- });
- }
-
- for (const dynamicSkill of manifest.dynamicSkills) {
- moduleSourceRefs.set(dynamicSkill.sourceId, {
- exportName: dynamicSkill.exportName,
- sourceKind: "module",
- logicalPath: dynamicSkill.logicalPath,
- sourceId: dynamicSkill.sourceId,
- });
- }
-
- for (const dynamicTool of manifest.dynamicTools) {
- moduleSourceRefs.set(dynamicTool.sourceId, {
- exportName: dynamicTool.exportName,
- sourceKind: "module",
- logicalPath: dynamicTool.logicalPath,
- sourceId: dynamicTool.sourceId,
- });
- }
-
- for (const remoteAgent of manifest.remoteAgents) {
- moduleSourceRefs.set(remoteAgent.sourceId, {
- exportName: remoteAgent.exportName,
- sourceKind: "module",
- logicalPath: remoteAgent.logicalPath,
- sourceId: remoteAgent.sourceId,
- });
- }
-
- for (const hook of manifest.hooks) {
- moduleSourceRefs.set(hook.sourceId, {
- exportName: hook.exportName,
- sourceKind: "module",
- logicalPath: hook.logicalPath,
- sourceId: hook.sourceId,
- });
- }
-
- for (const schedule of manifest.schedules) {
- // Only `run`-handler schedules need their source loaded at dispatch
- // time. Markdown schedules execute from `manifest.markdown`.
- if (schedule.sourceKind !== "module" || !schedule.hasRun) {
- continue;
- }
- moduleSourceRefs.set(schedule.sourceId, {
- sourceKind: "module",
- logicalPath: schedule.logicalPath,
- sourceId: schedule.sourceId,
- });
+ nodes[scope.nodeId] = { modules };
}
+ return { nodes };
+}
- if (manifest.sandbox !== null) {
- moduleSourceRefs.set(manifest.sandbox.sourceId, {
- exportName: manifest.sandbox.exportName,
- sourceKind: "module",
- logicalPath: manifest.sandbox.logicalPath,
- sourceId: manifest.sandbox.sourceId,
- });
- }
+/** Derives the stable package-owned scope used while loading an extension module. */
+export function resolveCompiledModuleExtensionScopeNamespace(
+ binding: CompiledModuleBinding,
+): string | undefined {
+ return binding.owner.kind === "extension"
+ ? packageStateNamespace(binding.owner.packageName)
+ : undefined;
+}
- // Extension mount modules (root manifest only). Their top-level factory call
- // binds config, so they must be evaluated at module-map load.
- const extensionMounts = (manifest as { extensionMounts?: readonly CompiledExtensionMount[] })
- .extensionMounts;
- if (extensionMounts !== undefined) {
- for (const mount of extensionMounts) {
- moduleSourceRefs.set(mount.mountSourceId, {
- sourceKind: "module",
- logicalPath: mount.mountLogicalPath,
- sourceId: mount.mountSourceId,
- });
+/** Returns every binding owned by one compiled node, including remote config modules. */
+export function collectModuleBindingsForManifest(
+ manifest: CompiledAgentNodeManifest | CompiledAgentResources,
+): readonly BoundModule[] {
+ const modules = new Map<string, CompiledModuleBinding>(Object.entries(manifest.bindings));
+ for (const remote of manifest.remoteAgents) {
+ if (modules.has(remote.sourceId)) {
+ throw new Error(`Remote agent binding "${remote.sourceId}" collides with a node binding.`);
}
+ modules.set(remote.sourceId, remote.binding);
}
-
- // Authored system modules execute once at build time. The compiled markdown
- // is captured into the manifest, so there is no need to include them in the
- // runtime module map.
-
- return [...moduleSourceRefs.values()];
+ return [...modules]
+ .sort(([left], [right]) => left.localeCompare(right))
+ .map(([sourceId, binding]) => ({ binding, sourceId }));
}
-function createImportSpecifier(input: {
- fromDirectory: string;
- importSpecifierStyle: "absolute" | "relative";
- targetPath: string;
-}): string {
- if (input.importSpecifierStyle === "absolute") {
- return normalizeEsmImportSpecifier(normalizeFilesystemPath(input.targetPath));
- }
-
- const relativeSpecifier = relativeFilesystemPath(input.fromDirectory, input.targetPath);
-
- if (relativeSpecifier.startsWith(".")) {
- return relativeSpecifier;
- }
-
- return `./${relativeSpecifier}`;
+function collectBoundNodeScopes(manifest: CompiledAgentManifest): readonly BoundNodeScope[] {
+ return [
+ {
+ modules: collectModuleBindingsForManifest(manifest),
+ nodeId: ROOT_COMPILED_AGENT_NODE_ID,
+ },
+ ...[...manifest.subagents]
+ .sort((left, right) => left.nodeId.localeCompare(right.nodeId))
+ .map((subagent) => ({
+ modules: collectModuleBindingsForManifest(subagent.agent),
+ nodeId: subagent.nodeId,
+ })),
+ ];
}
-function renderModuleMap(scopes: readonly CollectedModuleNodeScope[]): string {
+function renderModuleMap(scopes: readonly RenderedNodeScope[]): string {
return renderFrozenObject(
[
{
@@ -311,9 +189,9 @@ function renderModuleMap(scopes: readonly CollectedModuleNodeScope[]): string {
{
key: "modules",
value: renderFrozenObject(
- scope.modules.map((moduleImport) => ({
- key: moduleImport.sourceId,
- value: moduleImport.bindingName,
+ scope.modules.map((module) => ({
+ key: module.sourceId,
+ value: module.bindingName,
})),
),
},
@@ -329,61 +207,47 @@ function renderModuleMap(scopes: readonly CollectedModuleNodeScope[]): string {
}
function renderFrozenObject(
- entries: ReadonlyArray<{
- key: string;
- value: string;
- }>,
+ entries: ReadonlyArray<{ readonly key: string; readonly value: string }>,
depth: number = 1,
): string {
- if (entries.length === 0) {
- return "Object.freeze({})";
- }
-
+ if (entries.length === 0) return "Object.freeze({})";
const indentation = " ".repeat(depth);
const nestedIndentation = " ".repeat(depth + 1);
-
return [
"Object.freeze({",
entries
- .map((entry) => {
- return `${nestedIndentation}${JSON.stringify(entry.key)}: ${entry.value.replaceAll("\n", `\n${nestedIndentation}`)}`;
- })
+ .map(
+ (entry) =>
+ `${nestedIndentation}${JSON.stringify(entry.key)}: ${entry.value.replaceAll("\n", `\n${nestedIndentation}`)}`,
+ )
.join(",\n"),
`${indentation}})`,
].join("\n");
}
-function dirnameFilesystemPath(path: string): string {
- const parsed = splitFilesystemPath(path);
-
- if (parsed.segments.length === 0) {
- return parsed.root.length === 0 ? "." : parsed.root;
+function createImportSpecifier(input: {
+ readonly fromDirectory: string;
+ readonly importSpecifierStyle: "absolute" | "relative";
+ readonly targetPath: string;
+}): string {
+ if (input.importSpecifierStyle === "absolute") {
+ return normalizeEsmImportSpecifier(normalizeFilesystemPath(input.targetPath));
}
-
- return createFilesystemPath(parsed.root, parsed.segments.slice(0, -1));
+ const relativeSpecifier = relativeFilesystemPath(input.fromDirectory, input.targetPath);
+ return relativeSpecifier.startsWith(".") ? relativeSpecifier : `./${relativeSpecifier}`;
}
-function joinFilesystemPath(base: string, next: string): string {
- const parsedBase = splitFilesystemPath(base);
- const parsedNext = splitFilesystemPath(next);
-
- if (parsedNext.root.length > 0) {
- return createFilesystemPath(parsedNext.root, parsedNext.segments);
- }
-
- return createFilesystemPath(parsedBase.root, [...parsedBase.segments, ...parsedNext.segments]);
+function dirnameFilesystemPath(path: string): string {
+ const parsed = splitFilesystemPath(path);
+ if (parsed.segments.length === 0) return parsed.root.length === 0 ? "." : parsed.root;
+ return createFilesystemPath(parsed.root, parsed.segments.slice(0, -1));
}
function relativeFilesystemPath(fromDirectory: string, targetPath: string): string {
const from = splitFilesystemPath(fromDirectory);
const target = splitFilesystemPath(targetPath);
-
- if (from.root !== target.root) {
- return normalizeFilesystemPath(targetPath);
- }
-
+ if (from.root !== target.root) return normalizeFilesystemPath(targetPath);
let sharedIndex = 0;
-
while (
sharedIndex < from.segments.length &&
sharedIndex < target.segments.length &&
@@ -391,13 +255,12 @@ function relativeFilesystemPath(fromDirectory: string, targetPath: string): stri
) {
sharedIndex += 1;
}
-
- const relativeSegments = [
- ...Array.from({ length: from.segments.length - sharedIndex }, () => ".."),
- ...target.segments.slice(sharedIndex),
- ];
-
- return relativeSegments.length === 0 ? "." : relativeSegments.join("/");
+ return (
+ [
+ ...Array.from({ length: from.segments.length - sharedIndex }, () => ".."),
+ ...target.segments.slice(sharedIndex),
+ ].join("/") || "."
+ );
}
function normalizeFilesystemPath(path: string): string {
@@ -405,70 +268,36 @@ function normalizeFilesystemPath(path: string): string {
return createFilesystemPath(parsed.root, parsed.segments);
}
-function splitFilesystemPath(path: string): {
- readonly root: string;
- readonly segments: string[];
-} {
+function splitFilesystemPath(path: string): { readonly root: string; readonly segments: string[] } {
const normalized = path.replaceAll("\\", "/");
let root = "";
let remainder = normalized;
-
- const windowsDriveMatch = normalized.match(/^[A-Za-z]:/);
-
- if (windowsDriveMatch !== null) {
- root = windowsDriveMatch[0];
+ const windowsDrive = normalized.match(/^[A-Za-z]:/);
+ if (windowsDrive !== null) {
+ root = windowsDrive[0];
remainder = normalized.slice(root.length);
-
if (remainder.startsWith("/")) {
- root = `${root}/`;
+ root += "/";
remainder = remainder.slice(1);
}
} else if (normalized.startsWith("/")) {
root = "/";
remainder = normalized.slice(1);
}
-
const segments: string[] = [];
-
for (const segment of remainder.split("/")) {
- if (segment.length === 0 || segment === ".") {
- continue;
- }
-
+ if (segment.length === 0 || segment === ".") continue;
if (segment === "..") {
- if (segments.length > 0 && segments[segments.length - 1] !== "..") {
- segments.pop();
- continue;
- }
-
- if (root.length === 0) {
- segments.push(segment);
- }
-
- continue;
- }
-
- segments.push(segment);
+ if (segments.length > 0 && segments.at(-1) !== "..") segments.pop();
+ else if (root.length === 0) segments.push(segment);
+ } else segments.push(segment);
}
-
- return {
- root,
- segments,
- };
+ return { root, segments };
}
function createFilesystemPath(root: string, segments: readonly string[]): string {
- if (root === "/") {
- return segments.length === 0 ? "/" : `/${segments.join("/")}`;
- }
-
- if (root.endsWith("/")) {
- return segments.length === 0 ? root : `${root}${segments.join("/")}`;
- }
-
- if (root.length > 0) {
- return segments.length === 0 ? root : `${root}/${segments.join("/")}`;
- }
-
+ if (root === "/") return segments.length === 0 ? "/" : `/${segments.join("/")}`;
+ if (root.endsWith("/")) return segments.length === 0 ? root : `${root}${segments.join("/")}`;
+ if (root.length > 0) return segments.length === 0 ? root : `${root}/${segments.join("/")}`;
return segments.length === 0 ? "." : segments.join("/");
}
diff --git a/packages/eve/src/compiler/node-source-state.ts b/packages/eve/src/compiler/node-source-state.ts
new file mode 100644
index 000000000..49d44ae11
--- /dev/null
+++ b/packages/eve/src/compiler/node-source-state.ts
@@ -0,0 +1,144 @@
+import type { ModuleSourceRef } from "#shared/source-ref.js";
+import {
+ collectSelectedSourceIds,
+ mergeExternalDependencies,
+} from "#compiler/normalize-manifest-helpers.js";
+import type {
+ ProjectedAgentSources,
+ ProjectedSource,
+ ProjectedSubagentSource,
+} from "#compiler/project-sources.js";
+import {
+ createCompiledModuleBinding,
+ type AgentModuleCandidate,
+ type AgentSourceBacking,
+ type AgentSourceCandidate,
+ type AgentSourceDescriptor,
+ type ComposedAgentModuleCandidates,
+ type CompiledModuleBinding,
+} from "#compiler/source-graph.js";
+
+export interface ComposedNodeSourceGraph {
+ composed: ComposedAgentModuleCandidates;
+ readonly orderedCandidates: readonly AgentSourceCandidate[];
+ readonly projected: ProjectedAgentSources;
+ readonly sourcesBySourceId: ReadonlyMap<string, ProjectedSource>;
+ readonly subagentsBySourceId: ReadonlyMap<string, ProjectedSubagentSource>;
+}
+
+export interface SelectedNodeConfig {
+ readonly binding: CompiledModuleBinding;
+ readonly candidate: AgentModuleCandidate;
+ readonly definition: unknown;
+ readonly source: ModuleSourceRef;
+}
+
+export interface PhaseOneNodeSourceState {
+ readonly graph: ComposedNodeSourceGraph;
+ readonly selectedConfig: SelectedNodeConfig;
+}
+
+export interface FinalizedNodeSourceState extends ComposedNodeSourceGraph {
+ readonly bindings: Record<string, CompiledModuleBinding>;
+}
+
+export function finalizeNodeSourceState(
+ phaseOne: PhaseOneNodeSourceState,
+ externalDependencies: readonly string[],
+): FinalizedNodeSourceState {
+ const graph = phaseOne.graph;
+ const candidatesBySourceId = new Map(
+ graph.orderedCandidates.map((candidate) => {
+ const finalized = finalizeCandidateExternalDependencies(candidate, externalDependencies);
+ return [candidate.sourceId, finalized] as const;
+ }),
+ );
+ const candidateFor = <TCandidate extends AgentSourceCandidate>(candidate: TCandidate) => {
+ const finalized = candidatesBySourceId.get(candidate.sourceId);
+ if (finalized === undefined) {
+ throw new Error(`Agent source candidate "${candidate.sourceId}" is missing from its node.`);
+ }
+ return finalized as TCandidate;
+ };
+ const projected: ProjectedAgentSources = {
+ candidates: graph.projected.candidates.map(candidateFor),
+ resources: graph.projected.resources.map((entry) => ({
+ ...entry,
+ candidate: candidateFor(entry.candidate),
+ })) as ProjectedAgentSources["resources"],
+ subagents: graph.projected.subagents.map((entry) => ({
+ ...entry,
+ candidate: candidateFor(entry.candidate),
+ })),
+ };
+ const composed: ComposedAgentModuleCandidates = {
+ composition: {
+ entries: graph.composed.composition.entries.map((entry) => ({
+ ...entry,
+ source: finalizeDescriptorExternalDependencies(entry.source, externalDependencies),
+ })),
+ },
+ selected: new Map(
+ [...graph.composed.selected].map(([slot, candidate]) => [slot, candidateFor(candidate)]),
+ ),
+ };
+ const selectedSourceIds = collectSelectedSourceIds(composed);
+ const bindings = Object.fromEntries(
+ [...candidatesBySourceId.values()]
+ .filter(
+ (candidate): candidate is AgentModuleCandidate =>
+ selectedSourceIds.has(candidate.sourceId) && candidate.backing.kind !== "resource",
+ )
+ .map((candidate) => [candidate.sourceId, createCompiledModuleBinding(candidate)]),
+ );
+ return {
+ bindings,
+ composed,
+ orderedCandidates: graph.orderedCandidates.map(candidateFor),
+ projected,
+ sourcesBySourceId: new Map(
+ [...graph.sourcesBySourceId].map(([sourceId, entry]) => [
+ sourceId,
+ { ...entry, candidate: candidateFor(entry.candidate) } as ProjectedSource,
+ ]),
+ ),
+ subagentsBySourceId: new Map(
+ projected.subagents.map((entry) => [entry.candidate.sourceId, entry]),
+ ),
+ };
+}
+
+function finalizeCandidateExternalDependencies<TCandidate extends AgentSourceCandidate>(
+ candidate: TCandidate,
+ externalDependencies: readonly string[],
+): TCandidate {
+ if (candidate.backing.kind !== "filesystem") return candidate;
+ return {
+ ...candidate,
+ backing: finalizeBackingExternalDependencies(candidate.backing, externalDependencies),
+ } as TCandidate;
+}
+
+function finalizeDescriptorExternalDependencies(
+ descriptor: AgentSourceDescriptor,
+ externalDependencies: readonly string[],
+): AgentSourceDescriptor {
+ if (descriptor.backing.kind !== "filesystem") return descriptor;
+ return {
+ ...descriptor,
+ backing: finalizeBackingExternalDependencies(descriptor.backing, externalDependencies),
+ };
+}
+
+function finalizeBackingExternalDependencies(
+ backing: Extract<AgentSourceBacking, { readonly kind: "filesystem" }>,
+ externalDependencies: readonly string[],
+): Extract<AgentSourceBacking, { readonly kind: "filesystem" }> {
+ return {
+ ...backing,
+ externalDependencies: mergeExternalDependencies(
+ externalDependencies,
+ backing.externalDependencies,
+ ),
+ };
+}
diff --git a/packages/eve/src/compiler/normalize-agent-config.test.ts b/packages/eve/src/compiler/normalize-agent-config.test.ts
deleted file mode 100644
index 49a86469e..000000000
--- a/packages/eve/src/compiler/normalize-agent-config.test.ts
+++ /dev/null
@@ -1,111 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-import { createAgentSourceManifest, createModuleSourceRef } from "#discover/manifest.js";
-import { defineDynamic } from "#public/definitions/tool.js";
-import { chatgpt } from "#public/models/openai/index.js";
-import { compileAgentConfig } from "#compiler/normalize-agent-config.js";
-import type { ManifestCompileContext } from "#compiler/normalize-helpers.js";
-
-const mocks = vi.hoisted(() => ({
- loadModuleBackedDefinition: vi.fn(),
-}));
-
-vi.mock("#compiler/normalize-helpers.js", async (importOriginal) => ({
- ...(await importOriginal<typeof import("#compiler/normalize-helpers.js")>()),
- loadModuleBackedDefinition: mocks.loadModuleBackedDefinition,
-}));
-
-describe("compileAgentConfig", () => {
- beforeEach(() => {
- mocks.loadModuleBackedDefinition.mockReset();
- });
-
- it("compiles a dynamic model resolver without a model reference", async () => {
- mocks.loadModuleBackedDefinition.mockResolvedValue({
- model: defineDynamic({
- events: {
- "session.started": () => "openai/gpt-5.5-mini",
- "step.started": () => "openai/gpt-5.5",
- },
- }),
- });
-
- const manifest = createAgentSourceManifest({
- agentId: "app",
- agentRoot: "/app/agent",
- appRoot: "/app",
- configModule: createModuleSourceRef({
- logicalPath: "agent.ts",
- sourceId: "agent-config",
- }),
- });
-
- const modelCatalog = createModelCatalog();
- const compiled = await compileAgentConfig(manifest, { modelCatalog });
-
- expect(compiled.model).toBeUndefined();
- expect(compiled.dynamicModel).toEqual({
- eventNames: ["session.started", "step.started"],
- logicalPath: "agent.ts",
- sourceId: "agent-config",
- sourceKind: "module",
- });
- expect(modelCatalog.getModelLimits).not.toHaveBeenCalled();
- });
-
- it("compiles an eve-owned Codex model without AI Gateway metadata", async () => {
- mocks.loadModuleBackedDefinition.mockResolvedValue({ model: chatgpt("gpt-5.6-sol") });
- const manifest = createAgentSourceManifest({
- agentId: "app",
- agentRoot: "/app/agent",
- appRoot: "/app",
- configModule: createModuleSourceRef({ logicalPath: "agent.ts", sourceId: "agent-config" }),
- });
- const modelCatalog = createModelCatalog();
-
- const compiled = await compileAgentConfig(manifest, { modelCatalog });
-
- expect(compiled.model).toEqual(
- expect.objectContaining({
- id: "codex/gpt-5.6-sol",
- routing: { kind: "external", provider: "codex" },
- contextWindowTokens: 200_000,
- }),
- );
- expect(modelCatalog.getByProviderModelId).not.toHaveBeenCalled();
- expect(modelCatalog.getModelLimits).not.toHaveBeenCalled();
- });
-
- it("compiles an injected agent definition without reloading agent.ts", async () => {
- const manifest = createAgentSourceManifest({
- agentId: "researcher",
- agentRoot: "/app/agent/subagents/researcher",
- appRoot: "/app",
- configModule: createModuleSourceRef({
- logicalPath: "agent.ts",
- sourceId: "agent-config",
- }),
- });
-
- const compiled = await compileAgentConfig(
- manifest,
- { modelCatalog: createModelCatalog() },
- {
- definition: {
- model: "openai/gpt-5.5",
- },
- },
- );
-
- expect(mocks.loadModuleBackedDefinition).not.toHaveBeenCalled();
- expect(compiled.description).toBeUndefined();
- expect(compiled.source?.sourceId).toBe("agent-config");
- });
-});
-
-function createModelCatalog(): ManifestCompileContext["modelCatalog"] {
- return {
- getByProviderModelId: vi.fn(),
- getModelLimits: vi.fn(async () => ({ contextWindowTokens: 256_000 })),
- };
-}
diff --git a/packages/eve/src/compiler/normalize-agent-config.ts b/packages/eve/src/compiler/normalize-agent-config.ts
index e511a2863..c36927924 100644
--- a/packages/eve/src/compiler/normalize-agent-config.ts
+++ b/packages/eve/src/compiler/normalize-agent-config.ts
@@ -1,4 +1,4 @@
-import { isAbsolute, join, relative, resolve } from "node:path";
+import { isAbsolute, relative, resolve } from "node:path";
import type { AgentSourceManifest } from "#discover/manifest.js";
import { normalizeLogicalPath } from "#discover/filesystem.js";
@@ -7,7 +7,6 @@ import { serializeOutputSchema } from "#shared/tool-schema.js";
import { formatLanguageModelGatewayId } from "#internal/runtime-model.js";
import { classifyModelRouting } from "#internal/classify-model-routing.js";
import { isChatGptModelRouting } from "#shared/chatgpt-model.js";
-import { DEFAULT_AGENT_MODEL_ID } from "#shared/default-agent-model.js";
import { toErrorMessage } from "#shared/errors.js";
import { parseJsonObject, type JsonObject } from "#shared/json.js";
import type { ModuleSourceRef } from "#shared/source-ref.js";
@@ -22,6 +21,7 @@ import {
loadModuleBackedDefinition,
type ManifestCompileContext,
} from "#compiler/normalize-helpers.js";
+import type { CompiledModuleBinding } from "#compiler/source-graph.js";
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
@@ -33,27 +33,24 @@ export async function compileAgentConfig(
manifest: AgentSourceManifest,
context: ManifestCompileContext,
options: {
+ readonly binding: CompiledModuleBinding;
readonly definition?: unknown;
- } = {},
+ readonly source: ModuleSourceRef;
+ },
): Promise<CompiledAgentDefinition> {
- const configModule = manifest.configModule;
- const configModulePath =
- configModule === undefined ? undefined : formatAgentConfigModulePath(manifest, configModule);
- const hasInjectedDefinition = Object.hasOwn(options, "definition");
+ const configModule = options.source;
+ const configModulePath = formatAgentConfigModulePath(manifest, configModule, options.binding);
const definition = normalizeAgentDefinition(
- hasInjectedDefinition
+ Object.hasOwn(options, "definition")
? options.definition
- : configModule === undefined
- ? { model: DEFAULT_AGENT_MODEL_ID }
- : await loadModuleBackedDefinition({
- agentRoot: manifest.agentRoot,
- displayPath: configModulePath!,
- kind: "agent config",
- source: configModule,
- }),
- configModule === undefined
- ? `Expected the default agent config to match the public eve shape.`
- : `Expected the agent config export "${configModule.exportName ?? "default"}" from "${configModulePath}" to match the public eve shape.`,
+ : await loadModuleBackedDefinition({
+ binding: options.binding,
+ displayPath: configModulePath,
+ kind: "agent config",
+ registries: context.registries,
+ source: configModule,
+ }),
+ `Expected the agent config export "${configModule.exportName ?? "default"}" from "${configModulePath}" to match the public eve shape.`,
);
const dynamicModelDefinition = isDynamicModelDefinition(definition.model)
? definition.model
@@ -86,11 +83,12 @@ export async function compileAgentConfig(
name: string;
outputSchema?: JsonObject;
reasoning?: CompiledAgentDefinition["reasoning"];
- source?: ModuleSourceRef;
+ source: ModuleSourceRef;
limits?: CompiledAgentDefinition["limits"];
} = {
compaction,
name: manifest.agentId,
+ source: { ...configModule },
};
if (definition.description !== undefined) {
@@ -99,9 +97,6 @@ export async function compileAgentConfig(
let dynamicModel: CompiledAgentDefinition["dynamicModel"] | undefined;
if (dynamicModelDefinition !== undefined) {
- if (configModule === undefined) {
- throw new Error("Expected dynamic model definitions to be authored in agent.ts.");
- }
dynamicModel = {
eventNames: Object.keys(dynamicModelDefinition.events) as DynamicToolEventName[],
exportName: configModule.exportName,
@@ -141,15 +136,6 @@ export async function compileAgentConfig(
};
}
- if (configModule !== undefined) {
- compiledConfig.source = {
- exportName: configModule.exportName,
- sourceKind: "module",
- logicalPath: configModule.logicalPath,
- sourceId: configModule.sourceId,
- };
- }
-
if (definition.compaction?.model !== undefined) {
compaction.model = await normalizeAuthoredModelReference({
modelCatalog: context.modelCatalog,
@@ -306,9 +292,12 @@ async function normalizeAuthoredModelReference(input: {
function formatAgentConfigModulePath(
manifest: AgentSourceManifest,
configModule: ModuleSourceRef,
+ binding: CompiledModuleBinding,
): string {
- const configPath = join(manifest.agentRoot, configModule.logicalPath);
- return normalizeLogicalPath(relative(resolveTopLevelAgentRoot(manifest), configPath));
+ if (binding.backing.kind === "programmatic") return configModule.logicalPath;
+ return normalizeLogicalPath(
+ relative(resolveTopLevelAgentRoot(manifest), binding.backing.sourcePath),
+ );
}
function resolveTopLevelAgentRoot(manifest: AgentSourceManifest): string {
diff --git a/packages/eve/src/compiler/normalize-channel.ts b/packages/eve/src/compiler/normalize-channel.ts
index d35021c84..ce9296cd2 100644
--- a/packages/eve/src/compiler/normalize-channel.ts
+++ b/packages/eve/src/compiler/normalize-channel.ts
@@ -2,7 +2,7 @@ import { stripLogicalPathExtension } from "#discover/filesystem.js";
import type { ChannelSourceRef } from "#discover/manifest.js";
import { normalizeChannelDefinition } from "#internal/authored-definition/channel.js";
import { type ChannelRouteMethod, isDisabledRouteSentinel } from "#public/definitions/channel.js";
-import type { CompiledChannelEntry } from "#compiler/manifest.js";
+import type { CompiledChannelDefinition } from "#compiler/manifest.js";
import {
loadModuleBackedDefinition,
type ModuleBackedDefinitionLoadOptions,
@@ -22,25 +22,24 @@ import {
* the filesystem path; the URL path comes from the route's `path` field.
*/
export async function compileChannelDefinition(
- agentRoot: string,
+ _agentRoot: string,
source: ChannelSourceRef,
- options: ModuleBackedDefinitionLoadOptions = {},
-): Promise<CompiledChannelEntry | readonly CompiledChannelEntry[]> {
+ options: ModuleBackedDefinitionLoadOptions,
+): Promise<
+ | { readonly kind: "disabled"; readonly name: string }
+ | { readonly definitions: readonly CompiledChannelDefinition[]; readonly kind: "channel" }
+> {
const rawValue = await loadModuleBackedDefinition({
- agentRoot,
- externalDependencies: options.externalDependencies,
+ binding: options.binding,
kind: "channel",
+ registries: options.registries,
source,
});
const channelName = stripLogicalPathExtension(source.logicalPath).replace(/^channels\//, "");
if (isDisabledRouteSentinel(rawValue)) {
- return {
- kind: "disabled",
- name: channelName,
- logicalPath: source.logicalPath,
- };
+ return { kind: "disabled", name: channelName };
}
const definition = normalizeChannelDefinition(
@@ -48,18 +47,21 @@ export async function compileChannelDefinition(
`Expected the channel export "${source.exportName ?? "default"}" from "${source.logicalPath}" to match the public eve shape.`,
);
- return definition.routes.map((route) => ({
- kind: "channel" as const,
- name: channelName,
- logicalPath: source.logicalPath,
- method: route.method.toUpperCase() as ChannelRouteMethod,
- urlPath: route.path,
- sourceId: source.sourceId,
- sourceKind: "module" as const,
- exportName: source.exportName,
- adapterKind: extractAdapterKind(definition.adapter),
- cors: definition.cors,
- }));
+ return {
+ definitions: definition.routes.map((route) => ({
+ kind: "channel" as const,
+ name: channelName,
+ logicalPath: source.logicalPath,
+ method: route.method.toUpperCase() as ChannelRouteMethod,
+ urlPath: route.path,
+ sourceId: source.sourceId,
+ sourceKind: "module" as const,
+ exportName: source.exportName,
+ adapterKind: extractAdapterKind(definition.adapter),
+ cors: definition.cors,
+ })),
+ kind: "channel",
+ };
}
function extractAdapterKind(adapter: unknown): string | undefined {
diff --git a/packages/eve/src/compiler/normalize-connection.ts b/packages/eve/src/compiler/normalize-connection.ts
index a2684ae7f..efc3bf6a0 100644
--- a/packages/eve/src/compiler/normalize-connection.ts
+++ b/packages/eve/src/compiler/normalize-connection.ts
@@ -29,14 +29,14 @@ import { readConnectionProtocol } from "#public/definitions/connections/protocol
* runtime resolution) stays protocol-agnostic.
*/
export async function compileConnectionDefinition(
- agentRoot: string,
+ _agentRoot: string,
source: ConnectionSourceRef,
- options: ModuleBackedDefinitionLoadOptions = {},
+ options: ModuleBackedDefinitionLoadOptions,
): Promise<CompiledConnectionDefinition> {
const loaded = await loadModuleBackedDefinition({
- agentRoot,
- externalDependencies: options.externalDependencies,
+ binding: options.binding,
kind: "connection",
+ registries: options.registries,
source,
});
const protocol = readConnectionProtocol(loaded);
diff --git a/packages/eve/src/compiler/normalize-extension.test.ts b/packages/eve/src/compiler/normalize-extension.test.ts
deleted file mode 100644
index 9d5749949..000000000
--- a/packages/eve/src/compiler/normalize-extension.test.ts
+++ /dev/null
@@ -1,230 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import {
- applyOverrideDisables,
- composeExtensionSubagentSources,
- type CompiledExtensionContributions,
- mergeContributions,
-} from "#compiler/normalize-extension.js";
-import {
- createAgentSourceManifest,
- createLocalSubagentSourceRef,
- createModuleSourceRef,
-} from "#discover/manifest.js";
-
-// mergeContributions only reads each named contribution's identifier for dedup,
-// so minimal partial fixtures suffice.
-function contributions(
- overrides: Partial<CompiledExtensionContributions>,
-): CompiledExtensionContributions {
- return {
- channels: [],
- tools: [],
- dynamicTools: [],
- hooks: [],
- skills: [],
- dynamicSkills: [],
- dynamicInstructions: [],
- connections: [],
- instructions: [],
- schedules: [],
- ...overrides,
- };
-}
-
-describe("mergeContributions", () => {
- it("keeps the primary (consumer override) entry when a named contribution collides", () => {
- const primary = contributions({
- channels: [
- { name: "crm__webhook", logicalPath: "override", method: "GET" },
- { name: "crm__webhook", logicalPath: "override", method: "POST" },
- ] as never,
- tools: [{ name: "crm__search", logicalPath: "override" }] as never,
- connections: [{ connectionName: "crm__api", logicalPath: "override" }] as never,
- skills: [{ name: "crm__lookup", logicalPath: "override" }] as never,
- dynamicTools: [{ slug: "crm__dynamic", logicalPath: "override" }] as never,
- schedules: [{ name: "crm__sweep", logicalPath: "override" }] as never,
- });
- const secondary = contributions({
- channels: [
- { name: "crm__webhook", logicalPath: "extension", method: "POST" },
- { name: "crm__status", logicalPath: "extension", method: "GET" },
- ] as never,
- tools: [
- { name: "crm__search", logicalPath: "extension" },
- { name: "crm__list", logicalPath: "extension" },
- ] as never,
- connections: [{ connectionName: "crm__api", logicalPath: "extension" }] as never,
- skills: [{ name: "crm__lookup", logicalPath: "extension" }] as never,
- dynamicTools: [{ slug: "crm__dynamic", logicalPath: "extension" }] as never,
- schedules: [
- { name: "crm__sweep", logicalPath: "extension" },
- { name: "crm__digest", logicalPath: "extension" },
- ] as never,
- });
-
- const merged = mergeContributions(primary, secondary);
-
- expect(merged.channels).toEqual([
- { name: "crm__webhook", logicalPath: "override", method: "GET" },
- { name: "crm__webhook", logicalPath: "override", method: "POST" },
- { name: "crm__status", logicalPath: "extension", method: "GET" },
- ]);
- expect(merged.tools).toEqual([
- { name: "crm__search", logicalPath: "override" },
- { name: "crm__list", logicalPath: "extension" },
- ]);
- expect(merged.connections).toEqual([{ connectionName: "crm__api", logicalPath: "override" }]);
- expect(merged.skills).toEqual([{ name: "crm__lookup", logicalPath: "override" }]);
- expect(merged.dynamicTools).toEqual([{ slug: "crm__dynamic", logicalPath: "override" }]);
- expect(merged.schedules).toEqual([
- { name: "crm__sweep", logicalPath: "override" },
- { name: "crm__digest", logicalPath: "extension" },
- ]);
- });
-
- it("concatenates unnamed contributions from both sets", () => {
- const primary = contributions({
- hooks: [{ slug: "crm__before" }] as never,
- instructions: [{ content: "override", role: "system" }] as never,
- });
- const secondary = contributions({
- hooks: [{ slug: "crm__after" }] as never,
- instructions: [{ content: "extension", role: "user" }] as never,
- });
-
- const merged = mergeContributions(primary, secondary);
-
- expect(merged.hooks).toEqual([{ slug: "crm__before" }, { slug: "crm__after" }]);
- expect(merged.instructions).toEqual([
- { content: "override", role: "system" },
- { content: "extension", role: "user" },
- ]);
- });
-});
-
-describe("composeExtensionSubagentSources", () => {
- it("namespaces extension subagents and lets a directory override win", () => {
- const extensionRoot = "/packages/crm/dist/extension";
- const overrideRoot = "/app/agent/extensions/crm";
- const createSubagent = (root: string, subagentId: string) => {
- const agentRoot = `${root}/subagents/${subagentId}`;
- return createLocalSubagentSourceRef({
- entryPath: agentRoot,
- logicalPath: `subagents/${subagentId}`,
- manifest: createAgentSourceManifest({
- agentId: subagentId,
- agentRoot,
- appRoot: "/app",
- configModule: createModuleSourceRef({ logicalPath: "agent.ts" }),
- tools: [createModuleSourceRef({ logicalPath: "tools/search.ts" })],
- }),
- rootPath: agentRoot,
- subagentId,
- });
- };
- const extensionManifest = createAgentSourceManifest({
- agentRoot: extensionRoot,
- appRoot: "/packages/crm",
- subagents: [
- createSubagent(extensionRoot, "reviewer"),
- createSubagent(extensionRoot, "analyst"),
- ],
- });
- const overrideManifest = createAgentSourceManifest({
- agentRoot: overrideRoot,
- appRoot: "/app",
- subagents: [createSubagent(overrideRoot, "reviewer")],
- });
-
- const result = composeExtensionSubagentSources({
- consumerAgentRoot: "/app/agent",
- mount: {
- namespace: "crm",
- specifier: "@acme/crm",
- packageName: "@acme/crm",
- packageRoot: "/packages/crm",
- sourceRoot: extensionRoot,
- manifest: extensionManifest,
- externalDependencies: [],
- overrides: overrideManifest,
- },
- });
-
- expect(result.map((source) => [source.subagentId, source.sourceId])).toEqual([
- ["crm__reviewer", "ext-override:crm:subagents/reviewer"],
- ["crm__analyst", "ext:crm:subagents/analyst"],
- ]);
- expect(result[1]?.manifest.tools[0]?.sourceId).toBe(
- "ext:crm:subagents/analyst/tools/search.ts",
- );
- });
-});
-
-describe("applyOverrideDisables", () => {
- it("removes the disabled static extension tool while keeping the rest", () => {
- const merged = contributions({
- tools: [
- { name: "crm__search", logicalPath: "extension" },
- { name: "crm__list", logicalPath: "extension" },
- ] as never,
- });
-
- const result = applyOverrideDisables({
- merged,
- disables: [{ name: "crm__search", logicalPath: "tools/search.ts" }],
- extensionToolNames: new Set(["crm__search", "crm__list"]),
- extensionDynamicToolSlugs: new Set(),
- namespace: "crm",
- });
-
- expect(result.tools).toEqual([{ name: "crm__list", logicalPath: "extension" }]);
- });
-
- it("removes a disabled dynamic resolver slot by slug", () => {
- const merged = contributions({
- tools: [{ name: "crm__list", logicalPath: "extension" }] as never,
- dynamicTools: [{ slug: "crm__search", logicalPath: "extension" }] as never,
- });
-
- const result = applyOverrideDisables({
- merged,
- disables: [{ name: "crm__search", logicalPath: "tools/search.ts" }],
- extensionToolNames: new Set(["crm__list"]),
- extensionDynamicToolSlugs: new Set(["crm__search"]),
- namespace: "crm",
- });
-
- expect(result.dynamicTools).toEqual([]);
- expect(result.tools).toEqual([{ name: "crm__list", logicalPath: "extension" }]);
- });
-
- it("throws, listing static and dynamic slots, when the disable targets neither", () => {
- expect(() =>
- applyOverrideDisables({
- merged: contributions({
- tools: [{ name: "crm__list", logicalPath: "extension" }] as never,
- dynamicTools: [{ slug: "crm__lookup", logicalPath: "extension" }] as never,
- }),
- disables: [{ name: "crm__search", logicalPath: "tools/search.ts" }],
- extensionToolNames: new Set(["crm__list"]),
- extensionDynamicToolSlugs: new Set(["crm__lookup"]),
- namespace: "crm",
- }),
- ).toThrow(/no tool named "search"[\s\S]*It contributes: list, lookup/);
- });
-
- it("returns the merged set unchanged when nothing is disabled", () => {
- const merged = contributions({ tools: [{ name: "crm__list" }] as never });
-
- expect(
- applyOverrideDisables({
- merged,
- disables: [],
- extensionToolNames: new Set(["crm__list"]),
- extensionDynamicToolSlugs: new Set(),
- namespace: "crm",
- }),
- ).toBe(merged);
- });
-});
diff --git a/packages/eve/src/compiler/normalize-extension.ts b/packages/eve/src/compiler/normalize-extension.ts
deleted file mode 100644
index a4cca1b87..000000000
--- a/packages/eve/src/compiler/normalize-extension.ts
+++ /dev/null
@@ -1,527 +0,0 @@
-import { join as joinPath, relative as relativePath } from "node:path";
-
-import {
- createPathDerivedSourceId,
- type AgentSourceManifest,
- type LocalSubagentSourceRef,
- type ResolvedExtensionMount,
-} from "#discover/manifest.js";
-import type {
- CompiledChannelEntry,
- CompiledConnectionDefinition,
- CompiledDynamicInstructionsDefinition,
- CompiledDynamicSkillDefinition,
- CompiledDynamicToolDefinition,
- CompiledHookDefinition,
- CompiledInstructionsDefinition,
- CompiledScheduleDefinition,
- CompiledSkillDefinition,
- CompiledToolDefinition,
-} from "#compiler/manifest.js";
-import { compileChannelDefinition } from "#compiler/normalize-channel.js";
-import { compileConnectionDefinition } from "#compiler/normalize-connection.js";
-import type { ManifestCompileContext } from "#compiler/normalize-helpers.js";
-import { compileHookEntry } from "#compiler/normalize-hook.js";
-import { compileInstructionsEntry } from "#compiler/normalize-instructions.js";
-import { compileScheduleDefinition } from "#compiler/normalize-schedule.js";
-import { compileSkillSource } from "#compiler/normalize-skill.js";
-import { compileToolEntry } from "#compiler/normalize-tool.js";
-
-/**
- * Contributions one mounted extension composes into the consuming agent,
- * already namespaced by the mount and rebased onto the consumer's agent root.
- */
-export interface CompiledExtensionContributions {
- readonly channels: CompiledChannelEntry[];
- readonly tools: CompiledToolDefinition[];
- readonly dynamicTools: CompiledDynamicToolDefinition[];
- readonly hooks: CompiledHookDefinition[];
- readonly skills: CompiledSkillDefinition[];
- readonly dynamicSkills: CompiledDynamicSkillDefinition[];
- readonly dynamicInstructions: CompiledDynamicInstructionsDefinition[];
- readonly connections: CompiledConnectionDefinition[];
- readonly instructions: CompiledInstructionsDefinition[];
- readonly schedules: CompiledScheduleDefinition[];
-}
-
-/**
- * Compiles one mounted extension's source tree and namespaces its
- * contributions by the mount name. Module-backed contributions keep loading
- * from the extension package because their `logicalPath` is rebased to a
- * consumer-relative path — the module-map codegen resolves it against the
- * consumer's agent root, reaching into the extension package unchanged.
- *
- * When the mount was authored as a directory (`extensions/<ns>/`), any
- * consumer-authored override slots are composed under the same namespace and
- * win on name collision: an override tool `<ns>__search` shadows the
- * extension's own `<ns>__search`.
- */
-export async function compileExtensionContributions(input: {
- readonly mount: ResolvedExtensionMount;
- readonly context: ManifestCompileContext;
- readonly consumerAgentRoot: string;
- readonly externalDependencies: readonly string[];
-}): Promise<CompiledExtensionContributions> {
- const { mount, consumerAgentRoot } = input;
- const options = { externalDependencies: input.externalDependencies };
-
- const base = await composeManifestContributions({
- manifest: mount.manifest,
- namespace: mount.namespace,
- consumerAgentRoot,
- options,
- sourceIdScope: `ext:${mount.namespace}`,
- role: "extension",
- });
-
- if (mount.overrides === undefined) {
- return base.contributions;
- }
-
- // Overrides are consumer-authored files, so they are NOT extension-scoped. The
- // `ext-override:` prefix keeps their module-map keys distinct from the
- // extension's own `ext:<ns>:` modules while deliberately not matching the
- // loader's `^ext:<ns>:` scope pattern, so dev and prod both treat them unscoped.
- const overrides = await composeManifestContributions({
- manifest: mount.overrides,
- namespace: mount.namespace,
- consumerAgentRoot,
- options,
- sourceIdScope: `ext-override:${mount.namespace}`,
- role: "override",
- });
-
- // Consumer overrides win: list them first so first-registration-wins dedup
- // keeps the override over the extension's same-named contribution.
- const merged = mergeContributions(overrides.contributions, base.contributions);
-
- return applyOverrideDisables({
- merged,
- disables: overrides.disabledToolTargets,
- extensionToolNames: new Set(base.contributions.tools.map((tool) => tool.name)),
- extensionDynamicToolSlugs: new Set(base.contributions.dynamicTools.map((tool) => tool.slug)),
- namespace: mount.namespace,
- });
-}
-
-/** Composes one mount's root-visible subagents under its namespace. */
-export function composeExtensionSubagentSources(input: {
- readonly consumerAgentRoot: string;
- readonly mount: ResolvedExtensionMount;
-}): LocalSubagentSourceRef[] {
- const base = scopeExtensionSubagents({
- consumerAgentRoot: input.consumerAgentRoot,
- manifest: input.mount.manifest,
- namespace: input.mount.namespace,
- sourceIdScope: `ext:${input.mount.namespace}`,
- sourceRoot: input.mount.sourceRoot,
- });
- if (input.mount.overrides === undefined) {
- return base;
- }
-
- const overrides = scopeExtensionSubagents({
- consumerAgentRoot: input.consumerAgentRoot,
- manifest: input.mount.overrides,
- namespace: input.mount.namespace,
- sourceIdScope: `ext-override:${input.mount.namespace}`,
- sourceRoot: input.mount.overrides.agentRoot,
- });
- return mergeExtensionSubagentSources(overrides, base);
-}
-
-/** Returns authored and mounted-extension subagents visible from one agent node. */
-export function composeAgentSubagentSources(
- manifest: AgentSourceManifest,
-): LocalSubagentSourceRef[] {
- return [
- ...manifest.subagents,
- ...[...manifest.resolvedExtensions]
- .sort((left, right) => left.namespace.localeCompare(right.namespace))
- .flatMap((mount) =>
- composeExtensionSubagentSources({ consumerAgentRoot: manifest.agentRoot, mount }),
- ),
- ];
-}
-
-/** Earlier entries win, matching directory-override precedence for other slots. */
-export function mergeExtensionSubagentSources(
- primary: readonly LocalSubagentSourceRef[],
- secondary: readonly LocalSubagentSourceRef[],
-): LocalSubagentSourceRef[] {
- return dedupeBy([...primary, ...secondary], (source) => source.subagentId);
-}
-
-function scopeExtensionSubagents(input: {
- readonly consumerAgentRoot: string;
- readonly manifest: AgentSourceManifest;
- readonly namespace: string;
- readonly sourceIdScope: string;
- readonly sourceRoot: string;
-}): LocalSubagentSourceRef[] {
- return input.manifest.subagents.map((source) => ({
- ...scopeExtensionSubagentSource(source, input.sourceRoot, input.sourceIdScope),
- logicalPath: relativePath(input.consumerAgentRoot, source.entryPath).replaceAll("\\", "/"),
- subagentId: `${input.namespace}__${source.subagentId}`,
- }));
-}
-
-function scopeExtensionSubagentSource(
- source: LocalSubagentSourceRef,
- sourceRoot: string,
- sourceIdScope: string,
-): LocalSubagentSourceRef {
- return {
- ...source,
- manifest: scopeExtensionSubagentManifest(source.manifest, sourceRoot, sourceIdScope),
- sourceId: scopeExtensionSourceId(sourceRoot, source.entryPath, sourceIdScope),
- };
-}
-
-function scopeExtensionSubagentManifest(
- manifest: AgentSourceManifest,
- sourceRoot: string,
- sourceIdScope: string,
-): AgentSourceManifest {
- const scopeRef = <T extends { readonly logicalPath: string; readonly sourceId: string }>(
- source: T,
- ): T => ({
- ...source,
- sourceId: scopeExtensionSourceId(
- sourceRoot,
- joinPath(manifest.agentRoot, source.logicalPath),
- sourceIdScope,
- ),
- });
-
- return {
- ...manifest,
- channels: manifest.channels.map(scopeRef),
- connections: manifest.connections.map(scopeRef),
- ...(manifest.configModule === undefined
- ? {}
- : { configModule: scopeRef(manifest.configModule) }),
- extensions: manifest.extensions.map(scopeRef),
- hooks: manifest.hooks.map(scopeRef),
- instructions: manifest.instructions.map(scopeRef),
- lib: manifest.lib.map(scopeRef),
- sandbox: manifest.sandbox === null ? null : scopeRef(manifest.sandbox),
- sandboxWorkspaces: manifest.sandboxWorkspaces.map(scopeRef),
- schedules: manifest.schedules.map(scopeRef),
- skills: manifest.skills.map(scopeRef),
- subagents: manifest.subagents.map((source) =>
- scopeExtensionSubagentSource(source, sourceRoot, sourceIdScope),
- ),
- tools: manifest.tools.map(scopeRef),
- };
-}
-
-function scopeExtensionSourceId(
- sourceRoot: string,
- sourcePath: string,
- sourceIdScope: string,
-): string {
- const logicalPath = relativePath(sourceRoot, sourcePath).replaceAll("\\", "/");
- return `${sourceIdScope}:${createPathDerivedSourceId(logicalPath)}`;
-}
-
-export interface DisabledToolTarget {
- /** Namespaced target, e.g. `crm__search`. */
- readonly name: string;
- /** Override-relative authored path, e.g. `tools/search.ts`, for diagnostics. */
- readonly logicalPath: string;
-}
-
-interface ComposedContributions {
- readonly contributions: CompiledExtensionContributions;
- readonly disabledToolTargets: readonly DisabledToolTarget[];
-}
-
-/**
- * Removes the extension tools an override slot opted out of with `disableTool()`.
- * A `disableTool()` targets a slot by name, so it removes the extension's
- * same-named static tool or dynamic resolver — whichever kind occupies the slot.
- * A disable that matches neither throws rather than silently disabling nothing.
- *
- * Exported for unit testing.
- */
-export function applyOverrideDisables(input: {
- readonly merged: CompiledExtensionContributions;
- readonly disables: readonly DisabledToolTarget[];
- readonly extensionToolNames: ReadonlySet<string>;
- readonly extensionDynamicToolSlugs: ReadonlySet<string>;
- readonly namespace: string;
-}): CompiledExtensionContributions {
- if (input.disables.length === 0) {
- return input.merged;
- }
- const prefixLength = input.namespace.length + 2; // strip the `<ns>__` prefix
- const removed = new Set<string>();
- for (const disable of input.disables) {
- if (
- !input.extensionToolNames.has(disable.name) &&
- !input.extensionDynamicToolSlugs.has(disable.name)
- ) {
- const available = [...input.extensionToolNames, ...input.extensionDynamicToolSlugs]
- .map((name) => name.slice(prefixLength))
- .sort();
- throw new Error(
- `The override "agent/extensions/${input.namespace}/${disable.logicalPath}" calls disableTool(), ` +
- `but the "${input.namespace}" extension contributes no tool named "${disable.name.slice(prefixLength)}". ` +
- `It contributes: ${available.length > 0 ? available.join(", ") : "(no tools)"}.`,
- );
- }
- removed.add(disable.name);
- }
- return {
- ...input.merged,
- tools: input.merged.tools.filter((tool) => !removed.has(tool.name)),
- dynamicTools: input.merged.dynamicTools.filter((tool) => !removed.has(tool.slug)),
- };
-}
-
-interface ComposeOptions {
- readonly externalDependencies: readonly string[];
-}
-
-/**
- * Compiles one agent-shaped manifest into namespaced extension contributions
- * rebased onto the consumer's agent root. Used for both the extension's own
- * source tree and a directory mount's consumer override slots.
- */
-async function composeManifestContributions(input: {
- readonly manifest: AgentSourceManifest;
- readonly namespace: string;
- readonly consumerAgentRoot: string;
- readonly options: ComposeOptions;
- readonly sourceIdScope: string;
- readonly role: "extension" | "override";
-}): Promise<ComposedContributions> {
- const { manifest, namespace, consumerAgentRoot, options, sourceIdScope, role } = input;
- const sourceRoot = manifest.agentRoot;
- const prefix = `${namespace}__`;
- const scopeSourceId = (sourceId: string): string => `${sourceIdScope}:${sourceId}`;
- const rebase = (logicalPath: string): string =>
- relativePath(consumerAgentRoot, joinPath(sourceRoot, logicalPath)).replaceAll("\\", "/");
-
- const channels = (
- await Promise.all(
- manifest.channels.map((source) => compileChannelDefinition(sourceRoot, source, options)),
- )
- )
- .flat()
- .map((channel): CompiledChannelEntry =>
- channel.kind === "disabled"
- ? {
- ...channel,
- name: `${prefix}${channel.name}`,
- logicalPath: rebase(channel.logicalPath),
- }
- : {
- ...channel,
- name: `${prefix}${channel.name}`,
- sourceId: scopeSourceId(channel.sourceId),
- logicalPath: rebase(channel.logicalPath),
- },
- );
-
- const tools: CompiledToolDefinition[] = [];
- const dynamicTools: CompiledDynamicToolDefinition[] = [];
- const disabledToolTargets: DisabledToolTarget[] = [];
- for (const source of manifest.tools) {
- const entry = await compileToolEntry(sourceRoot, source, options);
- if (entry.kind === "tool") {
- tools.push({
- ...entry.definition,
- name: `${prefix}${entry.definition.name}`,
- sourceId: scopeSourceId(entry.definition.sourceId),
- logicalPath: rebase(entry.definition.logicalPath),
- });
- } else if (entry.kind === "dynamic-tool") {
- dynamicTools.push({
- ...entry.definition,
- slug: `${prefix}${entry.definition.slug}`,
- extensionNamespace: namespace,
- sourceId: scopeSourceId(entry.definition.sourceId),
- logicalPath: rebase(entry.definition.logicalPath),
- });
- } else if (entry.kind === "workflow-tool") {
- throw new Error(
- `${describeExtensionSource(role, namespace, source.logicalPath)} enables the Workflow tool, ` +
- `but the Workflow tool is the consuming agent's to enable, not an extension's. Remove it.`,
- );
- } else if (entry.kind === "web-search-tool") {
- throw new Error(
- `${describeExtensionSource(role, namespace, source.logicalPath)} configures web search, ` +
- `but the web search provider is the consuming agent's to configure, not an extension's. Remove it.`,
- );
- } else if (role === "extension") {
- throw new Error(
- `${describeExtensionSource(role, namespace, source.logicalPath)} calls disableTool(), ` +
- `but an extension cannot disable framework tools — that is the consuming agent's to own. Remove it.`,
- );
- } else {
- disabledToolTargets.push({ name: `${prefix}${entry.name}`, logicalPath: source.logicalPath });
- }
- }
-
- const hooks: CompiledHookDefinition[] = manifest.hooks.map((source) => {
- const hook = compileHookEntry(source);
- return {
- ...hook,
- slug: `${prefix}${hook.slug}`,
- sourceId: scopeSourceId(hook.sourceId),
- logicalPath: rebase(hook.logicalPath),
- };
- });
-
- const skills: CompiledSkillDefinition[] = [];
- const dynamicSkills: CompiledDynamicSkillDefinition[] = [];
- for (const source of manifest.skills) {
- const entry = await compileSkillSource(sourceRoot, source, options);
- if (entry.kind === "skill") {
- skills.push({
- ...entry.definition,
- name: `${prefix}${entry.definition.name}`,
- sourceId: scopeSourceId(entry.definition.sourceId),
- logicalPath: rebase(entry.definition.logicalPath),
- });
- } else {
- dynamicSkills.push({
- ...entry.definition,
- slug: `${prefix}${entry.definition.slug}`,
- extensionNamespace: namespace,
- sourceId: scopeSourceId(entry.definition.sourceId),
- logicalPath: rebase(entry.definition.logicalPath),
- });
- }
- }
-
- const connections: CompiledConnectionDefinition[] = (
- await Promise.all(
- manifest.connections.map((source) =>
- compileConnectionDefinition(sourceRoot, source, options),
- ),
- )
- ).map((connection) => ({
- ...connection,
- connectionName: `${prefix}${connection.connectionName}`,
- sourceId: scopeSourceId(connection.sourceId),
- logicalPath: rebase(connection.logicalPath),
- }));
-
- const dynamicInstructions: CompiledDynamicInstructionsDefinition[] = [];
- const instructions: CompiledInstructionsDefinition[] = [];
- for (const source of manifest.instructions) {
- const entry = await compileInstructionsEntry(sourceRoot, source, options);
- if (entry.kind === "instructions") {
- instructions.push({
- ...entry.definition,
- sourceId: scopeSourceId(entry.definition.sourceId),
- logicalPath: rebase(entry.definition.logicalPath),
- });
- } else {
- dynamicInstructions.push({
- ...entry.definition,
- slug: `${prefix}${entry.definition.slug}`,
- sourceId: scopeSourceId(entry.definition.sourceId),
- logicalPath: rebase(entry.definition.logicalPath),
- });
- }
- }
-
- const schedules = await Promise.all(
- manifest.schedules.map(async (source) => {
- const schedule = await compileScheduleDefinition(sourceRoot, source, options);
- return {
- ...schedule,
- name: `${prefix}${schedule.name}`,
- sourceId: scopeSourceId(schedule.sourceId),
- logicalPath: rebase(schedule.logicalPath),
- };
- }),
- );
-
- return {
- contributions: {
- channels,
- tools,
- dynamicTools,
- hooks,
- skills,
- dynamicSkills,
- dynamicInstructions,
- connections,
- instructions,
- schedules,
- },
- disabledToolTargets,
- };
-}
-
-function describeExtensionSource(
- role: "extension" | "override",
- namespace: string,
- logicalPath: string,
-): string {
- return role === "override"
- ? `The override "agent/extensions/${namespace}/${logicalPath}"`
- : `The "${namespace}" extension's "${logicalPath}"`;
-}
-
-/**
- * Merges two composed contribution sets with earlier-set-wins precedence per
- * composed name. Named contributions dedup by their composed identifier so
- * an override shadows the extension's same-named entry. Channel entries dedup
- * as a group so every route from the winning channel is preserved. Unnamed
- * contributions (hooks, dynamic skills, dynamic instructions, static
- * instructions) simply concatenate.
- *
- * Exported for unit testing: passing the consumer overrides as `primary` and
- * the extension's own contributions as `secondary` yields consumer-wins
- * shadowing on name collision.
- */
-export function mergeContributions(
- primary: CompiledExtensionContributions,
- secondary: CompiledExtensionContributions,
-): CompiledExtensionContributions {
- const primaryChannelNames = new Set(primary.channels.map((channel) => channel.name));
- return {
- channels: [
- ...primary.channels,
- ...secondary.channels.filter((channel) => !primaryChannelNames.has(channel.name)),
- ],
- tools: dedupeBy([...primary.tools, ...secondary.tools], (tool) => tool.name),
- dynamicTools: dedupeBy(
- [...primary.dynamicTools, ...secondary.dynamicTools],
- (tool) => tool.slug,
- ),
- connections: dedupeBy(
- [...primary.connections, ...secondary.connections],
- (connection) => connection.connectionName,
- ),
- skills: dedupeBy([...primary.skills, ...secondary.skills], (skill) => skill.name),
- schedules: dedupeBy(
- [...primary.schedules, ...secondary.schedules],
- (schedule) => schedule.name,
- ),
- hooks: [...primary.hooks, ...secondary.hooks],
- dynamicSkills: [...primary.dynamicSkills, ...secondary.dynamicSkills],
- dynamicInstructions: [...primary.dynamicInstructions, ...secondary.dynamicInstructions],
- instructions: [...primary.instructions, ...secondary.instructions],
- };
-}
-
-function dedupeBy<T>(items: readonly T[], key: (item: T) => string): T[] {
- const seen = new Set<string>();
- const result: T[] = [];
- for (const item of items) {
- const identifier = key(item);
- if (seen.has(identifier)) {
- continue;
- }
- seen.add(identifier);
- result.push(item);
- }
- return result;
-}
diff --git a/packages/eve/src/compiler/normalize-helpers.ts b/packages/eve/src/compiler/normalize-helpers.ts
index 315cc4931..bf3178d39 100644
--- a/packages/eve/src/compiler/normalize-helpers.ts
+++ b/packages/eve/src/compiler/normalize-helpers.ts
@@ -1,16 +1,17 @@
-import { join } from "node:path";
-
import {
getAuthoredModuleExport,
materializeAuthoredModuleExport,
} from "#internal/authored-module.js";
-import {
- type AuthoredModuleLoadOptions,
- loadAuthoredModuleNamespace,
-} from "#internal/authored-module-loader.js";
+import { loadAuthoredModuleNamespace } from "#internal/authored-module-loader.js";
import { toErrorMessage } from "#shared/errors.js";
import type { ModuleSourceRef } from "#shared/source-ref.js";
import type { CompiledRuntimeModelCatalogLoader } from "#compiler/model-catalog.js";
+import {
+ loadProgrammaticModuleNamespace,
+ type AgentSourceRegistry,
+ type CompiledModuleBinding,
+ type AgentSourceOwner,
+} from "#compiler/source-graph.js";
const SANDBOX_PARENT_DEFINITION_MARKER = Symbol.for("eve.sandbox-parent-definition");
@@ -24,10 +25,28 @@ const SANDBOX_PARENT_DEFINITION_MARKER = Symbol.for("eve.sandbox-parent-definiti
*/
export interface ManifestCompileContext {
readonly modelCatalog: CompiledRuntimeModelCatalogLoader;
+ readonly registries: readonly AgentSourceRegistry[];
}
export interface ModuleBackedDefinitionLoadOptions {
- readonly externalDependencies?: AuthoredModuleLoadOptions["externalDependencies"];
+ readonly binding: CompiledModuleBinding;
+ readonly registries: readonly AgentSourceRegistry[];
+}
+
+export interface SourceDefinitionCompileOptions {
+ readonly binding?: CompiledModuleBinding;
+ readonly owner: AgentSourceOwner;
+ readonly registries?: readonly AgentSourceRegistry[];
+}
+
+export function requireModuleBackedDefinitionLoadOptions(
+ options: SourceDefinitionCompileOptions,
+ logicalPath: string,
+): ModuleBackedDefinitionLoadOptions {
+ if (options.binding === undefined || options.registries === undefined) {
+ throw new Error(`Module-backed source "${logicalPath}" requires a compiled binding.`);
+ }
+ return { binding: options.binding, registries: options.registries };
}
/**
@@ -40,16 +59,26 @@ export interface ModuleBackedDefinitionLoadOptions {
* authored file failed.
*/
export async function loadModuleBackedDefinition(input: {
- readonly agentRoot: string;
+ readonly binding: CompiledModuleBinding;
readonly displayPath?: string;
- readonly externalDependencies?: ModuleBackedDefinitionLoadOptions["externalDependencies"];
readonly kind: string;
+ readonly registries: readonly AgentSourceRegistry[];
readonly source: ModuleSourceRef;
}): Promise<unknown> {
- const moduleNamespace = await loadAuthoredModuleNamespace(
- join(input.agentRoot, input.source.logicalPath),
- { externalDependencies: input.externalDependencies },
- );
+ if (input.binding.logicalPath !== input.source.logicalPath) {
+ throw new Error(
+ `Compiled binding "${input.source.sourceId}" targets "${input.binding.logicalPath}", not "${input.source.logicalPath}".`,
+ );
+ }
+ const moduleNamespace =
+ input.binding.backing.kind === "filesystem"
+ ? await loadAuthoredModuleNamespace(input.binding.backing.sourcePath, {
+ externalDependencies: input.binding.backing.externalDependencies,
+ })
+ : await loadProgrammaticModuleNamespace({
+ backing: input.binding.backing,
+ registries: input.registries,
+ });
const exportValue = getAuthoredModuleExport(moduleNamespace, input.source);
// defineSandbox marks parent selectors so they remain distinguishable from
diff --git a/packages/eve/src/compiler/normalize-hook.test.ts b/packages/eve/src/compiler/normalize-hook.test.ts
deleted file mode 100644
index 0a99c99b3..000000000
--- a/packages/eve/src/compiler/normalize-hook.test.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { compileHookEntry } from "./normalize-hook.js";
-
-describe("compileHookEntry", () => {
- it("derives the slug from the path-relative file location", () => {
- expect(
- compileHookEntry({
- logicalPath: "hooks/audit.ts",
- sourceId: "hooks/audit.ts",
- sourceKind: "module",
- }),
- ).toEqual({
- logicalPath: "hooks/audit.ts",
- slug: "audit",
- sourceId: "hooks/audit.ts",
- sourceKind: "module",
- });
- });
-
- it("preserves nested directory segments inside the slug", () => {
- expect(
- compileHookEntry({
- logicalPath: "hooks/auth/guard.ts",
- sourceId: "hooks/auth/guard.ts",
- sourceKind: "module",
- }).slug,
- ).toBe("auth/guard");
- });
-
- it("preserves an authored exportName when present", () => {
- expect(
- compileHookEntry({
- exportName: "guard",
- logicalPath: "hooks/auth.ts",
- sourceId: "hooks/auth.ts",
- sourceKind: "module",
- }).exportName,
- ).toBe("guard");
- });
-});
diff --git a/packages/eve/src/compiler/normalize-hook.ts b/packages/eve/src/compiler/normalize-hook.ts
index 2bb31262c..00b9c95a6 100644
--- a/packages/eve/src/compiler/normalize-hook.ts
+++ b/packages/eve/src/compiler/normalize-hook.ts
@@ -1,18 +1,44 @@
-import { stripLogicalPathExtension } from "../discover/filesystem.js";
+import { stripLogicalPathExtension } from "#discover/filesystem.js";
import type { HookSourceRef } from "#discover/manifest.js";
-import type { CompiledHookDefinition } from "./manifest.js";
+import type { CompiledHookDefinition } from "#compiler/manifest.js";
+import {
+ loadModuleBackedDefinition,
+ type ModuleBackedDefinitionLoadOptions,
+} from "#compiler/normalize-helpers.js";
+import { expectFunction, expectObjectRecord } from "#internal/authored-module.js";
+
+/** Compiles and validates one selected hook while preserving its exact subscriptions. */
+export async function compileHookEntry(
+ source: HookSourceRef,
+ options: ModuleBackedDefinitionLoadOptions,
+): Promise<CompiledHookDefinition> {
+ const loaded = expectObjectRecord(
+ await loadModuleBackedDefinition({
+ binding: options.binding,
+ kind: "hook",
+ registries: options.registries,
+ source,
+ }),
+ `Expected the hook export "${source.exportName ?? "default"}" from "${source.logicalPath}" to return an object.`,
+ );
+ const events =
+ loaded.events === undefined
+ ? {}
+ : expectObjectRecord(
+ loaded.events,
+ `Expected the hook export "${source.exportName ?? "default"}" from "${source.logicalPath}" to expose events as an object.`,
+ );
+ const eventNames = Object.entries(events).flatMap(([name, handler]) => {
+ if (handler === undefined) return [];
+ expectFunction(
+ handler,
+ `Expected the hook export "${source.exportName ?? "default"}" from "${source.logicalPath}" to provide a function for events.${name}.`,
+ );
+ return [name];
+ });
-/**
- * Compiles one authored hook module into the manifest entry stored on
- * the compiled agent node.
- *
- * Hook event handlers are arbitrary functions and cannot be statically
- * validated at compile time — the normalization step only derives the
- * path-relative slug used for diagnostics and ordering. Per-handler
- * validation lives in the runtime resolver.
- */
-export function compileHookEntry(source: HookSourceRef): CompiledHookDefinition {
return {
+ eventNames,
exportName: source.exportName,
logicalPath: source.logicalPath,
slug: stripLogicalPathExtension(source.logicalPath).replace(/^hooks\//, ""),
diff --git a/packages/eve/src/compiler/normalize-instructions.ts b/packages/eve/src/compiler/normalize-instructions.ts
index 773e8e27d..d900b99c5 100644
--- a/packages/eve/src/compiler/normalize-instructions.ts
+++ b/packages/eve/src/compiler/normalize-instructions.ts
@@ -7,7 +7,8 @@ import type {
} from "#compiler/manifest.js";
import {
loadModuleBackedDefinition,
- type ModuleBackedDefinitionLoadOptions,
+ requireModuleBackedDefinitionLoadOptions,
+ type SourceDefinitionCompileOptions,
} from "#compiler/normalize-helpers.js";
import {
assertResolverOnlyDynamicSentinel,
@@ -44,9 +45,9 @@ export type CompiledInstructionsEntry =
* runtime.
*/
export async function compileInstructionsEntry(
- agentRoot: string,
+ _agentRoot: string,
source: InstructionsSourceRef,
- options: ModuleBackedDefinitionLoadOptions = {},
+ options: SourceDefinitionCompileOptions,
): Promise<CompiledInstructionsEntry> {
if (source.sourceKind === "markdown") {
const definition = normalizeInstructionsDefinition(
@@ -58,6 +59,7 @@ export async function compileInstructionsEntry(
definition: {
name: stripLogicalPathExtension(source.logicalPath),
logicalPath: source.logicalPath,
+ owner: options.owner,
content: definition.content,
role: definition.role,
sourceId: source.sourceId,
@@ -66,10 +68,11 @@ export async function compileInstructionsEntry(
};
}
+ const loadOptions = requireModuleBackedDefinitionLoadOptions(options, source.logicalPath);
const exportValue = await loadModuleBackedDefinition({
- agentRoot,
- externalDependencies: options.externalDependencies,
+ binding: loadOptions.binding,
kind: "instructions",
+ registries: loadOptions.registries,
source,
});
@@ -126,7 +129,7 @@ export async function compileInstructionsEntry(
export async function compileInstructions(
agentRoot: string,
source: InstructionsSourceRef,
- options: ModuleBackedDefinitionLoadOptions = {},
+ options: SourceDefinitionCompileOptions,
): Promise<CompiledInstructionsDefinition> {
const entry = await compileInstructionsEntry(agentRoot, source, options);
if (entry.kind === "dynamic-instructions") {
diff --git a/packages/eve/src/compiler/normalize-manifest-helpers.ts b/packages/eve/src/compiler/normalize-manifest-helpers.ts
new file mode 100644
index 000000000..3593df167
--- /dev/null
+++ b/packages/eve/src/compiler/normalize-manifest-helpers.ts
@@ -0,0 +1,197 @@
+import { posix } from "node:path";
+
+import { mountRefNamespace, packageStateNamespace } from "#discover/extensions.js";
+import type { AgentSourceManifest, LocalSubagentSourceRef } from "#discover/manifest.js";
+import type {
+ CompiledAgentDefinition,
+ CompiledExtensionMount,
+ CompiledRemoteAgentNode,
+} from "#compiler/manifest.js";
+import { ROOT_COMPILED_AGENT_NODE_ID } from "#compiler/manifest.js";
+import type { ModuleSourceRef } from "#shared/source-ref.js";
+import { normalizeSubagentConfig } from "#compiler/normalize-subagent.js";
+import {
+ canonicalSourceSlot,
+ type AgentModuleCandidate,
+ type AgentSourceOwner,
+ type AgentSourceRegistry,
+ type ComposedAgentModuleCandidates,
+ type CompiledModuleBinding,
+} from "#compiler/source-graph.js";
+
+export function collectSelectedSourceIds(composed: ComposedAgentModuleCandidates): Set<string> {
+ return new Set([...composed.selected.values()].map((candidate) => candidate.sourceId));
+}
+
+export function assertRootOnlyConfig(
+ config: CompiledAgentDefinition,
+ isRoot: boolean,
+ agentId: string,
+): void {
+ if (isRoot) return;
+ if (config.experimental?.workflow !== undefined) {
+ throw new Error(
+ `Workflow runtime configuration is only supported on the root agent config. Remove "experimental.workflow" from "${agentId}".`,
+ );
+ }
+ if (config.experimental?.tasks !== undefined) {
+ throw new Error(
+ `Background tasks are only supported on the root agent config. Remove "experimental.tasks" from "${agentId}".`,
+ );
+ }
+}
+
+export function assertApplicationOverlayCanApplyToAllNodes(logicalPaths: readonly string[]): void {
+ const unsupported = logicalPaths.find((logicalPath) => {
+ const slot = canonicalSourceSlot(logicalPath);
+ return (
+ slot === "agent" ||
+ slot.startsWith("channels/") ||
+ slot.startsWith("schedules/") ||
+ slot.startsWith("subagents/") ||
+ slot.startsWith("extensions/")
+ );
+ });
+ if (unsupported !== undefined) {
+ throw new Error(
+ `Application programmatic source registered for all local nodes cannot declare "${unsupported}".`,
+ );
+ }
+}
+
+export function assertUniqueRegistryIds(registries: readonly AgentSourceRegistry[]): void {
+ const ids = new Set<string>();
+ for (const registry of registries) {
+ for (const sourceId of registry.sources.keys()) {
+ if (ids.has(sourceId)) {
+ throw new Error(`Programmatic agent source id "${sourceId}" is registered more than once.`);
+ }
+ ids.add(sourceId);
+ }
+ }
+}
+
+export function assertRootOwnedSpecialTool(candidate: AgentModuleCandidate, label: string): void {
+ if (candidate.nodeId !== ROOT_COMPILED_AGENT_NODE_ID) {
+ throw new Error(`${label} can only be enabled on the root agent.`);
+ }
+ assertNonExtensionSpecialTool(candidate, label);
+}
+
+export function assertNonExtensionSpecialTool(
+ candidate: AgentModuleCandidate,
+ label: string,
+): void {
+ if (candidate.owner.kind === "extension") {
+ throw new Error(`${label} cannot be configured by an extension source.`);
+ }
+}
+
+export function withExtensionNamespace<T extends { readonly extensionNamespace?: string }>(
+ definition: T,
+ owner: AgentSourceOwner,
+): T {
+ return owner.kind === "extension"
+ ? { ...definition, extensionNamespace: owner.namespace }
+ : definition;
+}
+
+export function assertUniqueBy<T>(
+ values: readonly T[],
+ identity: (value: T) => string,
+ label: string,
+): void {
+ const seen = new Set<string>();
+ for (const value of values) {
+ const key = identity(value);
+ if (seen.has(key)) throw new Error(`Compiled ${label} "${key}" is declared more than once.`);
+ seen.add(key);
+ }
+}
+
+export function expectSubagentDescription(
+ config: CompiledAgentDefinition,
+ source: LocalSubagentSourceRef,
+): string {
+ if (config.description === undefined || config.description.trim().length === 0) {
+ throw new Error(`Subagent "${source.logicalPath}" must define a non-empty description.`);
+ }
+ return config.description;
+}
+
+export function createCompiledRemoteAgent(input: {
+ readonly binding: CompiledModuleBinding;
+ readonly definition: Extract<
+ ReturnType<typeof normalizeSubagentConfig>,
+ { readonly kind: "remote" }
+ >;
+ readonly nodeId: string;
+ readonly owner: AgentSourceOwner;
+ readonly parentNodeId: string;
+ readonly source: LocalSubagentSourceRef;
+ readonly sourceRef: ModuleSourceRef;
+}): CompiledRemoteAgentNode {
+ const logicalPath =
+ input.source.logicalPath.endsWith(".ts") || input.source.logicalPath.endsWith(".js")
+ ? input.source.logicalPath
+ : posix.join(input.source.logicalPath, "agent.ts");
+ const sourceId = input.source.sourceId;
+ const binding: CompiledModuleBinding = {
+ backing: input.binding.backing,
+ logicalPath,
+ owner: input.owner,
+ };
+ const node = {
+ backing: { kind: "resource" as const, sourcePath: input.source.entryPath },
+ binding,
+ description: input.definition.description,
+ entryPath: input.source.entryPath,
+ logicalPath,
+ name: input.source.subagentId,
+ nodeId: input.nodeId,
+ owner: input.owner,
+ parentNodeId: input.parentNodeId,
+ path: input.definition.path,
+ rootPath: input.source.rootPath,
+ sourceId,
+ sourceKind: "module" as const,
+ };
+ if (input.sourceRef.exportName !== undefined) {
+ Object.assign(node, { exportName: input.sourceRef.exportName });
+ }
+ if (input.definition.outputSchema !== undefined) {
+ Object.assign(node, { outputSchema: input.definition.outputSchema });
+ }
+ if (input.definition.url !== undefined) Object.assign(node, { url: input.definition.url });
+ return node;
+}
+
+export function compileExtensionMounts(
+ manifest: AgentSourceManifest,
+ composed: ComposedAgentModuleCandidates,
+): CompiledExtensionMount[] {
+ const selected = collectSelectedSourceIds(composed);
+ return manifest.resolvedExtensions.flatMap((mount) => {
+ const mountRef = manifest.extensions.find(
+ (entry) => mountRefNamespace(entry.logicalPath) === mount.namespace,
+ );
+ if (mountRef === undefined || !selected.has(mountRef.sourceId)) return [];
+ return [
+ {
+ externalDependencies: [...mount.externalDependencies],
+ mountLogicalPath: mountRef.logicalPath,
+ mountSourceId: mountRef.sourceId,
+ namespace: mount.namespace,
+ packageName: mount.packageName,
+ packageNamespace: packageStateNamespace(mount.packageName),
+ sourceRoot: mount.sourceRoot,
+ },
+ ];
+ });
+}
+
+export function mergeExternalDependencies(
+ ...lists: ReadonlyArray<readonly string[] | undefined>
+): string[] {
+ return [...new Set(lists.flatMap((list) => list ?? []))];
+}
diff --git a/packages/eve/src/compiler/normalize-manifest.test.ts b/packages/eve/src/compiler/normalize-manifest.test.ts
index 67ca2912b..2e7a3c133 100644
--- a/packages/eve/src/compiler/normalize-manifest.test.ts
+++ b/packages/eve/src/compiler/normalize-manifest.test.ts
@@ -1,530 +1,400 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { describe, expect, it, vi } from "vitest";
-import { z } from "#compiled/zod/index.js";
-import type { AgentSourceManifest } from "#discover/manifest.js";
import {
createAgentSourceManifest,
createLocalSubagentSourceRef,
createModuleSourceRef,
} from "#discover/manifest.js";
-import { classifyModelRouting } from "#internal/classify-model-routing.js";
-import type { CompiledAgentDefinition } from "#compiler/manifest.js";
+import {
+ createAgentSourceRegistry,
+ defineProgrammaticAgentSource,
+ type ProgrammaticAgentModule,
+} from "#compiler/source-graph.js";
import { compileAgentManifest } from "#compiler/normalize-manifest.js";
-import { collectModuleRefsForManifest } from "#compiler/module-map.js";
-import { defineAgent, defineDynamic } from "#public/definitions/agent.js";
-import { defineInstructions } from "#public/definitions/instructions.js";
-import { defineTool, experimental_workflow } from "#public/definitions/tool.js";
-import { webSearch } from "#public/tools/web-search.js";
-
-const mocks = vi.hoisted(() => ({
- compileAgentConfig: vi.fn(),
- loadModuleBackedDefinition: vi.fn(),
-}));
-
-vi.mock("#compiler/normalize-agent-config.js", () => ({
- compileAgentConfig: mocks.compileAgentConfig,
-}));
-
-vi.mock("#compiler/normalize-helpers.js", () => ({
- loadModuleBackedDefinition: mocks.loadModuleBackedDefinition,
-}));
-
-describe("compileAgentManifest", () => {
- beforeEach(() => {
- mocks.compileAgentConfig.mockReset();
- mocks.loadModuleBackedDefinition.mockReset();
+import type { CompilerDiagnostic } from "#compiler/diagnostics.js";
+import { createProgrammaticCompiledModuleMap } from "#compiler/module-map.js";
+import { validateCompiledModuleMap } from "#compiler/validate-artifact.js";
+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";
+
+function manifest() {
+ return createAgentSourceManifest({
+ agentId: "source-test",
+ agentRoot: "/virtual/source-test/agent",
+ appRoot: "/virtual/source-test",
});
+}
- it("rejects Workflow runtime configuration on subagents", async () => {
- const subagentManifest = createAgentSourceManifest({
- agentId: "research",
- agentRoot: "/app/agent/subagents/research",
- appRoot: "/app",
- configModule: createModuleSourceRef({
- logicalPath: "agent.ts",
+function registry(modules: readonly ProgrammaticAgentModule[]) {
+ return createAgentSourceRegistry([
+ {
+ applyTo: "root",
+ source: defineProgrammaticAgentSource({
+ id: "test:application",
+ modules,
+ revision: "test:application:v1",
}),
- });
- const manifest = createAgentSourceManifest({
- agentId: "root",
- agentRoot: "/app/agent",
- appRoot: "/app",
- subagents: [
- createLocalSubagentSourceRef({
- entryPath: "subagents/research/agent.ts",
- logicalPath: "subagents/research",
- manifest: subagentManifest,
- rootPath: "/app/agent/subagents/research",
- subagentId: "research",
- }),
- ],
- });
-
- mocks.compileAgentConfig.mockImplementation(async (input: AgentSourceManifest) => {
- if (input.agentId === "research") {
- return createConfig({
- description: "Research subagent",
- name: "research",
- experimental: {
- workflow: {
- world: "@workflow/world-postgres",
- },
- },
- });
- }
+ },
+ ]);
+}
- return createConfig({ name: "root" });
- });
- mocks.loadModuleBackedDefinition.mockResolvedValue({
- description: "Research subagent",
- model: "openai/gpt-5.5",
- });
+describe("compileAgentManifest source graph", () => {
+ it("freezes source metadata behind an immutable registry map", () => {
+ const sourceRegistry = registry([]);
- await expect(compileAgentManifest(manifest)).rejects.toThrow(
- 'Remove "experimental.workflow" from "research"',
- );
+ expect(Object.isFrozen(sourceRegistry)).toBe(true);
+ expect(Object.isFrozen(sourceRegistry.registrations)).toBe(true);
+ expect("set" in sourceRegistry.sources).toBe(false);
});
- it("merges agent-owned and extension-owned external dependencies", async () => {
- const extensionManifest = createAgentSourceManifest({
- agentId: "research-extension",
- agentRoot: "/packages/research/dist/extension",
- appRoot: "/packages/research",
+ it("selects authored config and ordinary tools through one programmatic source", async () => {
+ const sourceRegistry = registry([
+ {
+ logicalPath: "agent.ts",
+ loadNamespace: async () => ({
+ default: defineAgent({ model: "openai/gpt-5.4" }),
+ }),
+ },
+ {
+ logicalPath: "tools/weather.ts",
+ loadNamespace: async () => ({
+ default: defineTool({
+ description: "Gets weather.",
+ execute: () => ({ ok: true }),
+ inputSchema: { type: "object" },
+ }),
+ }),
+ },
+ ]);
+
+ const compiled = await compileAgentManifest(manifest(), {
+ sourceRegistries: [sourceRegistry],
});
- const manifest = createAgentSourceManifest({
- agentId: "root",
- agentRoot: "/app/agent",
- appRoot: "/app",
- extensions: [createModuleSourceRef({ logicalPath: "extensions/research.ts" })],
- resolvedExtensions: [
- {
- namespace: "research",
- specifier: "@acme/research",
- packageName: "@acme/research",
- packageRoot: "/packages/research",
- sourceRoot: "/packages/research/dist/extension",
- manifest: extensionManifest,
- externalDependencies: ["extension-only", "shared"],
- },
- ],
+
+ const weather = compiled.tools.find((tool) => tool.name === "weather");
+ expect(compiled.config.source.logicalPath).toBe("agent.ts");
+ expect(compiled.bindings[compiled.config.source.sourceId]?.owner).toEqual({
+ kind: "application",
});
- mocks.compileAgentConfig.mockResolvedValue(
- createConfig({
- name: "root",
- build: { externalDependencies: ["agent-only", "shared"] },
+ expect(weather).toMatchObject({
+ hasExecute: true,
+ logicalPath: "tools/weather.ts",
+ name: "weather",
+ });
+ expect(compiled.sourceComposition.entries).toContainEqual(
+ expect.objectContaining({
+ kind: "shadowed",
+ source: expect.objectContaining({
+ logicalPath: "agent.ts",
+ owner: expect.objectContaining({ kind: "framework" }),
+ }),
}),
);
- const compiled = await compileAgentManifest(manifest);
-
- expect(compiled.config.build?.externalDependencies).toEqual([
- "agent-only",
- "shared",
- "extension-only",
- ]);
- expect(compiled.extensionMounts).toEqual([
- expect.objectContaining({
- namespace: "research",
- externalDependencies: ["extension-only", "shared"],
- }),
+ const moduleMap = await createProgrammaticCompiledModuleMap(compiled, [
+ frameworkAgentSourceRegistry,
+ sourceRegistry,
]);
+ expect(() => validateCompiledModuleMap(compiled, moduleMap)).not.toThrow();
});
- it("retains extension mounts on the subagent that owns them", async () => {
- const extensionManifest = createAgentSourceManifest({
- agentId: "research-extension",
- agentRoot: "/packages/research/dist/extension",
- appRoot: "/packages/research",
- });
- const mountRef = createModuleSourceRef({ logicalPath: "extensions/research.ts" });
- const subagentManifest = createAgentSourceManifest({
- agentId: "researcher",
- agentRoot: "/app/agent/subagents/researcher",
- appRoot: "/app",
- configModule: createModuleSourceRef({ logicalPath: "agent.ts" }),
- extensions: [mountRef],
- resolvedExtensions: [
- {
- namespace: "research",
- specifier: "@acme/research",
- packageName: "@acme/research",
- packageRoot: "/packages/research",
- sourceRoot: "/packages/research/dist/extension",
- manifest: extensionManifest,
- externalDependencies: [],
+ it("loads the selected config before any non-config definition", async () => {
+ const order: string[] = [];
+ const sourceRegistry = registry([
+ {
+ logicalPath: "agent.ts",
+ loadNamespace: async () => {
+ order.push("config");
+ return { default: defineAgent({ model: "openai/gpt-5.4" }) };
},
- ],
- });
- const manifest = createAgentSourceManifest({
- agentId: "root",
- agentRoot: "/app/agent",
- appRoot: "/app",
- subagents: [
- createLocalSubagentSourceRef({
- entryPath: "subagents/researcher/agent.ts",
- logicalPath: "subagents/researcher",
- manifest: subagentManifest,
- rootPath: "/app/agent/subagents/researcher",
- subagentId: "researcher",
- }),
- ],
- });
- mocks.compileAgentConfig.mockImplementation(async (input: AgentSourceManifest) =>
- input.agentId === "researcher"
- ? createConfig({ name: input.agentId, description: "Research the request." })
- : createConfig({ name: input.agentId }),
- );
- mocks.loadModuleBackedDefinition.mockResolvedValue({
- description: "Research the request.",
- model: "openai/gpt-5.5",
- });
+ },
+ {
+ logicalPath: "tools/probe.ts",
+ loadNamespace: async () => {
+ order.push("tool");
+ return {
+ default: defineTool({ description: "Probe.", inputSchema: {}, execute: () => null }),
+ };
+ },
+ },
+ ]);
- const compiled = await compileAgentManifest(manifest);
+ await compileAgentManifest(manifest(), { sourceRegistries: [sourceRegistry] });
- expect(compiled.extensionMounts).toEqual([]);
- expect(compiled.subagents[0]?.agent.extensionMounts).toEqual([
- expect.objectContaining({
- namespace: "research",
- mountLogicalPath: "extensions/research.ts",
- packageName: "@acme/research",
- }),
- ]);
- expect(collectModuleRefsForManifest(compiled.subagents[0]!.agent)).toContainEqual({
- sourceKind: "module",
- logicalPath: "extensions/research.ts",
- sourceId: "extensions/research.ts",
- });
+ expect(order[0]).toBe("config");
+ expect(order).toContain("tool");
});
- it("rejects background-task configuration on subagents", async () => {
- const subagentManifest = createAgentSourceManifest({
- agentId: "research",
- agentRoot: "/app/agent/subagents/research",
- appRoot: "/app",
- configModule: createModuleSourceRef({
- logicalPath: "agent.ts",
- }),
+ it("projects the root node once and finalizes its filesystem bindings after config", async () => {
+ let toolSourceIterations = 0;
+ const discovered = manifest();
+ discovered.instrumentation = createModuleSourceRef({ logicalPath: "instrumentation.ts" });
+ discovered.tools = new Proxy(discovered.tools, {
+ get(target, property, receiver) {
+ if (property === Symbol.iterator) toolSourceIterations += 1;
+ return Reflect.get(target, property, receiver);
+ },
});
- const manifest = createAgentSourceManifest({
- agentId: "root",
- agentRoot: "/app/agent",
- appRoot: "/app",
- subagents: [
- createLocalSubagentSourceRef({
- entryPath: "subagents/research/agent.ts",
- logicalPath: "subagents/research",
- manifest: subagentManifest,
- rootPath: "/app/agent/subagents/research",
- subagentId: "research",
+ const sourceRegistry = registry([
+ {
+ logicalPath: "agent.ts",
+ loadNamespace: async () => ({
+ default: defineAgent({
+ build: { externalDependencies: ["sharp"] },
+ model: "openai/gpt-5.4",
+ }),
}),
- ],
- });
+ },
+ ]);
- mocks.compileAgentConfig.mockImplementation(async (input: AgentSourceManifest) => {
- if (input.agentId === "research") {
- return createConfig({
- description: "Research subagent",
- name: "research",
- experimental: {
- tasks: true,
- },
- });
- }
-
- return createConfig({ name: "root" });
- });
- mocks.loadModuleBackedDefinition.mockResolvedValue({
- description: "Research subagent",
- model: "openai/gpt-5.5",
+ const compiled = await compileAgentManifest(discovered, {
+ sourceRegistries: [sourceRegistry],
});
- await expect(compileAgentManifest(manifest)).rejects.toThrow(
- 'Remove "experimental.tasks" from "research"',
- );
+ expect(toolSourceIterations).toBe(1);
+ expect(compiled.bindings["instrumentation.ts"]?.backing).toMatchObject({
+ externalDependencies: ["sharp"],
+ kind: "filesystem",
+ });
});
- it("requires experimental.tasks for background tools", async () => {
- const manifest = createAgentSourceManifest({
- agentId: "root",
- agentRoot: "/app/agent",
- appRoot: "/app",
- tools: [createModuleSourceRef({ logicalPath: "tools/export.ts" })],
+ it("projects a local subagent node once", async () => {
+ let toolSourceIterations = 0;
+ const child = createAgentSourceManifest({
+ agentId: "child",
+ agentRoot: "/virtual/source-test/agent/subagents/child",
+ appRoot: "/virtual/source-test",
+ });
+ child.tools = new Proxy(child.tools, {
+ get(target, property, receiver) {
+ if (property === Symbol.iterator) toolSourceIterations += 1;
+ return Reflect.get(target, property, receiver);
+ },
});
- mocks.loadModuleBackedDefinition.mockResolvedValue(
- defineTool({
- description: "Starts an export.",
- execution: "background",
- inputSchema: z.object({}),
- execute: () => ({ ok: true }),
+ const discovered = manifest();
+ discovered.subagents.push(
+ createLocalSubagentSourceRef({
+ entryPath: child.agentRoot,
+ logicalPath: "subagents/child",
+ manifest: child,
+ rootPath: child.agentRoot,
+ subagentId: "child",
}),
);
- mocks.compileAgentConfig.mockResolvedValue(createConfig({ name: "root" }));
- await expect(compileAgentManifest(manifest)).rejects.toThrow(
- 'Background tool "export" requires experimental.tasks: true in the root agent config.',
- );
+ await expect(
+ compileAgentManifest(discovered, {
+ sourceRegistries: [
+ registry([
+ {
+ logicalPath: "agent.ts",
+ loadNamespace: async () => ({
+ default: defineAgent({ model: "openai/gpt-5.4" }),
+ }),
+ },
+ ]),
+ ],
+ }),
+ ).rejects.toThrow('Subagent "subagents/child" must define a non-empty description.');
- mocks.compileAgentConfig.mockResolvedValue(
- createConfig({ experimental: { tasks: true }, name: "root" }),
- );
- await expect(compileAgentManifest(manifest)).resolves.toMatchObject({
- tools: [expect.objectContaining({ execution: "background", name: "export" })],
- });
+ expect(toolSourceIterations).toBe(1);
});
- it("compiles experimental Workflow tool configuration", async () => {
- const manifest = createAgentSourceManifest({
- agentId: "root",
- agentRoot: "/app/agent",
- appRoot: "/app",
- tools: [createModuleSourceRef({ logicalPath: "tools/workflow.ts" })],
- });
- mocks.compileAgentConfig.mockResolvedValue(createConfig({ name: "root" }));
- mocks.loadModuleBackedDefinition.mockResolvedValue(experimental_workflow({ maxSubagents: 6 }));
-
- const compiled = await compileAgentManifest(manifest);
-
- expect(compiled.workflowTool).toEqual({ maxSubagents: 6 });
- });
+ it("disables a lower-precedence framework slot without retaining a binding", async () => {
+ const sourceRegistry = registry([
+ {
+ logicalPath: "tools/bash.ts",
+ loadNamespace: async () => ({ default: disableTool() }),
+ },
+ ]);
- it("compiles web search provider configuration", async () => {
- const manifest = createAgentSourceManifest({
- agentId: "root",
- agentRoot: "/app/agent",
- appRoot: "/app",
- tools: [createModuleSourceRef({ logicalPath: "tools/web_search.ts" })],
+ const compiled = await compileAgentManifest(manifest(), {
+ sourceRegistries: [sourceRegistry],
});
- mocks.compileAgentConfig.mockResolvedValue(createConfig({ name: "root" }));
- mocks.loadModuleBackedDefinition.mockResolvedValue(webSearch({ provider: "exa" }));
-
- const compiled = await compileAgentManifest(manifest);
+ const disabled = compiled.sourceComposition.entries.find(
+ (entry) => entry.kind === "disabled" && entry.source.logicalPath === "tools/bash.ts",
+ );
- expect(compiled.webSearchProvider).toBe("exa");
- expect(compiled.tools).toEqual([]);
+ expect(compiled.tools.some((tool) => tool.name === "bash")).toBe(false);
+ expect(disabled).toBeDefined();
+ expect(compiled.bindings[disabled!.source.sourceId]).toBeUndefined();
});
- it("preserves ordered static instruction content, roles, and legacy definitions", async () => {
- const manifest = createAgentSourceManifest({
- agentId: "root",
- agentRoot: "/app/agent",
- appRoot: "/app",
- instructions: [
- createModuleSourceRef({ logicalPath: "instructions/10-user.ts" }),
- createModuleSourceRef({ logicalPath: "instructions/20-legacy.ts" }),
- ],
- });
- mocks.compileAgentConfig.mockResolvedValue(createConfig({ name: "root" }));
- mocks.loadModuleBackedDefinition
- .mockResolvedValueOnce(defineInstructions({ content: "Account context.", role: "user" }))
- .mockResolvedValueOnce(defineInstructions({ markdown: "Legacy system context." }));
-
- const compiled = await compileAgentManifest(manifest);
-
- expect(compiled.instructions).toEqual([
- expect.objectContaining({
- content: "Account context.",
- logicalPath: "instructions/10-user.ts",
- role: "user",
- }),
- expect.objectContaining({
- content: "Legacy system context.",
- logicalPath: "instructions/20-legacy.ts",
- role: "system",
- }),
+ it("retains concrete route shadows and appends compiler diagnostics", async () => {
+ const diagnostics: CompilerDiagnostic[] = [];
+ const sourceRegistry = registry([
+ {
+ logicalPath: "channels/first.ts",
+ loadNamespace: async () => ({
+ default: defineChannel({ routes: [GET("/same/:id", async () => new Response("first"))] }),
+ }),
+ },
+ {
+ logicalPath: "channels/second.ts",
+ loadNamespace: async () => ({
+ default: defineChannel({
+ routes: [GET("/same/[name]", async () => new Response("second"))],
+ }),
+ }),
+ },
]);
- });
- it("rejects unsupported dynamic instruction event keys", async () => {
- const manifest = createAgentSourceManifest({
- agentId: "root",
- agentRoot: "/app/agent",
- appRoot: "/app",
- instructions: [createModuleSourceRef({ logicalPath: "instructions/dynamic.ts" })],
+ const compiled = await compileAgentManifest(manifest(), {
+ diagnostics,
+ sourceRegistries: [sourceRegistry],
});
- mocks.compileAgentConfig.mockResolvedValue(createConfig({ name: "root" }));
- mocks.loadModuleBackedDefinition.mockResolvedValue(
- defineDynamic({
- events: {
- "step.started": () => defineInstructions({ content: "Too late." }),
- },
- }),
- );
- await expect(compileAgentManifest(manifest)).rejects.toThrow(
- 'Unsupported event: "step.started"',
+ expect(compiled.channelRoutes.shadowed).toHaveLength(1);
+ expect(compiled.channelRoutes.shadowed[0]).toMatchObject({
+ method: "GET",
+ source: {
+ layer: "application",
+ logicalPath: "channels/second.ts",
+ owner: { kind: "application" },
+ },
+ urlPath: "/same/[name]",
+ });
+ expect(diagnostics).toContainEqual(
+ expect.objectContaining({ code: "compile/channel-route-shadowed", severity: "warning" }),
);
+ expect(compiled.diagnosticsSummary.warnings).toBe(1);
});
- it("requires web search configuration to use the web_search filename", async () => {
- const manifest = createAgentSourceManifest({
- agentId: "root",
- agentRoot: "/app/agent",
- appRoot: "/app",
- tools: [createModuleSourceRef({ logicalPath: "tools/search.ts" })],
- });
- mocks.compileAgentConfig.mockResolvedValue(createConfig({ name: "root" }));
- mocks.loadModuleBackedDefinition.mockResolvedValue(webSearch({ provider: "exa" }));
+ it("rejects duplicate routes emitted by one selected channel", async () => {
+ const sourceRegistry = registry([
+ {
+ logicalPath: "channels/duplicate.ts",
+ loadNamespace: async () => ({
+ default: defineChannel({
+ routes: [
+ GET("/duplicate/:id", async () => new Response()),
+ GET("/duplicate/[name]", async () => new Response()),
+ ],
+ }),
+ }),
+ },
+ ]);
- await expect(compileAgentManifest(manifest)).rejects.toThrow(
- 'must be exported from "tools/web_search.ts"',
- );
+ await expect(
+ compileAgentManifest(manifest(), { sourceRegistries: [sourceRegistry] }),
+ ).rejects.toThrow("compile/channel-route-duplicate");
});
- it("compiles a dynamic subagent manifest without resolving an agent config", async () => {
- const dynamic = defineDynamic({
- events: {
- "session.started": () =>
- defineAgent({
- description: "Research the request.",
- model: "openai/gpt-5.5",
+ it("rejects conflicting CORS policies across overlapping route patterns", async () => {
+ const sourceRegistry = registry([
+ {
+ logicalPath: "channels/accounts-read.ts",
+ loadNamespace: async () => ({
+ default: defineChannel({
+ cors: { origin: ["https://read.example.com"] },
+ routes: [GET("/accounts/:id", async () => new Response())],
}),
- "turn.started": () => null,
+ }),
},
- });
- const manifest = createManifestWithSubagent();
- mocks.compileAgentConfig.mockImplementation(async (input: AgentSourceManifest) =>
- createConfig({ name: input.agentId }),
- );
- mocks.loadModuleBackedDefinition.mockResolvedValue(dynamic);
-
- const compiled = await compileAgentManifest(manifest);
+ {
+ logicalPath: "channels/accounts-write.ts",
+ loadNamespace: async () => ({
+ default: defineChannel({
+ cors: { origin: ["https://write.example.com"] },
+ routes: [POST("/accounts/me", async () => new Response())],
+ }),
+ }),
+ },
+ ]);
- expect(compiled.subagents[0]?.configResolver).toMatchObject({
- eventNames: ["session.started", "turn.started"],
- logicalPath: "agent.ts",
- sourceId: "agent.ts",
- sourceKind: "module",
- });
- expect("config" in compiled.subagents[0]!.agent).toBe(false);
- expect(compiled.subagents[0]?.description).toBeUndefined();
- expect(mocks.compileAgentConfig).toHaveBeenCalledTimes(1);
+ await expect(
+ compileAgentManifest(manifest(), { sourceRegistries: [sourceRegistry] }),
+ ).rejects.toThrow("compile/channel-cors-conflict");
});
- it("applies dynamic subagent build configuration before resolving events", async () => {
- const dynamic = defineDynamic({
- build: { externalDependencies: ["just-bash"] },
- events: {
- "session.started": () =>
- defineAgent({
- description: "Edit the request.",
- model: "openai/gpt-5.5",
+ it("allows identical CORS policies across overlapping route patterns", async () => {
+ const cors = { origin: ["https://app.example.com"] } as const;
+ const sourceRegistry = registry([
+ {
+ logicalPath: "channels/accounts-read.ts",
+ loadNamespace: async () => ({
+ default: defineChannel({
+ cors,
+ routes: [GET("/accounts/:id", async () => new Response())],
}),
+ }),
},
- });
- const manifest = createManifestWithSubagent();
- mocks.compileAgentConfig.mockImplementation(async (input: AgentSourceManifest) =>
- createConfig({ name: input.agentId }),
- );
- mocks.loadModuleBackedDefinition.mockResolvedValue(dynamic);
+ {
+ logicalPath: "channels/accounts-write.ts",
+ loadNamespace: async () => ({
+ default: defineChannel({
+ cors,
+ routes: [POST("/accounts/me", async () => new Response())],
+ }),
+ }),
+ },
+ ]);
- const compiled = await compileAgentManifest(manifest);
+ const compiled = await compileAgentManifest(manifest(), { sourceRegistries: [sourceRegistry] });
- expect(compiled.subagents[0]?.configResolver).toMatchObject({
- build: { externalDependencies: ["just-bash"] },
- eventNames: ["session.started"],
- logicalPath: "agent.ts",
- sourceId: "agent.ts",
- sourceKind: "module",
- });
- expect("config" in compiled.subagents[0]!.agent).toBe(false);
- expect(mocks.compileAgentConfig).toHaveBeenCalledTimes(1);
+ expect(compiled.channelRoutes.preflight).toHaveLength(2);
});
- it("rejects invalid dynamic subagent build configuration", async () => {
- mocks.compileAgentConfig.mockResolvedValue(createConfig({ name: "root" }));
- mocks.loadModuleBackedDefinition.mockResolvedValue({
- build: { externalDependencies: "just-bash" },
- events: { "session.started": () => null },
- kind: "eve:dynamic",
- });
-
- await expect(compileAgentManifest(createManifestWithSubagent())).rejects.toThrow(
- "Expected the dynamic subagent config export",
- );
- });
+ it("loads programmatic hooks and persists exact event subscriptions", async () => {
+ const sourceRegistry = registry([
+ {
+ exportName: "audit",
+ logicalPath: "hooks/auth/guard.ts",
+ loadNamespace: async () => ({
+ audit: defineHook({
+ events: {
+ "session.started": async () => {},
+ "step.started": async () => {},
+ },
+ }),
+ }),
+ },
+ ]);
- it("rejects fallback on a dynamic subagent", async () => {
- mocks.compileAgentConfig.mockResolvedValue(createConfig({ name: "root" }));
- mocks.loadModuleBackedDefinition.mockResolvedValue({
- ...defineDynamic({
- events: {
- "session.started": () => null,
- },
- }),
- fallback: defineAgent({
- description: "Research the request.",
- model: "openai/gpt-5.5",
- }),
+ const compiled = await compileAgentManifest(manifest(), {
+ sourceRegistries: [sourceRegistry],
});
- await expect(compileAgentManifest(createManifestWithSubagent())).rejects.toThrow(
- 'Unknown key "fallback"',
- );
+ expect(compiled.hooks).toContainEqual({
+ eventNames: ["session.started", "step.started"],
+ exportName: "audit",
+ logicalPath: "hooks/auth/guard.ts",
+ slug: "auth/guard",
+ sourceId: "test:application:hooks/auth/guard.ts",
+ sourceKind: "module",
+ });
});
- it("rejects step-scoped dynamic subagents", async () => {
- mocks.compileAgentConfig.mockResolvedValue(createConfig({ name: "root" }));
- mocks.loadModuleBackedDefinition.mockResolvedValue(
- defineDynamic({
- events: {
- "step.started": () =>
- defineAgent({
- description: "Research the request.",
- model: "openai/gpt-5.5",
- }),
- },
- }),
- );
+ it("rejects stale programmatic revisions before loading a namespace", async () => {
+ const loader = vi.fn(async () => ({ default: defineAgent({ model: "openai/gpt-5.4" }) }));
+ const source = defineProgrammaticAgentSource({
+ id: "revision-test",
+ modules: [{ loadNamespace: loader, logicalPath: "agent.ts" }],
+ revision: "v1",
+ });
+ const sourceRegistry = createAgentSourceRegistry([{ applyTo: "root", source }]);
+ const compiled = await compileAgentManifest(manifest(), {
+ sourceRegistries: [sourceRegistry],
+ });
+ const binding = compiled.bindings[compiled.config.source.sourceId]!;
+ const staleRegistry = createAgentSourceRegistry([
+ {
+ applyTo: "root",
+ source: defineProgrammaticAgentSource({
+ id: "revision-test",
+ modules: [{ loadNamespace: loader, logicalPath: "agent.ts" }],
+ revision: "v2",
+ }),
+ },
+ ]);
- await expect(compileAgentManifest(createManifestWithSubagent())).rejects.toThrow(
- 'Dynamic subagents support only "session.started" and "turn.started" handlers',
- );
+ await expect(
+ createProgrammaticCompiledModuleMap(compiled, [frameworkAgentSourceRegistry, staleRegistry]),
+ ).rejects.toThrow("revision mismatch");
+ expect(loader).toHaveBeenCalledTimes(1);
+ expect(binding.backing.kind).toBe("programmatic");
});
});
-
-function createManifestWithSubagent(): AgentSourceManifest {
- const subagentManifest = createAgentSourceManifest({
- agentId: "researcher",
- agentRoot: "/app/agent/subagents/researcher",
- appRoot: "/app",
- configModule: createModuleSourceRef({ logicalPath: "agent.ts" }),
- });
- return createAgentSourceManifest({
- agentId: "root",
- agentRoot: "/app/agent",
- appRoot: "/app",
- subagents: [
- createLocalSubagentSourceRef({
- entryPath: "subagents/researcher/agent.ts",
- logicalPath: "subagents/researcher",
- manifest: subagentManifest,
- rootPath: "/app/agent/subagents/researcher",
- subagentId: "researcher",
- }),
- ],
- });
-}
-
-function createConfig(
- input: Pick<CompiledAgentDefinition, "name"> &
- Partial<Pick<CompiledAgentDefinition, "build" | "description" | "experimental">>,
-): CompiledAgentDefinition {
- const config: CompiledAgentDefinition = {
- model: {
- id: "openai/gpt-5.5",
- routing: classifyModelRouting("openai/gpt-5.5"),
- },
- name: input.name,
- };
-
- if (input.description !== undefined) {
- config.description = input.description;
- }
- if (input.build !== undefined) {
- config.build = input.build;
- }
- if (input.experimental !== undefined) {
- config.experimental = input.experimental;
- }
-
- return config;
-}
diff --git a/packages/eve/src/compiler/normalize-manifest.ts b/packages/eve/src/compiler/normalize-manifest.ts
index 30f7e57a7..9bcadb785 100644
--- a/packages/eve/src/compiler/normalize-manifest.ts
+++ b/packages/eve/src/compiler/normalize-manifest.ts
@@ -1,318 +1,608 @@
import type { AgentSourceManifest } from "#discover/manifest.js";
-import { mountRefNamespace, packageStateNamespace } from "#discover/extensions.js";
+import type { ModuleSourceRef } from "#shared/source-ref.js";
+import type { WebSearchProvider } from "#shared/web-search.js";
import {
+ type CompiledAgentDefinition,
type CompiledAgentManifest,
type CompiledAgentNodeManifest,
type CompiledAgentResources,
+ type CompiledChannelDefinition,
+ type CompiledConnectionDefinition,
type CompiledDynamicInstructionsDefinition,
- type CompiledExtensionMount,
type CompiledDynamicSkillDefinition,
type CompiledDynamicToolDefinition,
type CompiledInstructionsDefinition,
+ type CompiledHookDefinition,
+ type CompiledRemoteAgentNode,
type CompiledSkillDefinition,
+ type CompiledScheduleDefinition,
+ type CompiledSandboxDefinition,
+ type CompiledSubagentNode,
type CompiledToolDefinition,
type CompiledWorkflowToolDefinition,
createCompiledAgentManifest,
createCompiledAgentNodeManifest,
createCompiledAgentResources,
+ createCompiledSubagentNodeId,
ROOT_COMPILED_AGENT_NODE_ID,
} from "#compiler/manifest.js";
-import type { WebSearchProvider } from "#shared/web-search.js";
import { createCompiledRuntimeModelCatalogLoader } from "#compiler/model-catalog.js";
import { compileAgentConfig } from "#compiler/normalize-agent-config.js";
import { compileChannelDefinition } from "#compiler/normalize-channel.js";
import { compileConnectionDefinition } from "#compiler/normalize-connection.js";
import {
- composeAgentSubagentSources,
- compileExtensionContributions,
-} from "#compiler/normalize-extension.js";
-import type { ManifestCompileContext } from "#compiler/normalize-helpers.js";
+ loadModuleBackedDefinition,
+ type ManifestCompileContext,
+} from "#compiler/normalize-helpers.js";
import { compileHookEntry } from "#compiler/normalize-hook.js";
-import { compileSandboxDefinition } from "#compiler/normalize-sandbox.js";
import { compileInstructionsEntry } from "#compiler/normalize-instructions.js";
+import { compileSandboxDefinition } from "#compiler/normalize-sandbox.js";
import { compileScheduleDefinition } from "#compiler/normalize-schedule.js";
import { compileSkillSource } from "#compiler/normalize-skill.js";
-import { compileSubagentGraph } from "#compiler/normalize-subagent.js";
+import {
+ assertRemoteAgentDefinitionHasNoLocalPackageEntries,
+ normalizeSubagentConfig,
+} from "#compiler/normalize-subagent.js";
import { compileToolEntry } from "#compiler/normalize-tool.js";
+import { createCompiledChannelRoutePlan } from "#compiler/channel-route-plan.js";
+import {
+ finalizeNodeSourceState,
+ type ComposedNodeSourceGraph,
+ type FinalizedNodeSourceState,
+ type PhaseOneNodeSourceState,
+ type SelectedNodeConfig,
+} from "#compiler/node-source-state.js";
+import {
+ assertApplicationOverlayCanApplyToAllNodes,
+ assertNonExtensionSpecialTool,
+ assertRootOnlyConfig,
+ assertRootOwnedSpecialTool,
+ assertUniqueBy,
+ assertUniqueRegistryIds,
+ compileExtensionMounts,
+ createCompiledRemoteAgent,
+ expectSubagentDescription,
+ mergeExternalDependencies,
+ collectSelectedSourceIds,
+ withExtensionNamespace,
+} from "#compiler/normalize-manifest-helpers.js";
+import { summarizeCompilerDiagnostics, type CompilerDiagnostic } from "#compiler/diagnostics.js";
+import { projectAgentSources, projectSelectedSources } from "#compiler/project-sources.js";
+import {
+ composeAgentModuleCandidates,
+ createCompiledModuleBinding,
+ createProgrammaticModuleCandidates,
+ describeAgentSourceCandidate,
+ disableComposedCandidate,
+ type AgentModuleCandidate,
+ type AgentSourceCandidate,
+ type AgentSourceLayer,
+ type AgentSourceOwner,
+ type AgentSourceRegistry,
+} from "#compiler/source-graph.js";
+import { frameworkAgentSourceRegistry } from "#framework/sources/registry.js";
+
+export interface CompileAgentManifestOptions {
+ readonly diagnostics?: CompilerDiagnostic[];
+ readonly sourceRegistries?: readonly AgentSourceRegistry[];
+}
+
+interface NodeCompileInput {
+ readonly extensionScope?: { readonly namespace: string; readonly sourceRoot: string };
+ readonly inheritedExternalDependencies: readonly string[];
+ readonly isRoot: boolean;
+ readonly layer: AgentSourceLayer;
+ readonly manifest: AgentSourceManifest;
+ readonly nodeId: string;
+ readonly owner: AgentSourceOwner;
+ readonly parentNodeId?: string;
+}
+
+interface CompiledLocalNodeResult {
+ readonly descendants: readonly CompiledSubagentNode[];
+ readonly manifest: CompiledAgentNodeManifest;
+}
-/**
- * Compiles one discovery manifest into the normalized manifest loaded by the runtime.
- */
+/** Compiles one discovery graph through the canonical source composition pipeline. */
export async function compileAgentManifest(
manifest: AgentSourceManifest,
+ options: CompileAgentManifestOptions = {},
): Promise<CompiledAgentManifest> {
+ const registries = [frameworkAgentSourceRegistry, ...(options.sourceRegistries ?? [])];
+ assertUniqueRegistryIds(registries);
const context: ManifestCompileContext = {
modelCatalog: createCompiledRuntimeModelCatalogLoader(manifest.appRoot),
+ registries,
};
- const compiledNode = await compileAgentNodeManifest(manifest, context);
- const subagentGraph = await compileSubagentGraph({
- appRoot: manifest.appRoot,
- compileAgentNodeManifest,
- compileAgentResources,
- context,
- externalDependencies: compiledNode.config.build?.externalDependencies ?? [],
- parentAgentRoot: manifest.agentRoot,
- parentNodeId: ROOT_COMPILED_AGENT_NODE_ID,
- subagents: composeAgentSubagentSources(manifest),
+ const diagnostics = options.diagnostics ?? [];
+ const compiler = new AgentGraphCompiler(context, registries, diagnostics);
+ const root = await compiler.compileStaticNode({
+ inheritedExternalDependencies: [],
+ isRoot: true,
+ layer: "application",
+ manifest,
+ nodeId: ROOT_COMPILED_AGENT_NODE_ID,
+ owner: { kind: "application" },
});
- const backgroundTool = [compiledNode, ...subagentGraph.nodes.map((node) => node.agent)]
+ const allNodeManifests = [root.manifest, ...root.descendants.map((node) => node.agent)];
+ const backgroundTool = allNodeManifests
.flatMap((node) => node.tools)
.find((tool) => tool.execution === "background");
- if (backgroundTool !== undefined && compiledNode.config.experimental?.tasks !== true) {
+ if (backgroundTool !== undefined && root.manifest.config.experimental?.tasks !== true) {
throw new Error(
`Background tool "${backgroundTool.name}" requires experimental.tasks: true in the root agent config.`,
);
}
+ const diagnosticsSummary = summarizeCompilerDiagnostics(diagnostics);
+ const subagents: CompiledSubagentNode[] = root.descendants.map((subagent) =>
+ subagent.configResolver === undefined
+ ? {
+ ...subagent,
+ agent: { ...subagent.agent, diagnosticsSummary },
+ }
+ : {
+ ...subagent,
+ agent: { ...subagent.agent, diagnosticsSummary },
+ },
+ );
return createCompiledAgentManifest({
- ...compiledNode,
- extensionMounts: compiledNode.extensionMounts,
- remoteAgents: subagentGraph.remoteAgents,
- subagentEdges: subagentGraph.edges,
- subagents: subagentGraph.nodes,
+ ...root.manifest,
+ diagnosticsSummary,
+ subagents,
});
}
-async function compileAgentNodeManifest(
- manifest: AgentSourceManifest,
- context: ManifestCompileContext,
- options: {
- readonly agentConfigDefinition?: unknown;
- readonly externalDependencies?: readonly string[];
- readonly allowRootOnlyConfig?: boolean;
- } = {},
-): Promise<CompiledAgentNodeManifest> {
- const rawConfig = Object.hasOwn(options, "agentConfigDefinition")
- ? await compileAgentConfig(manifest, context, {
- definition: options.agentConfigDefinition,
- })
- : await compileAgentConfig(manifest, context);
- if (options.allowRootOnlyConfig === false && rawConfig.experimental?.workflow !== undefined) {
- throw new Error(
- `Workflow runtime configuration is only supported on the root agent config. Remove "experimental.workflow" from "${manifest.agentId}".`,
- );
- }
- if (options.allowRootOnlyConfig === false && rawConfig.experimental?.tasks !== undefined) {
- throw new Error(
- `Background tasks are only supported on the root agent config. Remove "experimental.tasks" from "${manifest.agentId}".`,
- );
+class AgentGraphCompiler {
+ private readonly context: ManifestCompileContext;
+ private readonly registries: readonly AgentSourceRegistry[];
+ private readonly diagnostics: CompilerDiagnostic[];
+
+ constructor(
+ context: ManifestCompileContext,
+ registries: readonly AgentSourceRegistry[],
+ diagnostics: CompilerDiagnostic[],
+ ) {
+ this.context = context;
+ this.registries = registries;
+ this.diagnostics = diagnostics;
}
- const externalDependencies = mergeExternalDependencies(
- options.externalDependencies,
- rawConfig.build?.externalDependencies,
- manifest.resolvedExtensions.flatMap((mount) => mount.externalDependencies),
- );
- const config =
- externalDependencies.length === 0
- ? rawConfig
- : {
- ...rawConfig,
- build: {
- ...rawConfig.build,
- externalDependencies,
- },
- };
- const resources = await compileAgentResources(manifest, context, { externalDependencies });
- return createCompiledAgentNodeManifest({ ...resources, config });
-}
-async function compileAgentResources(
- manifest: AgentSourceManifest,
- context: ManifestCompileContext,
- options: { readonly externalDependencies?: readonly string[] } = {},
-): Promise<CompiledAgentResources> {
- const externalDependencies = [...(options.externalDependencies ?? [])];
- const compiledToolEntries = await Promise.all(
- manifest.tools.map((toolSource) =>
- compileToolEntry(manifest.agentRoot, toolSource, { externalDependencies }),
- ),
- );
- const tools: CompiledToolDefinition[] = [];
- const dynamicTools: CompiledDynamicToolDefinition[] = [];
- const disabledFrameworkTools: string[] = [];
- let workflowTool: CompiledWorkflowToolDefinition | undefined;
- let webSearchProvider: WebSearchProvider | undefined;
+ async compileStaticNode(input: NodeCompileInput): Promise<CompiledLocalNodeResult> {
+ const phaseOne = await this.createPhaseOneNodeSourceState(
+ input,
+ input.inheritedExternalDependencies,
+ );
+ let config = await compileAgentConfig(input.manifest, this.context, {
+ binding: phaseOne.selectedConfig.binding,
+ definition: phaseOne.selectedConfig.definition,
+ source: phaseOne.selectedConfig.source,
+ });
+ assertRootOnlyConfig(config, input.isRoot, input.manifest.agentId);
- for (const entry of compiledToolEntries) {
- if (entry.kind === "tool") {
- tools.push(entry.definition);
- } else if (entry.kind === "dynamic-tool") {
- dynamicTools.push(entry.definition);
- } else if (entry.kind === "workflow-tool") {
- workflowTool = { maxSubagents: entry.maxSubagents };
- } else if (entry.kind === "web-search-tool") {
- webSearchProvider = entry.provider;
- } else {
- disabledFrameworkTools.push(entry.name);
+ const externalDependencies = mergeExternalDependencies(
+ input.inheritedExternalDependencies,
+ config.build?.externalDependencies,
+ input.manifest.resolvedExtensions.flatMap((mount) => mount.externalDependencies),
+ );
+ if (externalDependencies.length > 0) {
+ config = {
+ ...config,
+ build: { ...config.build, externalDependencies },
+ };
}
+ const state = finalizeNodeSourceState(phaseOne, externalDependencies);
+ assertInstrumentationLayoutConfig(config, state);
+ const resources = await this.compileResources(input, state);
+ const children = await this.compileChildren(input, state, externalDependencies);
+ const manifest = createCompiledAgentNodeManifest({
+ ...resources,
+ config,
+ remoteAgents: children.remoteAgents,
+ });
+ return {
+ descendants: children.nodes,
+ manifest,
+ };
}
- const compiledChannelResults = await Promise.all(
- manifest.channels.map((channelSource) =>
- compileChannelDefinition(manifest.agentRoot, channelSource, { externalDependencies }),
- ),
- );
+ private async compileChildren(
+ input: NodeCompileInput,
+ state: FinalizedNodeSourceState,
+ inheritedExternalDependencies: readonly string[],
+ ): Promise<{
+ readonly nodes: readonly CompiledSubagentNode[];
+ readonly remoteAgents: readonly CompiledRemoteAgentNode[];
+ }> {
+ const nodes: CompiledSubagentNode[] = [];
+ const remoteAgents: CompiledRemoteAgentNode[] = [];
+ const selectedSourceIds = collectSelectedSourceIds(state.composed);
+ const subagents = state.projected.subagents.filter((source) =>
+ selectedSourceIds.has(source.candidate.sourceId),
+ );
- // compileChannelDefinition returns one entry for a disabled-channel
- // sentinel or an array of entries (one per route) for an authored
- // CompiledChannel. Flatten so the manifest holds a single channel list.
- const compiledChannels = compiledChannelResults.flat();
+ for (const projected of subagents) {
+ const source = projected.source;
+ const nodeId = createCompiledSubagentNodeId(input.nodeId, source.sourceId);
+ const childInput: NodeCompileInput = {
+ extensionScope: projected.extensionScope ?? input.extensionScope,
+ inheritedExternalDependencies,
+ isRoot: false,
+ layer: projected.candidate.layer,
+ manifest: source.manifest,
+ nodeId,
+ owner: projected.owner,
+ parentNodeId: input.nodeId,
+ };
+ const phaseOne = await this.createPhaseOneNodeSourceState(
+ childInput,
+ inheritedExternalDependencies,
+ );
+ const normalized = normalizeSubagentConfig(
+ phaseOne.selectedConfig.definition,
+ `Expected the subagent config export "${phaseOne.selectedConfig.source.exportName ?? "default"}" from "${source.entryPath}" to match the public eve shape.`,
+ );
- const compiledSkillEntries = await Promise.all(
- manifest.skills.map((skillSource) =>
- compileSkillSource(manifest.agentRoot, skillSource, { externalDependencies }),
- ),
- );
- const skills: CompiledSkillDefinition[] = [];
- const dynamicSkills: CompiledDynamicSkillDefinition[] = [];
+ if (normalized.kind === "remote") {
+ assertRemoteAgentDefinitionHasNoLocalPackageEntries(source);
+ remoteAgents.push(
+ createCompiledRemoteAgent({
+ binding: phaseOne.selectedConfig.binding,
+ definition: normalized,
+ nodeId,
+ owner: projected.owner,
+ parentNodeId: input.nodeId,
+ source,
+ sourceRef: phaseOne.selectedConfig.source,
+ }),
+ );
+ continue;
+ }
- for (const entry of compiledSkillEntries) {
- if (entry.kind === "skill") {
- skills.push(entry.definition);
- } else {
- dynamicSkills.push(entry.definition);
+ let config: CompiledAgentDefinition | undefined;
+ let dynamicBuildDependencies: readonly string[] | undefined;
+ if (normalized.kind === "local") {
+ config = await compileAgentConfig(source.manifest, this.context, {
+ binding: phaseOne.selectedConfig.binding,
+ definition: normalized.definition,
+ source: phaseOne.selectedConfig.source,
+ });
+ assertRootOnlyConfig(config, false, source.manifest.agentId);
+ } else {
+ dynamicBuildDependencies = normalized.build?.externalDependencies;
+ }
+ const externalDependencies = mergeExternalDependencies(
+ inheritedExternalDependencies,
+ config?.build?.externalDependencies,
+ dynamicBuildDependencies,
+ source.manifest.resolvedExtensions.flatMap((mount) => mount.externalDependencies),
+ );
+ if (config !== undefined && externalDependencies.length > 0) {
+ config = { ...config, build: { ...config.build, externalDependencies } };
+ }
+ const finalState = finalizeNodeSourceState(phaseOne, externalDependencies);
+ if (config !== undefined) assertInstrumentationLayoutConfig(config, finalState);
+ const resources = await this.compileResources(childInput, finalState);
+ const children = await this.compileChildren(childInput, finalState, externalDependencies);
+ const base = {
+ backing: projected.candidate.backing,
+ entryPath: source.entryPath,
+ logicalPath: source.logicalPath,
+ name: source.subagentId,
+ nodeId,
+ owner: projected.owner,
+ parentNodeId: input.nodeId,
+ rootPath: source.rootPath,
+ sourceId: source.sourceId,
+ sourceKind: "module" as const,
+ };
+ let node: CompiledSubagentNode;
+ if (config === undefined) {
+ node = {
+ ...base,
+ agent: createCompiledAgentResources({
+ ...resources,
+ remoteAgents: children.remoteAgents,
+ }),
+ configResolver: {
+ build: normalized.kind === "dynamic" ? normalized.build : undefined,
+ eventNames: normalized.kind === "dynamic" ? normalized.eventNames : [],
+ exportName: phaseOne.selectedConfig.source.exportName,
+ logicalPath: phaseOne.selectedConfig.source.logicalPath,
+ sourceId: phaseOne.selectedConfig.source.sourceId,
+ sourceKind: "module",
+ },
+ };
+ } else {
+ node = {
+ ...base,
+ agent: createCompiledAgentNodeManifest({
+ ...resources,
+ config,
+ remoteAgents: children.remoteAgents,
+ }),
+ description: expectSubagentDescription(config, source),
+ };
+ }
+ nodes.push(node, ...children.nodes);
}
- }
- const compiledInstructionsEntries = await Promise.all(
- manifest.instructions.map((source) =>
- compileInstructionsEntry(manifest.agentRoot, source, { externalDependencies }),
- ),
- );
- const staticInstructions: CompiledInstructionsDefinition[] = [];
- const dynamicInstructions: CompiledDynamicInstructionsDefinition[] = [];
-
- for (const entry of compiledInstructionsEntries) {
- if (entry.kind === "instructions") {
- staticInstructions.push(entry.definition);
- } else {
- dynamicInstructions.push(entry.definition);
- }
+ return { nodes, remoteAgents };
}
- const connections = await Promise.all(
- manifest.connections.map((connectionSource) =>
- compileConnectionDefinition(manifest.agentRoot, connectionSource, { externalDependencies }),
- ),
- );
- const hooks = manifest.hooks.map((hookSource) => compileHookEntry(hookSource));
- const schedules = await Promise.all(
- manifest.schedules.map((scheduleSource) =>
- compileScheduleDefinition(manifest.agentRoot, scheduleSource, { externalDependencies }),
- ),
- );
-
- // Sorted by namespace so first-registration-wins dedup is deterministic when
- // two extensions contribute the same composed name.
- const toolNames = new Set(tools.map((tool) => tool.name));
- const dynamicToolSlugs = new Set(dynamicTools.map((tool) => tool.slug));
- const connectionNames = new Set(connections.map((connection) => connection.connectionName));
- const skillNames = new Set(skills.map((skill) => skill.name));
- const extensionInstructions: CompiledInstructionsDefinition[] = [];
- for (const mount of [...manifest.resolvedExtensions].sort((left, right) =>
- left.namespace.localeCompare(right.namespace),
- )) {
- const contributions = await compileExtensionContributions({
- mount,
- context,
- consumerAgentRoot: manifest.agentRoot,
+ private composeNodeSources(
+ input: NodeCompileInput,
+ externalDependencies: readonly string[],
+ ): ComposedNodeSourceGraph {
+ const projected = projectAgentSources({
externalDependencies,
+ extensionScope: input.extensionScope,
+ layer: input.layer,
+ manifest: input.manifest,
+ nodeId: input.nodeId,
+ owner: input.owner,
});
- compiledChannels.push(...contributions.channels);
- for (const tool of contributions.tools) {
- if (!toolNames.has(tool.name)) {
- toolNames.add(tool.name);
- tools.push(tool);
+ const frameworkCandidates: AgentModuleCandidate[] = [];
+ const applicationCandidates: AgentModuleCandidate[] = [];
+ for (const registry of this.registries) {
+ const framework = registry === frameworkAgentSourceRegistry;
+ for (const registration of registry.registrations) {
+ if (registration.applyTo === "root" && !input.isRoot) continue;
+ if (!framework && registration.applyTo === "all-local-nodes") {
+ assertApplicationOverlayCanApplyToAllNodes(
+ registration.source.modules.map((m) => m.logicalPath),
+ );
+ }
+ const candidates = createProgrammaticModuleCandidates({
+ layer: framework ? "framework-default" : "application",
+ nodeId: input.nodeId,
+ owner: framework
+ ? { feature: registration.source.id, kind: "framework" }
+ : { kind: "application" },
+ registration,
+ });
+ (framework ? frameworkCandidates : applicationCandidates).push(...candidates);
}
}
- for (const tool of contributions.dynamicTools) {
- if (!dynamicToolSlugs.has(tool.slug)) {
- dynamicToolSlugs.add(tool.slug);
- dynamicTools.push(tool);
- }
+ const orderedCandidates: AgentSourceCandidate[] = [
+ ...frameworkCandidates,
+ ...projected.candidates,
+ ...applicationCandidates,
+ ];
+ const composed = composeAgentModuleCandidates(orderedCandidates);
+ const sources = projectSelectedSources({
+ candidates: composed.selected.values(),
+ resources: projected.resources,
+ });
+ return {
+ composed,
+ orderedCandidates,
+ projected,
+ sourcesBySourceId: new Map(sources.map((entry) => [entry.candidate.sourceId, entry])),
+ subagentsBySourceId: new Map(
+ projected.subagents.map((entry) => [entry.candidate.sourceId, entry]),
+ ),
+ };
+ }
+
+ private async createPhaseOneNodeSourceState(
+ input: NodeCompileInput,
+ externalDependencies: readonly string[],
+ ): Promise<PhaseOneNodeSourceState> {
+ const graph = this.composeNodeSources(input, externalDependencies);
+ return {
+ graph,
+ selectedConfig: await this.loadSelectedConfig(graph),
+ };
+ }
+
+ private async loadSelectedConfig(state: ComposedNodeSourceGraph): Promise<SelectedNodeConfig> {
+ const candidate = state.composed.selected.get("agent");
+ if (candidate === undefined || !isModuleCandidate(candidate)) {
+ throw new Error("Every local agent node requires a selected module-backed agent.ts source.");
}
- for (const connection of contributions.connections) {
- if (!connectionNames.has(connection.connectionName)) {
- connectionNames.add(connection.connectionName);
- connections.push(connection);
- }
+ const binding = createCompiledModuleBinding(candidate);
+ const projected = state.sourcesBySourceId.get(candidate.sourceId);
+ if (projected?.source.sourceKind !== "module") {
+ throw new Error(`Selected agent config source "${candidate.sourceId}" was not projected.`);
}
- for (const skill of contributions.skills) {
- if (!skillNames.has(skill.name)) {
- skillNames.add(skill.name);
- skills.push(skill);
+ const source = projected.source;
+ return {
+ binding,
+ candidate,
+ definition: await loadModuleBackedDefinition({
+ binding,
+ kind: "agent config",
+ registries: this.registries,
+ source,
+ }),
+ source,
+ };
+ }
+
+ private async compileResources(
+ input: NodeCompileInput,
+ state: FinalizedNodeSourceState,
+ ): Promise<CompiledAgentResources> {
+ const tools: CompiledToolDefinition[] = [];
+ const dynamicTools: CompiledDynamicToolDefinition[] = [];
+ const skills: CompiledSkillDefinition[] = [];
+ const dynamicSkills: CompiledDynamicSkillDefinition[] = [];
+ const instructions: CompiledInstructionsDefinition[] = [];
+ const dynamicInstructions: CompiledDynamicInstructionsDefinition[] = [];
+ const connections: CompiledConnectionDefinition[] = [];
+ const hooks: CompiledHookDefinition[] = [];
+ const schedules: CompiledScheduleDefinition[] = [];
+ const channels: CompiledChannelDefinition[] = [];
+ let sandbox: CompiledSandboxDefinition | undefined;
+ let instrumentation: ModuleSourceRef | undefined;
+ let workflowTool: CompiledWorkflowToolDefinition | undefined;
+ let webSearchProvider: WebSearchProvider | undefined;
+ const selectedSourceIds = collectSelectedSourceIds(state.composed);
+
+ for (const candidate of state.orderedCandidates) {
+ if (!selectedSourceIds.has(candidate.sourceId)) continue;
+ const entry = state.sourcesBySourceId.get(candidate.sourceId);
+ if (entry === undefined) continue;
+ const binding = state.bindings[candidate.sourceId];
+ const options = {
+ binding,
+ owner: candidate.owner,
+ registries: this.registries,
+ };
+ switch (entry.kind) {
+ case "config":
+ case "extension":
+ break;
+ case "channel": {
+ const result = await compileChannelDefinition(input.manifest.agentRoot, entry.source, {
+ binding: binding!,
+ registries: this.registries,
+ });
+ if (result.kind === "disabled") {
+ state.composed = disableComposedCandidate({ candidate, composed: state.composed });
+ delete state.bindings[candidate.sourceId];
+ selectedSourceIds.delete(candidate.sourceId);
+ } else channels.push(...result.definitions);
+ break;
+ }
+ case "connection":
+ connections.push(
+ await compileConnectionDefinition(input.manifest.agentRoot, entry.source, {
+ binding: binding!,
+ registries: this.registries,
+ }),
+ );
+ break;
+ case "hook":
+ hooks.push(
+ await compileHookEntry(entry.source, {
+ binding: binding!,
+ registries: this.registries,
+ }),
+ );
+ break;
+ case "instructions": {
+ const result = await compileInstructionsEntry(
+ input.manifest.agentRoot,
+ entry.source,
+ options,
+ );
+ if (result.kind === "instructions") instructions.push(result.definition);
+ else dynamicInstructions.push(result.definition);
+ break;
+ }
+ case "instrumentation":
+ instrumentation = entry.source;
+ break;
+ case "sandbox":
+ sandbox = await compileSandboxDefinition(input.manifest.agentRoot, entry.source, {
+ binding: binding!,
+ registries: this.registries,
+ });
+ break;
+ case "schedule":
+ schedules.push(
+ await compileScheduleDefinition(input.manifest.agentRoot, entry.source, options),
+ );
+ break;
+ case "skill": {
+ const result = await compileSkillSource(input.manifest.agentRoot, entry.source, options);
+ if (result.kind === "skill") skills.push(result.definition);
+ else dynamicSkills.push(withExtensionNamespace(result.definition, candidate.owner));
+ break;
+ }
+ case "tool": {
+ const result = await compileToolEntry(input.manifest.agentRoot, entry.source, {
+ binding: binding!,
+ registries: this.registries,
+ });
+ if (result.kind === "disabled") {
+ state.composed = disableComposedCandidate({ candidate, composed: state.composed });
+ delete state.bindings[candidate.sourceId];
+ selectedSourceIds.delete(candidate.sourceId);
+ } else if (result.kind === "tool") tools.push(result.definition);
+ else if (result.kind === "dynamic-tool") {
+ dynamicTools.push(withExtensionNamespace(result.definition, candidate.owner));
+ } else if (result.kind === "workflow-tool") {
+ assertRootOwnedSpecialTool(candidate as AgentModuleCandidate, "Workflow");
+ workflowTool = { ...entry.source, maxSubagents: result.maxSubagents };
+ } else {
+ assertNonExtensionSpecialTool(candidate as AgentModuleCandidate, "Web search");
+ tools.push(result.definition);
+ webSearchProvider = result.provider;
+ }
+ break;
+ }
}
}
- schedules.push(...contributions.schedules);
- hooks.push(...contributions.hooks);
- dynamicSkills.push(...contributions.dynamicSkills);
- dynamicInstructions.push(...contributions.dynamicInstructions);
- extensionInstructions.push(...contributions.instructions);
- }
- const instructions = [...staticInstructions, ...extensionInstructions];
+ if (sandbox === undefined) {
+ throw new Error(`Agent node "${input.nodeId}" has no selected sandbox source.`);
+ }
+ assertUniqueBy(tools, (tool) => tool.name, "tool name");
+ assertUniqueBy(dynamicTools, (tool) => tool.slug, "dynamic tool slug");
+ assertUniqueBy(connections, (connection) => connection.connectionName, "connection name");
+ assertUniqueBy(skills, (skill) => skill.name, "skill name");
- return createCompiledAgentResources({
- agentRoot: manifest.agentRoot,
- appRoot: manifest.appRoot,
- channels: compiledChannels,
- extensionMounts: compileExtensionMounts(manifest),
- connections,
- diagnosticsSummary: manifest.diagnosticsSummary,
- disabledFrameworkTools,
- workflowTool,
- webSearchProvider,
- dynamicSkills,
- dynamicTools,
- hooks,
- sandbox:
- manifest.sandbox === null
- ? null
- : await compileSandboxDefinition(manifest.agentRoot, manifest.sandbox, {
- externalDependencies,
- }),
- sandboxWorkspaces: manifest.sandboxWorkspaces.map((workspace) => ({
- logicalPath: workspace.logicalPath,
- rootEntries: [...workspace.rootEntries],
- sourceId: workspace.sourceId,
- sourcePath: workspace.sourcePath,
- })),
- schedules,
- dynamicInstructions,
- skills,
- instructions,
- tools,
- });
+ const channelRoutes = createCompiledChannelRoutePlan({
+ bindings: state.bindings,
+ channels,
+ diagnostics: this.diagnostics,
+ nodeId: input.nodeId,
+ sources: Object.fromEntries(
+ state.orderedCandidates.map((candidate) => [
+ candidate.sourceId,
+ describeAgentSourceCandidate(candidate),
+ ]),
+ ),
+ });
+ return createCompiledAgentResources({
+ agentRoot: input.manifest.agentRoot,
+ appRoot: input.manifest.appRoot,
+ bindings: state.bindings,
+ channelRoutes,
+ connections,
+ diagnosticsSummary: summarizeCompilerDiagnostics(this.diagnostics),
+ dynamicInstructions,
+ dynamicSkills,
+ dynamicTools,
+ extensionMounts: compileExtensionMounts(input.manifest, state.composed),
+ hooks,
+ instructions,
+ instrumentation,
+ sandbox,
+ sandboxWorkspaces: input.manifest.sandboxWorkspaces.map((workspace) => ({
+ logicalPath: workspace.logicalPath,
+ rootEntries: [...workspace.rootEntries],
+ sourceId: workspace.sourceId,
+ sourcePath: workspace.sourcePath,
+ })),
+ schedules,
+ skills,
+ sourceComposition: state.composed.composition,
+ tools,
+ webSearchProvider,
+ workflowTool,
+ });
+ }
}
-function compileExtensionMounts(manifest: AgentSourceManifest): CompiledExtensionMount[] {
- return manifest.resolvedExtensions.map((mount) => {
- const mountRef = manifest.extensions.find(
- (entry) => mountRefNamespace(entry.logicalPath) === mount.namespace,
- );
- return {
- externalDependencies: [...mount.externalDependencies],
- namespace: mount.namespace,
- packageName: mount.packageName,
- packageNamespace: packageStateNamespace(mount.packageName),
- sourceRoot: mount.sourceRoot,
- mountSourceId: mountRef?.sourceId ?? `extensions/${mount.namespace}`,
- mountLogicalPath: mountRef?.logicalPath ?? `extensions/${mount.namespace}`,
- };
- });
+function isModuleCandidate(candidate: AgentSourceCandidate): candidate is AgentModuleCandidate {
+ return candidate.backing.kind !== "resource";
}
-function mergeExternalDependencies(
- ...dependencyLists: ReadonlyArray<readonly string[] | undefined>
-): string[] {
- const dependencies = new Set<string>();
-
- for (const dependencyList of dependencyLists) {
- for (const dependencyName of dependencyList ?? []) {
- dependencies.add(dependencyName);
- }
+function assertInstrumentationLayoutConfig(
+ config: CompiledAgentDefinition,
+ state: FinalizedNodeSourceState,
+): void {
+ if (
+ config.experimental?.instrumentationProviders === true &&
+ state.composed.selected.has("instrumentation")
+ ) {
+ throw new Error(
+ "A selected instrumentation.ts source cannot be used with experimental.instrumentationProviders. Move the declaration into the instrumentation/ provider directory.",
+ );
}
-
- return [...dependencies];
}
diff --git a/packages/eve/src/compiler/normalize-sandbox.ts b/packages/eve/src/compiler/normalize-sandbox.ts
index 9311ab39f..5f3737153 100644
--- a/packages/eve/src/compiler/normalize-sandbox.ts
+++ b/packages/eve/src/compiler/normalize-sandbox.ts
@@ -1,6 +1,5 @@
import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";
-import { join } from "node:path";
import type { SandboxSourceRef } from "#discover/manifest.js";
import { normalizeSandboxDefinition } from "#internal/authored-definition/sandbox.js";
@@ -16,15 +15,15 @@ import { toErrorMessage } from "#shared/errors.js";
* definition stored on the compiled agent manifest.
*/
export async function compileSandboxDefinition(
- agentRoot: string,
+ _agentRoot: string,
source: SandboxSourceRef,
- options: ModuleBackedDefinitionLoadOptions = {},
+ options: ModuleBackedDefinitionLoadOptions,
): Promise<CompiledSandboxDefinition> {
const message = `Expected the sandbox export "${source.exportName ?? "default"}" from "${source.logicalPath}" to match the public eve shape.`;
const loaded = await loadModuleBackedDefinition({
- agentRoot,
- externalDependencies: options.externalDependencies,
+ binding: options.binding,
kind: "sandbox",
+ registries: options.registries,
source,
});
const inheritsParent = await resolveParentSandboxSelector(loaded, message);
@@ -45,7 +44,7 @@ export async function compileSandboxDefinition(
exportName: source.exportName,
logicalPath: source.logicalPath,
revalidationKey,
- sourceHash: await resolveSandboxSourceHash(agentRoot, source),
+ sourceHash: await resolveSandboxSourceHash(options.binding),
sourceId: source.sourceId,
sourceKind: "module",
};
@@ -127,9 +126,13 @@ async function resolveSandboxRevalidationKey(input: {
}
async function resolveSandboxSourceHash(
- agentRoot: string,
- source: SandboxSourceRef,
+ binding: ModuleBackedDefinitionLoadOptions["binding"],
): Promise<string> {
- const content = await readFile(join(agentRoot, source.logicalPath));
+ if (binding.backing.kind === "programmatic") {
+ return createHash("sha256")
+ .update(binding.backing.semanticRevision ?? binding.backing.revision)
+ .digest("hex");
+ }
+ const content = await readFile(binding.backing.sourcePath);
return createHash("sha256").update(content).digest("hex");
}
diff --git a/packages/eve/src/compiler/normalize-schedule.ts b/packages/eve/src/compiler/normalize-schedule.ts
index 458c96222..79b1cc9fb 100644
--- a/packages/eve/src/compiler/normalize-schedule.ts
+++ b/packages/eve/src/compiler/normalize-schedule.ts
@@ -5,7 +5,8 @@ import type { ScheduleDefinition } from "#public/definitions/schedule.js";
import type { CompiledScheduleDefinition } from "#compiler/manifest.js";
import {
loadModuleBackedDefinition,
- type ModuleBackedDefinitionLoadOptions,
+ requireModuleBackedDefinitionLoadOptions,
+ type SourceDefinitionCompileOptions,
} from "#compiler/normalize-helpers.js";
/**
@@ -20,9 +21,9 @@ import {
* (`schedules/billing/invoice-sweep.ts` → `"billing/invoice-sweep"`).
*/
export async function compileScheduleDefinition(
- agentRoot: string,
+ _agentRoot: string,
source: ScheduleSourceRef,
- options: ModuleBackedDefinitionLoadOptions = {},
+ options: SourceDefinitionCompileOptions,
): Promise<CompiledScheduleDefinition> {
const definition: ScheduleDefinition =
source.sourceKind === "markdown"
@@ -32,15 +33,16 @@ export async function compileScheduleDefinition(
)
: normalizeScheduleDefinition(
await loadModuleBackedDefinition({
- agentRoot,
- externalDependencies: options.externalDependencies,
+ binding: requireModuleBackedDefinitionLoadOptions(options, source.logicalPath).binding,
kind: "schedule",
+ registries: requireModuleBackedDefinitionLoadOptions(options, source.logicalPath)
+ .registries,
source,
}),
`Expected the schedule export "${source.exportName ?? "default"}" from "${source.logicalPath}" to match the public eve shape.`,
);
- const compiled: CompiledScheduleDefinition = {
+ const compiled = {
cron: definition.cron,
hasRun: definition.run !== undefined,
logicalPath: source.logicalPath,
@@ -49,11 +51,14 @@ export async function compileScheduleDefinition(
sourceKind: source.sourceKind,
};
- if (definition.markdown !== undefined) {
- return { ...compiled, markdown: definition.markdown.trim() };
- }
+ const withMarkdown =
+ definition.markdown === undefined
+ ? compiled
+ : { ...compiled, markdown: definition.markdown.trim() };
- return compiled;
+ return source.sourceKind === "module"
+ ? { ...withMarkdown, sourceKind: "module" }
+ : { ...withMarkdown, owner: options.owner, sourceKind: "markdown" };
}
function deriveScheduleName(logicalPath: string): string {
diff --git a/packages/eve/src/compiler/normalize-skill.ts b/packages/eve/src/compiler/normalize-skill.ts
index 32f3c9e10..fe61173dc 100644
--- a/packages/eve/src/compiler/normalize-skill.ts
+++ b/packages/eve/src/compiler/normalize-skill.ts
@@ -9,7 +9,8 @@ import type {
} from "#compiler/manifest.js";
import {
loadModuleBackedDefinition,
- type ModuleBackedDefinitionLoadOptions,
+ requireModuleBackedDefinitionLoadOptions,
+ type SourceDefinitionCompileOptions,
} from "#compiler/normalize-helpers.js";
import {
assertResolverOnlyDynamicSentinel,
@@ -33,12 +34,12 @@ export type CompiledSkillEntry =
* agent manifest.
*/
export async function compileSkillSource(
- agentRoot: string,
+ _agentRoot: string,
source: SkillSourceRef,
- options: ModuleBackedDefinitionLoadOptions = {},
+ options: SourceDefinitionCompileOptions,
): Promise<CompiledSkillEntry> {
if (source.sourceKind === "skill-package") {
- return { kind: "skill", definition: compileSkillPackageSource(source) };
+ return { kind: "skill", definition: compileSkillPackageSource(source, options.owner) };
}
if (source.sourceKind === "markdown") {
@@ -53,6 +54,7 @@ export async function compileSkillSource(
files: definition.files,
license: definition.license,
logicalPath: source.logicalPath,
+ owner: options.owner,
markdown: definition.markdown,
metadata:
definition.metadata === undefined
@@ -68,10 +70,11 @@ export async function compileSkillSource(
}
// Module-backed skill — load the export and check for DynamicSentinel.
+ const loadOptions = requireModuleBackedDefinitionLoadOptions(options, source.logicalPath);
const exportValue = await loadModuleBackedDefinition({
- agentRoot,
- externalDependencies: options.externalDependencies,
+ binding: loadOptions.binding,
kind: "skill",
+ registries: loadOptions.registries,
source,
});
@@ -122,12 +125,14 @@ export async function compileSkillSource(
function compileSkillPackageSource(
source: NamedSkillDefinition & SkillPackageSourceRef,
+ owner: SourceDefinitionCompileOptions["owner"],
): CompiledSkillDefinition {
return {
assetsPath: source.assetsPath,
description: source.description,
license: source.license,
logicalPath: source.logicalPath,
+ owner,
markdown: source.markdown,
metadata:
source.metadata === undefined
diff --git a/packages/eve/src/compiler/normalize-subagent.ts b/packages/eve/src/compiler/normalize-subagent.ts
index 503deee73..2c160b7dd 100644
--- a/packages/eve/src/compiler/normalize-subagent.ts
+++ b/packages/eve/src/compiler/normalize-subagent.ts
@@ -1,24 +1,3 @@
-import { join, relative } from "node:path";
-
-import {
- type AgentSourceManifest,
- createPathDerivedSourceId,
- type LocalSubagentSourceRef,
-} from "#discover/manifest.js";
-import {
- type CompiledAgentNodeManifest,
- type CompiledAgentResources,
- type CompiledRemoteAgentNode,
- type CompiledSubagentEdge,
- type CompiledSubagentNode,
- createCompiledSubagentNodeId,
-} from "#compiler/manifest.js";
-import { composeAgentSubagentSources } from "#compiler/normalize-extension.js";
-import type { CompiledDynamicSubagentDefinition } from "#compiler/remote-agent-node.js";
-import {
- loadModuleBackedDefinition,
- type ManifestCompileContext,
-} from "#compiler/normalize-helpers.js";
import {
expectBoolean,
expectFunction,
@@ -30,445 +9,83 @@ import { EVE_SESSION_ROUTE_PATH } from "#protocol/routes.js";
import { serializeOutputSchema, type ToolSchemaSource } from "#shared/tool-schema.js";
import type { JsonObject } from "#shared/json.js";
import { isDynamicSentinel, type DynamicToolEventName } from "#shared/dynamic-tool-definition.js";
+import type { LocalSubagentSourceRef } from "#discover/manifest.js";
const ALLOWED_DYNAMIC_SUBAGENT_EVENTS = new Set<DynamicToolEventName>([
"session.started",
"turn.started",
]);
-/**
- * Callback the subagent compiler uses to recurse into the per-node
- * manifest compiler. Injected by `normalize-manifest.ts` so this module
- * does not have to import the orchestrator (which would create a
- * circular dependency).
- */
-export type CompileAgentNodeManifestFn = (
- manifest: AgentSourceManifest,
- context: ManifestCompileContext,
- options?: {
- readonly agentConfigDefinition?: unknown;
- readonly externalDependencies?: readonly string[];
- readonly allowRootOnlyConfig?: boolean;
- },
-) => Promise<CompiledAgentNodeManifest>;
-
-export type CompileAgentResourcesFn = (
- manifest: AgentSourceManifest,
- context: ManifestCompileContext,
- options?: { readonly externalDependencies?: readonly string[] },
-) => Promise<CompiledAgentResources>;
-
-/**
- * Compiles every local subagent reachable from one parent node into a
- * flat node list and the parent→child edges that connect them.
- *
- * Recursive: each subagent may itself declare further subagents, which
- * are compiled depth-first via the injected `compileAgentNodeManifest`
- * callback.
- */
-export async function compileSubagentGraph(input: {
- readonly appRoot: string;
- readonly compileAgentNodeManifest: CompileAgentNodeManifestFn;
- readonly compileAgentResources: CompileAgentResourcesFn;
- readonly context: ManifestCompileContext;
- readonly externalDependencies?: readonly string[];
- readonly parentAgentRoot: string;
- readonly parentNodeId: string;
- readonly subagents: readonly LocalSubagentSourceRef[];
-}): Promise<{
- readonly edges: readonly CompiledSubagentEdge[];
- readonly nodes: readonly CompiledSubagentNode[];
- readonly remoteAgents: readonly CompiledRemoteAgentNode[];
-}> {
- const compiledNodes: CompiledSubagentNode[] = [];
- const compiledEdges: CompiledSubagentEdge[] = [];
- const compiledRemoteAgents: CompiledRemoteAgentNode[] = [];
-
- for (const subagentSource of input.subagents) {
- const compiledSubagent = await compileSubagentDefinition({
- appRoot: input.appRoot,
- compileAgentNodeManifest: input.compileAgentNodeManifest,
- compileAgentResources: input.compileAgentResources,
- context: input.context,
- externalDependencies: input.externalDependencies,
- parentAgentRoot: input.parentAgentRoot,
- parentNodeId: input.parentNodeId,
- source: subagentSource,
- });
-
- if (compiledSubagent.kind === "remote") {
- compiledRemoteAgents.push(compiledSubagent.node);
- continue;
- }
-
- compiledNodes.push(compiledSubagent.node, ...compiledSubagent.descendants.nodes);
- compiledEdges.push(
- {
- childNodeId: compiledSubagent.node.nodeId,
- parentNodeId: input.parentNodeId,
- },
- ...compiledSubagent.descendants.edges,
- );
- }
-
- return {
- edges: compiledEdges,
- nodes: compiledNodes,
- remoteAgents: compiledRemoteAgents,
- };
-}
-
-async function compileSubagentDefinition(input: {
- readonly appRoot: string;
- readonly compileAgentNodeManifest: CompileAgentNodeManifestFn;
- readonly compileAgentResources: CompileAgentResourcesFn;
- readonly context: ManifestCompileContext;
- readonly externalDependencies?: readonly string[];
- readonly parentAgentRoot: string;
- readonly parentNodeId: string;
- readonly source: LocalSubagentSourceRef;
-}): Promise<
+export type NormalizedSubagentConfig =
+ | { readonly kind: "local"; readonly definition: unknown }
| {
- readonly kind: "local";
- readonly descendants: {
- readonly edges: readonly CompiledSubagentEdge[];
- readonly nodes: readonly CompiledSubagentNode[];
- readonly remoteAgents: readonly CompiledRemoteAgentNode[];
- };
- readonly node: CompiledSubagentNode;
+ readonly build?: { readonly externalDependencies?: readonly string[] };
+ readonly eventNames: readonly DynamicToolEventName[];
+ readonly kind: "dynamic";
}
| {
+ readonly description: string;
readonly kind: "remote";
- readonly node: CompiledRemoteAgentNode;
- }
-> {
- const configModule = input.source.manifest.configModule;
-
- if (configModule === undefined) {
- throw new Error(`Subagent "${input.source.logicalPath}" is missing an agent config module.`);
- }
-
- const configModuleSource = createSubagentConfigModuleSourceRef(
- input.source,
- configModule,
- input.parentAgentRoot,
- );
- const definition = await loadModuleBackedDefinition({
- agentRoot: input.source.manifest.agentRoot,
- displayPath: configModuleSource.logicalPath,
- externalDependencies: input.externalDependencies,
- kind: "subagent config",
- source: configModule,
- });
- const dynamic = normalizeDynamicSubagentDefinition(
- definition,
- `Expected the dynamic subagent config export "${configModule.exportName ?? "default"}" from "${configModuleSource.logicalPath}" to match the public eve shape.`,
- );
- if (dynamic === undefined && readAgentDefinitionKind(definition) === "remote") {
- return {
- kind: "remote",
- node: compileRemoteAgent({
- parentAgentRoot: input.parentAgentRoot,
- source: input.source,
- value: definition,
- }),
+ readonly outputSchema?: JsonObject;
+ readonly path: string;
+ readonly url?: string;
};
- }
- return {
- kind: "local",
- ...(await compileLocalSubagent({
- ...input,
- agentConfigDefinition: dynamic === undefined ? definition : undefined,
- configResolver:
- dynamic === undefined
- ? undefined
- : { ...configModule, ...dynamic.definition, build: dynamic.build },
- })),
- };
-}
-
-async function compileSubagent(input: {
- readonly appRoot: string;
- readonly compileAgentNodeManifest: CompileAgentNodeManifestFn;
- readonly compileAgentResources: CompileAgentResourcesFn;
- readonly context: ManifestCompileContext;
- readonly agentConfigDefinition?: unknown;
- readonly configResolver?: CompiledDynamicSubagentDefinition;
- readonly externalDependencies?: readonly string[];
- readonly parentAgentRoot: string;
- readonly parentNodeId: string;
- readonly source: LocalSubagentSourceRef;
-}): Promise<{
- readonly descendants: {
- readonly edges: readonly CompiledSubagentEdge[];
- readonly nodes: readonly CompiledSubagentNode[];
- readonly remoteAgents: readonly CompiledRemoteAgentNode[];
- };
- readonly node: CompiledSubagentNode;
-}> {
- const nodeId = createCompiledSubagentNodeId(input.parentNodeId, input.source.sourceId);
- const subagentName = input.source.subagentId;
- const sourceManifest = {
- ...input.source.manifest,
- appRoot: input.appRoot,
- };
- const inheritedExternalDependencies = mergeExternalDependencies(
- input.externalDependencies,
- input.configResolver?.build?.externalDependencies,
- );
- const nodeBase = {
- entryPath: input.source.entryPath,
- logicalPath: input.source.logicalPath,
- name: subagentName,
- nodeId,
- rootPath: input.source.rootPath,
- sourceId: input.source.sourceId,
- sourceKind: "module" as const,
- };
-
- if (input.configResolver === undefined) {
- const agent = await input.compileAgentNodeManifest(sourceManifest, input.context, {
- agentConfigDefinition: input.agentConfigDefinition,
- allowRootOnlyConfig: false,
- externalDependencies: inheritedExternalDependencies,
- });
- const description = agent.config.description;
- if (!description) {
- throw new Error(
- `Local subagent "${input.source.logicalPath}" is missing a "description" field on its agent config. Add \`description\` to \`defineAgent({ ... })\` so the parent agent can decide when to delegate to this subagent.`,
- );
+export function normalizeSubagentConfig(value: unknown, message: string): NormalizedSubagentConfig {
+ if (isDynamicSentinel(value)) {
+ const record = expectObjectRecord(value, message);
+ expectOnlyKnownKeys(record, ["build", "events", "kind"], message);
+ const rawEvents = expectObjectRecord(record.events, message);
+ const eventNames: DynamicToolEventName[] = [];
+ for (const [eventName, handler] of Object.entries(rawEvents)) {
+ if (!ALLOWED_DYNAMIC_SUBAGENT_EVENTS.has(eventName as DynamicToolEventName)) {
+ throw new Error(
+ `${message} Dynamic subagents support only "session.started" and "turn.started" handlers.`,
+ );
+ }
+ expectFunction(handler, message);
+ eventNames.push(eventName as DynamicToolEventName);
}
-
- const descendants = await compileSubagentGraph({
- appRoot: input.appRoot,
- compileAgentNodeManifest: input.compileAgentNodeManifest,
- context: input.context,
- compileAgentResources: input.compileAgentResources,
- externalDependencies:
- agent.config.build?.externalDependencies ?? inheritedExternalDependencies,
- parentAgentRoot: input.source.manifest.agentRoot,
- parentNodeId: nodeId,
- subagents: composeAgentSubagentSources(input.source.manifest),
- });
- return {
- descendants,
- node: {
- ...nodeBase,
- agent: { ...agent, remoteAgents: [...descendants.remoteAgents] },
- description,
- },
- };
- }
-
- const resources = await input.compileAgentResources(sourceManifest, input.context, {
- externalDependencies: inheritedExternalDependencies,
- });
- const descendants = await compileSubagentGraph({
- appRoot: input.appRoot,
- compileAgentNodeManifest: input.compileAgentNodeManifest,
- context: input.context,
- compileAgentResources: input.compileAgentResources,
- externalDependencies: inheritedExternalDependencies,
- parentAgentRoot: input.source.manifest.agentRoot,
- parentNodeId: nodeId,
- subagents: composeAgentSubagentSources(input.source.manifest),
- });
- return {
- descendants,
- node: {
- ...nodeBase,
- agent: { ...resources, remoteAgents: [...descendants.remoteAgents] },
- configResolver: input.configResolver,
- },
- };
-}
-
-const compileLocalSubagent = compileSubagent;
-
-function compileRemoteAgent(input: {
- readonly parentAgentRoot: string;
- readonly source: LocalSubagentSourceRef;
- readonly value: unknown;
-}): CompiledRemoteAgentNode {
- const configModule = input.source.manifest.configModule;
-
- if (configModule === undefined) {
- throw new Error(`Remote agent "${input.source.logicalPath}" is missing a config module.`);
+ const build =
+ record.build === undefined ? undefined : normalizeDynamicSubagentBuild(record.build, message);
+ return build === undefined
+ ? { eventNames, kind: "dynamic" }
+ : { build, eventNames, kind: "dynamic" };
}
- assertRemoteAgentDefinitionHasNoLocalPackageEntries(input.source);
-
- const moduleSource = createSubagentConfigModuleSourceRef(
- input.source,
- configModule,
- input.parentAgentRoot,
- );
- const definition = normalizeRemoteAgentDefinition(
- input.value,
- `Expected the remote agent config export "${configModule.exportName ?? "default"}" from "${moduleSource.logicalPath}" to match the public eve shape.`,
- );
- const node = {
- ...moduleSource,
- description: definition.description,
- entryPath: input.source.entryPath,
- name: input.source.subagentId,
- nodeId: input.source.sourceId,
- outputSchema: definition.outputSchema,
- path: definition.path,
- rootPath: input.source.rootPath,
- };
-
- // A function `url` is deferred, so the compiled node omits it entirely.
- return definition.url === undefined ? node : { ...node, url: definition.url };
-}
-
-function normalizeDynamicSubagentDefinition(
- value: unknown,
- message: string,
-):
- | {
- readonly build?: { readonly externalDependencies?: readonly string[] };
- readonly definition: { readonly eventNames: readonly DynamicToolEventName[] };
- }
- | undefined {
- if (!isDynamicSentinel(value)) {
- return undefined;
- }
-
- const record = expectObjectRecord(value, message);
- expectOnlyKnownKeys(record, ["build", "events", "kind"], message);
-
- const build =
- record.build === undefined ? undefined : normalizeDynamicSubagentBuild(record.build, message);
- const rawEvents = expectObjectRecord(record.events, message);
- const eventNames: DynamicToolEventName[] = [];
-
- for (const [eventName, handler] of Object.entries(rawEvents)) {
- if (!ALLOWED_DYNAMIC_SUBAGENT_EVENTS.has(eventName as DynamicToolEventName)) {
- throw new Error(
- `${message} Dynamic subagents support only "session.started" and "turn.started" handlers.`,
+ if (
+ value !== null &&
+ typeof value === "object" &&
+ (value as { readonly kind?: unknown }).kind === "remote"
+ ) {
+ const record = expectObjectRecord(value, message);
+ expectOnlyKnownKeys(
+ record,
+ ["auth", "description", "forwardPrincipal", "headers", "kind", "outputSchema", "path", "url"],
+ message,
+ );
+ if (record.forwardPrincipal !== undefined) {
+ expectBoolean(
+ record.forwardPrincipal,
+ `${message} Expected "forwardPrincipal" to be a boolean.`,
);
}
- expectFunction(handler, message);
- eventNames.push(eventName as DynamicToolEventName);
- }
-
- const normalized: {
- build?: { readonly externalDependencies?: readonly string[] };
- readonly definition: { readonly eventNames: readonly DynamicToolEventName[] };
- } = {
- definition: { eventNames },
- };
- if (build !== undefined) {
- normalized.build = build;
+ const outputSchema = serializeOutputSchema(record.outputSchema as ToolSchemaSource | undefined);
+ return {
+ description: expectString(record.description, message),
+ kind: "remote",
+ outputSchema,
+ path: record.path === undefined ? EVE_SESSION_ROUTE_PATH : expectString(record.path, message),
+ url: typeof record.url === "function" ? undefined : expectString(record.url, message),
+ };
}
- return normalized;
-}
-
-function normalizeDynamicSubagentBuild(
- value: unknown,
- message: string,
-): { readonly externalDependencies?: readonly string[] } {
- const record = expectObjectRecord(value, message);
- expectOnlyKnownKeys(record, ["externalDependencies"], message);
- if (record.externalDependencies === undefined) return {};
- if (!Array.isArray(record.externalDependencies)) throw new Error(message);
- return {
- externalDependencies: record.externalDependencies.map((entry) => expectString(entry, message)),
- };
-}
-function mergeExternalDependencies(
- ...lists: ReadonlyArray<readonly string[] | undefined>
-): readonly string[] {
- return [...new Set(lists.flatMap((list) => list ?? []))];
+ return { definition: value, kind: "local" };
}
-function createSubagentConfigModuleSourceRef(
+export function assertRemoteAgentDefinitionHasNoLocalPackageEntries(
source: LocalSubagentSourceRef,
- configModule: NonNullable<LocalSubagentSourceRef["manifest"]["configModule"]>,
- parentAgentRoot: string,
-): {
- readonly exportName?: string;
- readonly logicalPath: string;
- readonly sourceId: string;
- readonly sourceKind: "module";
-} {
- const logicalPath = relative(
- parentAgentRoot,
- join(source.manifest.agentRoot, configModule.logicalPath),
- ).replaceAll("\\", "/");
- const sourceId =
- configModule.sourceId.startsWith("ext:") || configModule.sourceId.startsWith("ext-override:")
- ? configModule.sourceId
- : createPathDerivedSourceId(logicalPath);
- const moduleSource: {
- exportName?: string;
- logicalPath: string;
- sourceId: string;
- sourceKind: "module";
- } = {
- logicalPath,
- sourceId,
- sourceKind: "module",
- };
-
- if (configModule.exportName !== undefined) {
- moduleSource.exportName = configModule.exportName;
- }
-
- return moduleSource;
-}
-
-function readAgentDefinitionKind(value: unknown): "local" | "remote" {
- if (value === null || typeof value !== "object") {
- return "local";
- }
-
- return (value as { readonly kind?: unknown }).kind === "remote" ? "remote" : "local";
-}
-
-function normalizeRemoteAgentDefinition(
- value: unknown,
- message: string,
-): {
- readonly description: string;
- readonly outputSchema?: JsonObject;
- readonly path: string;
- readonly url?: string;
-} {
- const record = expectObjectRecord(value, message);
- expectOnlyKnownKeys(
- record,
- ["auth", "description", "forwardPrincipal", "headers", "kind", "outputSchema", "path", "url"],
- message,
- );
-
- if (record.kind !== "remote") {
- throw new Error(`${message} Expected "kind" to be "remote".`);
- }
-
- // `forwardPrincipal` rides the module-backed runtime definition (like
- // `auth` and `headers`), so it is validated here but never baked into the
- // manifest.
- if (record.forwardPrincipal !== undefined) {
- expectBoolean(
- record.forwardPrincipal,
- `${message} Expected "forwardPrincipal" to be a boolean.`,
- );
- }
-
- return {
- description: expectString(record.description, message),
- outputSchema: serializeOutputSchema(record.outputSchema as ToolSchemaSource | undefined),
- path: record.path === undefined ? EVE_SESSION_ROUTE_PATH : expectString(record.path, message),
- // A function `url` is resolved at runtime, not baked into the manifest.
- url: typeof record.url === "function" ? undefined : expectString(record.url, message),
- };
-}
-
-function assertRemoteAgentDefinitionHasNoLocalPackageEntries(source: LocalSubagentSourceRef): void {
+): void {
const manifest = source.manifest;
const extraEntries = [
manifest.connections.length > 0 ? "connections/" : undefined,
@@ -482,12 +99,22 @@ function assertRemoteAgentDefinitionHasNoLocalPackageEntries(source: LocalSubage
manifest.subagents.length > 0 ? "subagents/" : undefined,
manifest.tools.length > 0 ? "tools/" : undefined,
].filter((entry) => entry !== undefined);
-
- if (extraEntries.length === 0) {
- return;
+ if (extraEntries.length > 0) {
+ throw new Error(
+ `Remote subagent definition "${source.logicalPath}" cannot include local package entries. Remove unsupported entries: ${extraEntries.join(", ")}.`,
+ );
}
+}
- throw new Error(
- `Remote subagent definition "${source.logicalPath}" cannot include local package entries. Remove unsupported entries: ${extraEntries.join(", ")}.`,
- );
+function normalizeDynamicSubagentBuild(
+ value: unknown,
+ message: string,
+): { readonly externalDependencies?: readonly string[] } {
+ const record = expectObjectRecord(value, message);
+ expectOnlyKnownKeys(record, ["externalDependencies"], message);
+ if (record.externalDependencies === undefined) return {};
+ if (!Array.isArray(record.externalDependencies)) throw new Error(message);
+ return {
+ externalDependencies: record.externalDependencies.map((entry) => expectString(entry, message)),
+ };
}
diff --git a/packages/eve/src/compiler/normalize-tool.ts b/packages/eve/src/compiler/normalize-tool.ts
index 7b6a5e3d2..ee7f78507 100644
--- a/packages/eve/src/compiler/normalize-tool.ts
+++ b/packages/eve/src/compiler/normalize-tool.ts
@@ -18,7 +18,11 @@ export type CompiledToolEntry =
| { readonly kind: "tool"; readonly definition: CompiledToolDefinition }
| { readonly kind: "disabled"; readonly name: string }
| { readonly kind: "workflow-tool"; readonly maxSubagents?: number }
- | { readonly kind: "web-search-tool"; readonly provider: "exa" | "parallel" }
+ | {
+ readonly definition: CompiledToolDefinition;
+ readonly kind: "web-search-tool";
+ readonly provider: "exa" | "parallel";
+ }
| { readonly kind: "dynamic-tool"; readonly definition: CompiledDynamicToolDefinition };
/**
@@ -34,15 +38,15 @@ export type CompiledToolEntry =
* are rejected by the normalizer.
*/
export async function compileToolEntry(
- agentRoot: string,
+ _agentRoot: string,
source: ToolSourceRef,
- options: ModuleBackedDefinitionLoadOptions = {},
+ options: ModuleBackedDefinitionLoadOptions,
): Promise<CompiledToolEntry> {
const entry = normalizeToolDefinition(
await loadModuleBackedDefinition({
- agentRoot,
- externalDependencies: options.externalDependencies,
+ binding: options.binding,
kind: "tool",
+ registries: options.registries,
source,
}),
`Expected the tool export "${source.exportName ?? "default"}" from "${source.logicalPath}" to match the public eve shape.`,
@@ -65,7 +69,23 @@ export async function compileToolEntry(
`The webSearch() definition must be exported from "tools/web_search.ts", not "${source.logicalPath}".`,
);
}
- return { kind: "web-search-tool", provider: entry.provider };
+ return {
+ definition: {
+ description:
+ "Search the web for real-time information. Use this to find up-to-date information about current events, recent developments, or topics that may have changed since the knowledge cutoff.",
+ exportName: source.exportName,
+ hasExecute: false,
+ hasModelOutputProjection: false,
+ inputSchema: null,
+ logicalPath: source.logicalPath,
+ name: toolName,
+ sourceId: source.sourceId,
+ sourceKind: "module",
+ requiresApproval: false,
+ },
+ kind: "web-search-tool",
+ provider: entry.provider,
+ };
}
if (entry.kind === "dynamic-tool") {
@@ -88,10 +108,13 @@ export async function compileToolEntry(
description: entry.definition.description,
execution: entry.definition.execution,
exportName: source.exportName,
+ hasExecute: true,
+ hasModelOutputProjection: entry.definition.hasModelOutputProjection,
inputSchema: entry.definition.inputSchema ?? null,
logicalPath: source.logicalPath,
name: toolName,
outputSchema: entry.definition.outputSchema,
+ requiresApproval: entry.definition.hasApproval,
sourceId: source.sourceId,
sourceKind: "module",
},
diff --git a/packages/eve/src/compiler/project-sources.ts b/packages/eve/src/compiler/project-sources.ts
new file mode 100644
index 000000000..4f7b11076
--- /dev/null
+++ b/packages/eve/src/compiler/project-sources.ts
@@ -0,0 +1,401 @@
+import { join } from "node:path";
+
+import type {
+ AgentSourceManifest,
+ ConnectionSourceRef,
+ InstructionsSourceRef,
+ LocalSubagentSourceRef,
+ ResolvedExtensionMount,
+ ScheduleSourceRef,
+ SkillSourceRef,
+} from "#discover/manifest.js";
+import { stripLogicalPathExtension } from "#discover/filesystem.js";
+import type { ModuleSourceRef } from "#shared/source-ref.js";
+import type {
+ AgentModuleCandidate,
+ AgentResourceCandidate,
+ AgentSourceCandidate,
+ AgentSourceLayer,
+ AgentSourceOwner,
+} from "#compiler/source-graph.js";
+import { canonicalSourceSlot } from "#compiler/source-graph.js";
+
+export type ProjectedModuleSource =
+ | {
+ readonly candidate: AgentModuleCandidate;
+ readonly kind: "connection";
+ readonly source: ConnectionSourceRef;
+ }
+ | {
+ readonly candidate: AgentModuleCandidate;
+ readonly kind:
+ | "channel"
+ | "config"
+ | "extension"
+ | "hook"
+ | "instructions"
+ | "instrumentation"
+ | "sandbox"
+ | "schedule"
+ | "skill"
+ | "tool";
+ readonly source: ModuleSourceRef;
+ };
+
+export type ProjectedResourceSource =
+ | {
+ readonly candidate: AgentResourceCandidate;
+ readonly kind: "instructions";
+ readonly source: InstructionsSourceRef;
+ }
+ | {
+ readonly candidate: AgentResourceCandidate;
+ readonly kind: "schedule";
+ readonly source: ScheduleSourceRef;
+ }
+ | {
+ readonly candidate: AgentResourceCandidate;
+ readonly kind: "skill";
+ readonly source: SkillSourceRef;
+ };
+
+export type ProjectedSource = ProjectedModuleSource | ProjectedResourceSource;
+
+const MODULE_KIND_BY_SLOT_ROOT: Partial<
+ Record<string, Exclude<ProjectedModuleSource["kind"], "connection">>
+> = {
+ agent: "config",
+ channels: "channel",
+ extensions: "extension",
+ hooks: "hook",
+ instructions: "instructions",
+ instrumentation: "instrumentation",
+ sandbox: "sandbox",
+ schedules: "schedule",
+ skills: "skill",
+ tools: "tool",
+};
+
+export interface ProjectedSubagentSource {
+ readonly candidate: AgentResourceCandidate;
+ readonly extensionScope?: { readonly namespace: string; readonly sourceRoot: string };
+ readonly owner: AgentSourceOwner;
+ readonly source: LocalSubagentSourceRef;
+}
+
+export interface ProjectedAgentSources {
+ readonly candidates: readonly AgentSourceCandidate[];
+ readonly resources: readonly ProjectedResourceSource[];
+ readonly subagents: readonly ProjectedSubagentSource[];
+}
+
+export function projectAgentSources(input: {
+ readonly externalDependencies: readonly string[];
+ readonly extensionScope?: { readonly namespace: string; readonly sourceRoot: string };
+ readonly layer?: AgentSourceLayer;
+ readonly manifest: AgentSourceManifest;
+ readonly nodeId: string;
+ readonly owner?: AgentSourceOwner;
+}): ProjectedAgentSources {
+ const owner = input.owner ?? { kind: "application" as const };
+ const candidates: AgentSourceCandidate[] = [];
+ const resources: ProjectedResourceSource[] = [];
+ const subagents: ProjectedSubagentSource[] = [];
+
+ projectManifest({
+ externalDependencies: input.externalDependencies,
+ candidates,
+ extensionScope: input.extensionScope,
+ layer: input.layer ?? "application",
+ manifest: input.manifest,
+ nodeId: input.nodeId,
+ owner,
+ resources,
+ subagents,
+ });
+
+ for (const mount of [...input.manifest.resolvedExtensions].sort((left, right) =>
+ left.namespace.localeCompare(right.namespace),
+ )) {
+ const extensionOwner: AgentSourceOwner = {
+ kind: "extension",
+ namespace: mount.namespace,
+ packageName: mount.packageName,
+ };
+ projectManifest({
+ externalDependencies: mergeDependencies(
+ input.externalDependencies,
+ mount.externalDependencies,
+ ),
+ candidates,
+ extension: mount,
+ layer: "extension-package",
+ manifest: mount.manifest,
+ nodeId: input.nodeId,
+ owner: extensionOwner,
+ resources,
+ sourceIdPrefix: `ext:${mount.namespace}:`,
+ subagents,
+ });
+ if (mount.overrides !== undefined) {
+ projectManifest({
+ externalDependencies: input.externalDependencies,
+ candidates,
+ extension: mount,
+ layer: "extension-override",
+ manifest: mount.overrides,
+ nodeId: input.nodeId,
+ owner: { kind: "application" },
+ resources,
+ sourceIdPrefix: `ext-override:${mount.namespace}:`,
+ subagents,
+ });
+ }
+ }
+
+ return { candidates, resources, subagents };
+}
+
+export function projectSelectedSources(input: {
+ readonly candidates: Iterable<AgentSourceCandidate>;
+ readonly resources: readonly ProjectedResourceSource[];
+}): readonly ProjectedSource[] {
+ const resourcesBySourceId = new Map(
+ input.resources.map((entry) => [entry.candidate.sourceId, entry]),
+ );
+ const projected: ProjectedSource[] = [];
+ for (const candidate of input.candidates) {
+ if (!isModuleCandidate(candidate)) {
+ const resource = resourcesBySourceId.get(candidate.sourceId);
+ if (resource !== undefined) projected.push(resource);
+ } else {
+ projected.push(projectModuleCandidate(candidate));
+ }
+ }
+ return projected;
+}
+
+export function createFilesystemModuleCandidate(input: {
+ readonly externalDependencies: readonly string[];
+ readonly extension?: ResolvedExtensionMount;
+ readonly extensionScope?: { readonly namespace: string; readonly sourceRoot: string };
+ readonly layer: AgentSourceLayer;
+ readonly logicalPath: string;
+ readonly nodeId: string;
+ readonly owner: AgentSourceOwner;
+ readonly source: ModuleSourceRef;
+ readonly sourceId?: string;
+ readonly sourceRoot: string;
+}): AgentModuleCandidate {
+ const backing = {
+ externalDependencies: [...input.externalDependencies],
+ ...(input.owner.kind === "extension" &&
+ (input.extension !== undefined || input.extensionScope !== undefined)
+ ? {
+ extensionScope: {
+ namespace: input.extension?.namespace ?? input.extensionScope!.namespace,
+ sourceRoot: input.extension?.sourceRoot ?? input.extensionScope!.sourceRoot,
+ },
+ }
+ : {}),
+ kind: "filesystem" as const,
+ sourcePath: join(input.sourceRoot, input.source.logicalPath),
+ };
+ return {
+ backing,
+ exportName: input.source.exportName,
+ layer: input.layer,
+ logicalPath: input.logicalPath,
+ nodeId: input.nodeId,
+ owner: input.owner,
+ sourceId: input.sourceId ?? input.source.sourceId,
+ };
+}
+
+function projectManifest(input: {
+ readonly candidates: AgentSourceCandidate[];
+ readonly externalDependencies: readonly string[];
+ readonly extension?: ResolvedExtensionMount;
+ readonly extensionScope?: { readonly namespace: string; readonly sourceRoot: string };
+ readonly layer: AgentSourceLayer;
+ readonly manifest: AgentSourceManifest;
+ readonly nodeId: string;
+ readonly owner: AgentSourceOwner;
+ readonly resources: ProjectedResourceSource[];
+ readonly sourceIdPrefix?: string;
+ readonly subagents: ProjectedSubagentSource[];
+}): void {
+ const qualify = (logicalPath: string) =>
+ input.extension === undefined
+ ? logicalPath
+ : qualifyExtensionLogicalPath(logicalPath, input.extension.namespace);
+ const sourceId = (id: string) => `${input.sourceIdPrefix ?? ""}${id}`;
+ const pushModule = (source: ModuleSourceRef, logicalPathOverride?: string) => {
+ const logicalPath = logicalPathOverride ?? qualify(source.logicalPath);
+ const candidate = createFilesystemModuleCandidate({
+ externalDependencies: input.externalDependencies,
+ extension: input.extension,
+ extensionScope: input.extensionScope,
+ layer: input.layer,
+ logicalPath,
+ nodeId: input.nodeId,
+ owner: input.owner,
+ source,
+ sourceId: sourceId(source.sourceId),
+ sourceRoot: input.manifest.agentRoot,
+ });
+ input.candidates.push(candidate);
+ };
+ const pushResource = (
+ kind: ProjectedResourceSource["kind"],
+ source: InstructionsSourceRef | ScheduleSourceRef | SkillSourceRef,
+ ) => {
+ const logicalPath = qualify(source.logicalPath);
+ const projected = {
+ ...source,
+ ...(source.sourceKind === "skill-package"
+ ? {
+ name:
+ input.extension === undefined
+ ? source.name
+ : `${input.extension.namespace}__${source.name}`,
+ }
+ : {}),
+ logicalPath,
+ sourceId: sourceId(source.sourceId),
+ };
+ const candidate: AgentResourceCandidate = {
+ backing: {
+ kind: "resource",
+ sourcePath:
+ source.sourceKind === "skill-package"
+ ? source.skillFilePath
+ : join(input.manifest.agentRoot, source.logicalPath),
+ },
+ layer: input.layer,
+ logicalPath,
+ nodeId: input.nodeId,
+ owner: input.owner,
+ sourceId: projected.sourceId,
+ };
+ input.candidates.push(candidate);
+ input.resources.push({
+ candidate,
+ kind,
+ source: projected,
+ } as ProjectedResourceSource);
+ };
+
+ if (input.extension === undefined && input.manifest.configModule !== undefined) {
+ const logicalPath = input.manifest.configModule.logicalPath;
+ pushModule(
+ input.manifest.configModule,
+ canonicalSourceSlot(logicalPath) === "agent" ? undefined : "agent.ts",
+ );
+ }
+ if (input.manifest.instrumentation !== undefined) {
+ pushModule(input.manifest.instrumentation);
+ }
+ if (input.extension === undefined) {
+ for (const source of input.manifest.extensions) pushModule(source);
+ }
+ for (const source of input.manifest.channels) pushModule(source);
+ for (const source of input.manifest.connections) pushModule(source);
+ for (const source of input.manifest.hooks) pushModule(source);
+ if (input.manifest.sandbox !== null) pushModule(input.manifest.sandbox);
+ for (const source of input.manifest.tools) pushModule(source);
+ for (const source of input.manifest.instructions) {
+ if (source.sourceKind === "module") pushModule(source);
+ else pushResource("instructions", source);
+ }
+ for (const source of input.manifest.schedules) {
+ if (source.sourceKind === "module") pushModule(source);
+ else pushResource("schedule", source);
+ }
+ for (const source of input.manifest.skills) {
+ if (source.sourceKind === "module") pushModule(source);
+ else pushResource("skill", source);
+ }
+ for (const source of input.manifest.subagents) {
+ const name =
+ input.extension === undefined
+ ? source.subagentId
+ : `${input.extension.namespace}__${source.subagentId}`;
+ const logicalPath =
+ input.extension === undefined
+ ? source.logicalPath
+ : qualifyExtensionLogicalPath(source.logicalPath, input.extension.namespace);
+ const projectedSource = {
+ ...source,
+ logicalPath,
+ sourceId: sourceId(source.sourceId),
+ subagentId: name,
+ };
+ const candidate: AgentResourceCandidate = {
+ backing: { kind: "resource", sourcePath: source.entryPath },
+ layer: input.layer,
+ logicalPath,
+ nodeId: input.nodeId,
+ owner: input.owner,
+ sourceId: projectedSource.sourceId,
+ };
+ input.candidates.push(candidate);
+ input.subagents.push({
+ candidate,
+ ...(input.extension === undefined && input.extensionScope === undefined
+ ? {}
+ : {
+ extensionScope:
+ input.extension === undefined
+ ? input.extensionScope
+ : { namespace: input.extension.namespace, sourceRoot: input.extension.sourceRoot },
+ }),
+ owner: input.owner,
+ source: projectedSource,
+ });
+ }
+}
+
+function projectModuleCandidate(candidate: AgentModuleCandidate): ProjectedModuleSource {
+ const source: ModuleSourceRef = {
+ exportName: candidate.exportName,
+ logicalPath: candidate.logicalPath,
+ sourceId: candidate.sourceId,
+ sourceKind: "module",
+ };
+ const slot = canonicalSourceSlot(candidate.logicalPath);
+ if (slot.startsWith("connections/")) {
+ return {
+ candidate,
+ kind: "connection",
+ source: { ...source, connectionName: deriveConnectionName(candidate.logicalPath) },
+ };
+ }
+ const kind = MODULE_KIND_BY_SLOT_ROOT[slot.split("/", 1)[0]!];
+ if (kind === undefined) {
+ throw new Error(`Agent module source slot "${candidate.logicalPath}" is not compiled yet.`);
+ }
+ return { candidate, kind, source };
+}
+
+function isModuleCandidate(candidate: AgentSourceCandidate): candidate is AgentModuleCandidate {
+ return candidate.backing.kind !== "resource";
+}
+
+export function qualifyExtensionLogicalPath(logicalPath: string, namespace: string): string {
+ const parts = logicalPath.split("/");
+ if (parts.length < 2) return logicalPath;
+ const root = parts[0]!;
+ if (root === "sandbox" || root === "extensions" || root === "lib") return logicalPath;
+ parts[1] = `${namespace}__${parts[1]}`;
+ return parts.join("/");
+}
+
+function deriveConnectionName(logicalPath: string): string {
+ const stripped = stripLogicalPathExtension(logicalPath).replace(/^connections\//, "");
+ return stripped.endsWith("/connection") ? stripped.slice(0, -"/connection".length) : stripped;
+}
+
+function mergeDependencies(...lists: readonly (readonly string[])[]): readonly string[] {
+ return [...new Set(lists.flat())];
+}
diff --git a/packages/eve/src/compiler/remote-agent-node.ts b/packages/eve/src/compiler/remote-agent-node.ts
index b1122f114..c6a24fe32 100644
--- a/packages/eve/src/compiler/remote-agent-node.ts
+++ b/packages/eve/src/compiler/remote-agent-node.ts
@@ -4,6 +4,7 @@ import { jsonObjectSchema } from "#shared/json-schemas.js";
import type { JsonObject } from "#shared/json.js";
import type { Node } from "#shared/node.js";
import type { ModuleSourceRef } from "#shared/source-ref.js";
+import type { AgentSourceOwner, CompiledModuleBinding } from "#compiler/source-graph.js";
export interface CompiledDynamicSubagentDefinition extends Readonly<ModuleSourceRef> {
readonly build?: {
@@ -21,8 +22,12 @@ export type CompiledRemoteAgentNode = Readonly<
ModuleSourceRef &
Node & {
description: string;
+ backing: { readonly kind: "resource"; readonly sourcePath: string };
+ binding: CompiledModuleBinding;
entryPath: string;
name: string;
+ owner: AgentSourceOwner;
+ parentNodeId: string;
outputSchema?: JsonObject;
path: string;
rootPath: string;
@@ -36,12 +41,59 @@ export type CompiledRemoteAgentNode = Readonly<
*/
export const compiledRemoteAgentNodeSchema: z.ZodType<CompiledRemoteAgentNode> = z
.object({
+ backing: z.object({ kind: z.literal("resource"), sourcePath: z.string() }).strict(),
+ binding: z
+ .object({
+ backing: z.discriminatedUnion("kind", [
+ z
+ .object({
+ externalDependencies: z.array(z.string()).readonly(),
+ extensionScope: z
+ .object({ namespace: z.string(), sourceRoot: z.string() })
+ .strict()
+ .optional(),
+ kind: z.literal("filesystem"),
+ sourcePath: z.string(),
+ })
+ .strict(),
+ z
+ .object({
+ kind: z.literal("programmatic"),
+ moduleId: z.string(),
+ registryId: z.string(),
+ revision: z.string(),
+ semanticRevision: z.string().optional(),
+ })
+ .strict(),
+ ]),
+ logicalPath: z.string(),
+ owner: z.discriminatedUnion("kind", [
+ z.object({ kind: z.literal("application") }).strict(),
+ z.object({ feature: z.string(), kind: z.literal("framework") }).strict(),
+ z
+ .object({
+ kind: z.literal("extension"),
+ namespace: z.string(),
+ packageName: z.string(),
+ })
+ .strict(),
+ ]),
+ })
+ .strict(),
description: z.string(),
entryPath: z.string(),
exportName: z.string().optional(),
logicalPath: z.string(),
name: z.string(),
nodeId: z.string(),
+ owner: z.discriminatedUnion("kind", [
+ z.object({ kind: z.literal("application") }).strict(),
+ z.object({ feature: z.string(), kind: z.literal("framework") }).strict(),
+ z
+ .object({ kind: z.literal("extension"), namespace: z.string(), packageName: z.string() })
+ .strict(),
+ ]),
+ parentNodeId: z.string(),
outputSchema: jsonObjectSchema.optional(),
path: z.string(),
rootPath: z.string(),
diff --git a/packages/eve/src/compiler/source-graph.ts b/packages/eve/src/compiler/source-graph.ts
new file mode 100644
index 000000000..d748f93e8
--- /dev/null
+++ b/packages/eve/src/compiler/source-graph.ts
@@ -0,0 +1,489 @@
+import { isAbsolute, posix } from "node:path";
+
+import {
+ getSupportedModuleBaseName,
+ normalizeLogicalPath,
+ stripLogicalPathExtension,
+} from "#discover/filesystem.js";
+
+export type ProgrammaticModuleNamespace = Readonly<Record<string, unknown>>;
+
+export interface ProgrammaticAgentModule {
+ readonly exportName?: string;
+ readonly loadNamespace: () => Promise<ProgrammaticModuleNamespace>;
+ readonly logicalPath: string;
+ readonly semanticRevision?: string;
+}
+
+export interface ProgrammaticAgentSource {
+ readonly id: string;
+ readonly modules: readonly ProgrammaticAgentModule[];
+ readonly revision: string;
+}
+
+export interface AgentSourceRegistration {
+ readonly applyTo: "root" | "all-local-nodes";
+ readonly source: ProgrammaticAgentSource;
+}
+
+export interface AgentSourceRegistry {
+ readonly registrations: readonly AgentSourceRegistration[];
+ readonly sources: ReadonlyMap<string, ProgrammaticAgentSource>;
+}
+
+class ImmutableProgrammaticSourceMap implements ReadonlyMap<string, ProgrammaticAgentSource> {
+ readonly #values: ReadonlyMap<string, ProgrammaticAgentSource>;
+
+ constructor(values: ReadonlyMap<string, ProgrammaticAgentSource>) {
+ this.#values = new Map(values);
+ Object.freeze(this);
+ }
+
+ get size(): number {
+ return this.#values.size;
+ }
+
+ get [Symbol.toStringTag](): string {
+ return "ImmutableProgrammaticSourceMap";
+ }
+
+ [Symbol.iterator](): MapIterator<[string, ProgrammaticAgentSource]> {
+ return this.#values[Symbol.iterator]();
+ }
+
+ entries(): MapIterator<[string, ProgrammaticAgentSource]> {
+ return this.#values.entries();
+ }
+
+ forEach(
+ callbackfn: (
+ value: ProgrammaticAgentSource,
+ key: string,
+ map: ReadonlyMap<string, ProgrammaticAgentSource>,
+ ) => void,
+ thisArg?: unknown,
+ ): void {
+ this.#values.forEach((value, key) => callbackfn.call(thisArg, value, key, this));
+ }
+
+ get(key: string): ProgrammaticAgentSource | undefined {
+ return this.#values.get(key);
+ }
+
+ has(key: string): boolean {
+ return this.#values.has(key);
+ }
+
+ keys(): MapIterator<string> {
+ return this.#values.keys();
+ }
+
+ values(): MapIterator<ProgrammaticAgentSource> {
+ return this.#values.values();
+ }
+}
+
+export type AgentSourceOwner =
+ | { readonly kind: "application" }
+ | { readonly feature: string; readonly kind: "framework" }
+ | {
+ readonly kind: "extension";
+ readonly namespace: string;
+ readonly packageName: string;
+ };
+
+export type AgentSourceLayer =
+ | "framework-default"
+ | "extension-package"
+ | "extension-override"
+ | "application";
+
+export type AgentModuleBacking =
+ | {
+ readonly externalDependencies: readonly string[];
+ readonly extensionScope?: {
+ readonly namespace: string;
+ readonly sourceRoot: string;
+ };
+ readonly kind: "filesystem";
+ readonly sourcePath: string;
+ }
+ | {
+ readonly kind: "programmatic";
+ readonly moduleId: string;
+ readonly registryId: string;
+ readonly revision: string;
+ readonly semanticRevision?: string;
+ };
+
+export type AgentSourceBacking =
+ | AgentModuleBacking
+ | {
+ readonly kind: "resource";
+ readonly sourcePath: string;
+ };
+
+export interface AgentModuleCandidate {
+ readonly backing: AgentModuleBacking;
+ readonly exportName?: string;
+ readonly layer: AgentSourceLayer;
+ readonly logicalPath: string;
+ readonly nodeId: string;
+ readonly owner: AgentSourceOwner;
+ readonly sourceId: string;
+}
+
+export interface CompiledModuleBinding {
+ readonly backing: AgentModuleBacking;
+ readonly logicalPath: string;
+ readonly owner: AgentSourceOwner;
+}
+
+export interface AgentSourceDescriptor {
+ readonly backing: AgentSourceBacking;
+ readonly layer: AgentSourceLayer;
+ readonly logicalPath: string;
+ readonly owner: AgentSourceOwner;
+ readonly sourceId: string;
+}
+
+export interface AgentResourceCandidate {
+ readonly backing: Extract<AgentSourceBacking, { readonly kind: "resource" }>;
+ readonly layer: AgentSourceLayer;
+ readonly logicalPath: string;
+ readonly nodeId: string;
+ readonly owner: AgentSourceOwner;
+ readonly sourceId: string;
+}
+
+export type AgentSourceCandidate = AgentModuleCandidate | AgentResourceCandidate;
+
+export type AgentSourceCompositionEntry =
+ | {
+ readonly kind: "shadowed";
+ readonly source: AgentSourceDescriptor;
+ readonly winnerSourceId: string;
+ }
+ | {
+ readonly kind: "disabled";
+ readonly source: AgentSourceDescriptor;
+ };
+
+export interface AgentSourceComposition {
+ readonly entries: readonly AgentSourceCompositionEntry[];
+}
+
+export interface ComposedAgentModuleCandidates {
+ readonly composition: AgentSourceComposition;
+ readonly selected: ReadonlyMap<string, AgentSourceCandidate>;
+}
+
+const LAYER_PRECEDENCE: Readonly<Record<AgentSourceLayer, number>> = {
+ "framework-default": 0,
+ "extension-package": 1,
+ "extension-override": 2,
+ application: 3,
+};
+
+export function defineProgrammaticAgentSource(
+ input: ProgrammaticAgentSource,
+): ProgrammaticAgentSource {
+ const id = expectNonEmpty(input.id, "Programmatic agent source id");
+ const revision = expectNonEmpty(input.revision, `Programmatic agent source "${id}" revision`);
+ const logicalPaths = new Set<string>();
+ const modules = input.modules.map((module) => {
+ const logicalPath = validateProgrammaticLogicalPath(module.logicalPath);
+ if (logicalPaths.has(logicalPath)) {
+ throw new Error(
+ `Programmatic agent source "${id}" declares "${logicalPath}" more than once.`,
+ );
+ }
+ logicalPaths.add(logicalPath);
+ const semanticRevision =
+ module.semanticRevision === undefined
+ ? undefined
+ : expectNonEmpty(
+ module.semanticRevision,
+ `Programmatic module "${id}:${logicalPath}" semanticRevision`,
+ );
+ return Object.freeze({
+ exportName: module.exportName,
+ loadNamespace: module.loadNamespace,
+ logicalPath,
+ semanticRevision,
+ });
+ });
+
+ return Object.freeze({ id, modules: Object.freeze(modules), revision });
+}
+
+export function createAgentSourceRegistry(
+ registrations: readonly AgentSourceRegistration[],
+): AgentSourceRegistry {
+ const sources = new Map<string, ProgrammaticAgentSource>();
+ const frozenRegistrations = registrations.map((registration) => {
+ const source = defineProgrammaticAgentSource(registration.source);
+ const existing = sources.get(source.id);
+ if (existing !== undefined) {
+ throw new Error(`Programmatic agent source id "${source.id}" is registered more than once.`);
+ }
+ sources.set(source.id, source);
+ return Object.freeze({ applyTo: registration.applyTo, source });
+ });
+
+ return Object.freeze({
+ registrations: Object.freeze(frozenRegistrations),
+ sources: new ImmutableProgrammaticSourceMap(sources),
+ });
+}
+
+export function createProgrammaticModuleCandidates(input: {
+ readonly layer: AgentSourceLayer;
+ readonly nodeId: string;
+ readonly owner: AgentSourceOwner;
+ readonly registration: AgentSourceRegistration;
+}): readonly AgentModuleCandidate[] {
+ return input.registration.source.modules.map((module) => {
+ const sourceId = `${input.registration.source.id}:${module.logicalPath}`;
+ return Object.freeze({
+ backing: Object.freeze({
+ kind: "programmatic" as const,
+ moduleId: module.logicalPath,
+ registryId: input.registration.source.id,
+ revision: input.registration.source.revision,
+ semanticRevision: module.semanticRevision,
+ }),
+ exportName: module.exportName,
+ layer: input.layer,
+ logicalPath: module.logicalPath,
+ nodeId: input.nodeId,
+ owner: input.owner,
+ sourceId,
+ });
+ });
+}
+
+export function composeAgentModuleCandidates(
+ candidates: readonly AgentSourceCandidate[],
+): ComposedAgentModuleCandidates {
+ const candidatesBySlot = new Map<string, AgentSourceCandidate[]>();
+ const sourceIds = new Set<string>();
+
+ for (const candidate of candidates) {
+ if (sourceIds.has(candidate.sourceId)) {
+ throw new Error(
+ `Agent source id "${candidate.sourceId}" is declared more than once in node "${candidate.nodeId}".`,
+ );
+ }
+ sourceIds.add(candidate.sourceId);
+ const slot = canonicalSourceSlot(candidate.logicalPath);
+ const slotCandidates = candidatesBySlot.get(slot) ?? [];
+ slotCandidates.push(candidate);
+ candidatesBySlot.set(slot, slotCandidates);
+ }
+
+ const selected = new Map<string, AgentSourceCandidate>();
+ const entries: AgentSourceCompositionEntry[] = [];
+
+ for (const [slot, slotCandidates] of [...candidatesBySlot].sort(([left], [right]) =>
+ left.localeCompare(right),
+ )) {
+ const seenLayers = new Set<AgentSourceLayer>();
+ for (const candidate of slotCandidates) {
+ if (seenLayers.has(candidate.layer)) {
+ throw new Error(
+ `Agent source slot "${slot}" has more than one ${candidate.layer} candidate.`,
+ );
+ }
+ seenLayers.add(candidate.layer);
+ }
+
+ const ordered = [...slotCandidates].sort(
+ (left, right) => LAYER_PRECEDENCE[right.layer] - LAYER_PRECEDENCE[left.layer],
+ );
+ const winner = ordered[0]!;
+ selected.set(slot, winner);
+
+ for (const loser of ordered.slice(1)) {
+ entries.push({
+ kind: "shadowed",
+ source: describeAgentSourceCandidate(loser),
+ winnerSourceId: winner.sourceId,
+ });
+ }
+ }
+
+ return {
+ composition: { entries: Object.freeze(entries) },
+ selected,
+ };
+}
+
+export function disableComposedCandidate(input: {
+ readonly candidate: AgentSourceCandidate;
+ readonly composed: ComposedAgentModuleCandidates;
+}): ComposedAgentModuleCandidates {
+ const slot = canonicalSourceSlot(input.candidate.logicalPath);
+ const selected = new Map(input.composed.selected);
+ if (selected.get(slot)?.sourceId !== input.candidate.sourceId) {
+ throw new Error(`Only the selected source for "${slot}" can disable that slot.`);
+ }
+ const replaced = input.composed.composition.entries.some(
+ (entry) => entry.kind === "shadowed" && entry.winnerSourceId === input.candidate.sourceId,
+ );
+ if (!replaced) {
+ throw new Error(
+ `Source "${input.candidate.logicalPath}" disables a slot with no lower-precedence source.`,
+ );
+ }
+ selected.delete(slot);
+ return {
+ composition: {
+ entries: Object.freeze([
+ ...input.composed.composition.entries,
+ { kind: "disabled" as const, source: describeAgentSourceCandidate(input.candidate) },
+ ]),
+ },
+ selected,
+ };
+}
+
+export function createCompiledModuleBinding(
+ candidate: AgentModuleCandidate,
+): CompiledModuleBinding {
+ return Object.freeze({
+ backing: candidate.backing,
+ logicalPath: candidate.logicalPath,
+ owner: candidate.owner,
+ });
+}
+
+export async function loadProgrammaticModuleNamespace(input: {
+ readonly backing: Extract<AgentModuleBacking, { readonly kind: "programmatic" }>;
+ readonly registries: readonly AgentSourceRegistry[];
+}): Promise<ProgrammaticModuleNamespace> {
+ const matchingSources = input.registries
+ .map((registry) => registry.sources.get(input.backing.registryId))
+ .filter((source): source is ProgrammaticAgentSource => source !== undefined);
+ if (matchingSources.length !== 1) {
+ throw new Error(
+ `Expected exactly one registered programmatic source "${input.backing.registryId}", found ${matchingSources.length}.`,
+ );
+ }
+ const source = matchingSources[0]!;
+ if (source.revision !== input.backing.revision) {
+ throw new Error(
+ `Programmatic source "${source.id}" revision mismatch: artifact requires "${input.backing.revision}", registry provides "${source.revision}".`,
+ );
+ }
+ const module = source.modules.find(
+ (candidate) => candidate.logicalPath === input.backing.moduleId,
+ );
+ if (module === undefined) {
+ throw new Error(
+ `Programmatic source "${source.id}" does not register module "${input.backing.moduleId}".`,
+ );
+ }
+ if (module.semanticRevision !== input.backing.semanticRevision) {
+ throw new Error(
+ `Programmatic module "${source.id}:${module.logicalPath}" semantic revision does not match the compiled binding.`,
+ );
+ }
+ const namespace = await module.loadNamespace();
+ if (namespace === null || typeof namespace !== "object") {
+ throw new Error(
+ `Programmatic module "${source.id}:${module.logicalPath}" loader must return a module namespace object.`,
+ );
+ }
+ return namespace;
+}
+
+export function canonicalModuleSlot(logicalPath: string): string {
+ validateProgrammaticLogicalPath(logicalPath);
+ return canonicalSourceSlot(logicalPath);
+}
+
+/**
+ * Canonical composition slot for one logical path. Module extensions, folder
+ * forms, and skill packages collapse onto the same authored primitive identity.
+ */
+export function canonicalSourceSlot(logicalPath: string): string {
+ const normalized = normalizeLogicalPath(logicalPath);
+ if (
+ normalized.length === 0 ||
+ normalized === "." ||
+ normalized.startsWith("../") ||
+ normalized.includes("/../") ||
+ posix.normalize(normalized) !== normalized
+ ) {
+ throw new Error(`Agent source logical path "${logicalPath}" is invalid.`);
+ }
+
+ const withoutExtension = stripLogicalPathExtension(normalized);
+
+ const connectionFolderMatch = withoutExtension.match(/^connections\/([^/]+)\/connection$/);
+ if (connectionFolderMatch !== null) return `connections/${connectionFolderMatch[1]!}`;
+
+ if (withoutExtension === "sandbox/sandbox") return "sandbox";
+
+ const skillPackageMatch = withoutExtension.match(/^skills\/([^/]+)\/SKILL$/);
+ if (skillPackageMatch !== null) return `skills/${skillPackageMatch[1]!}`;
+
+ return withoutExtension;
+}
+
+export function validateProgrammaticLogicalPath(input: string): string {
+ if (input.length === 0 || isAbsolute(input) || input.includes("\\")) {
+ throw new Error(`Programmatic module logical path "${input}" must be a relative POSIX path.`);
+ }
+ const logicalPath = normalizeLogicalPath(input);
+ if (
+ logicalPath === "." ||
+ logicalPath.startsWith("../") ||
+ logicalPath.includes("/../") ||
+ posix.normalize(logicalPath) !== logicalPath
+ ) {
+ throw new Error(`Programmatic module logical path "${input}" may not traverse directories.`);
+ }
+ const segments = logicalPath.split("/");
+ const fileName = segments.at(-1)!;
+ if (getSupportedModuleBaseName(fileName) === null) {
+ throw new Error(
+ `Programmatic module logical path "${input}" must use a supported JavaScript or TypeScript extension.`,
+ );
+ }
+ const root = segments[0];
+ const extensionless = stripLogicalPathExtension(logicalPath);
+ const supported =
+ (segments.length === 1 && ["agent", "sandbox", "instrumentation"].includes(extensionless)) ||
+ (root === "sandbox" &&
+ segments.length === 2 &&
+ getSupportedModuleBaseName(fileName) === "sandbox") ||
+ (["channels", "connections", "hooks", "instructions", "schedules", "skills", "tools"].includes(
+ root!,
+ ) &&
+ segments.length >= 2);
+ if (!supported) {
+ throw new Error(
+ `Programmatic module logical path "${input}" does not select an eve module slot.`,
+ );
+ }
+ return logicalPath;
+}
+
+export function describeAgentSourceCandidate(
+ candidate: AgentSourceCandidate,
+): AgentSourceDescriptor {
+ return Object.freeze({
+ backing: candidate.backing,
+ layer: candidate.layer,
+ logicalPath: candidate.logicalPath,
+ owner: candidate.owner,
+ sourceId: candidate.sourceId,
+ });
+}
+
+function expectNonEmpty(value: string, label: string): string {
+ if (value.trim().length === 0) throw new Error(`${label} must be non-empty.`);
+ return value;
+}
diff --git a/packages/eve/src/compiler/validate-artifact.ts b/packages/eve/src/compiler/validate-artifact.ts
new file mode 100644
index 000000000..9bfd434a0
--- /dev/null
+++ b/packages/eve/src/compiler/validate-artifact.ts
@@ -0,0 +1,404 @@
+import type {
+ CompiledAgentManifest,
+ CompiledAgentNodeManifest,
+ CompiledAgentResources,
+ CompiledChannelDefinition,
+ CompiledSubagentNode,
+} from "#compiler/manifest.js";
+import { ROOT_COMPILED_AGENT_NODE_ID } from "#compiler/manifest.js";
+import type { CompiledModuleBinding } from "#compiler/source-graph.js";
+import type { CompiledModuleMap } from "#compiler/module-map.js";
+import { collectModuleBindingsForManifest } from "#compiler/module-map.js";
+import { HOST_HTTP_INVENTORY } from "#framework/host-inventory.js";
+
+type CompiledNode = CompiledAgentNodeManifest | CompiledAgentResources;
+
+/** Validates invariants that cannot be expressed by the serialized Zod shape. */
+export function validateCompiledAgentManifest(manifest: CompiledAgentManifest): void {
+ const nodes = new Map<string, CompiledNode>([[ROOT_COMPILED_AGENT_NODE_ID, manifest]]);
+ for (const subagent of manifest.subagents) {
+ if (nodes.has(subagent.nodeId)) {
+ fail(`subagent node id "${subagent.nodeId}" is duplicated`);
+ }
+ nodes.set(subagent.nodeId, subagent.agent);
+ validateSubagentRecord(subagent);
+ }
+ validateSubagentTree(manifest, nodes);
+
+ validateCompiledAgentResources(manifest, {
+ activeResourceSourceIds: manifest.subagents
+ .filter((node) => node.parentNodeId === ROOT_COMPILED_AGENT_NODE_ID)
+ .map((node) => node.sourceId),
+ });
+ for (const subagent of manifest.subagents) {
+ validateCompiledAgentResources(subagent.agent, {
+ additionalModuleSources:
+ subagent.configResolver === undefined ? [] : [subagent.configResolver],
+ activeResourceSourceIds: manifest.subagents
+ .filter((node) => node.parentNodeId === subagent.nodeId)
+ .map((node) => node.sourceId),
+ });
+ }
+
+ for (const [nodeId, node] of nodes) {
+ validateUniqueIdentities(
+ [
+ ...node.tools.map((tool) => ({ identity: tool.name, kind: "tool" })),
+ ...node.remoteAgents.map((agent) => ({ identity: agent.name, kind: "remote agent" })),
+ ...manifest.subagents
+ .filter((agent) => agent.parentNodeId === nodeId)
+ .map((agent) => ({ identity: agent.name, kind: "local agent" })),
+ ],
+ "tool and subagent public name",
+ );
+ }
+}
+
+function validateSubagentTree(
+ manifest: CompiledAgentManifest,
+ nodes: ReadonlyMap<string, CompiledNode>,
+): void {
+ const parentByNodeId = new Map(
+ manifest.subagents.map((subagent) => [subagent.nodeId, subagent.parentNodeId]),
+ );
+ for (const subagent of manifest.subagents) {
+ if (!nodes.has(subagent.parentNodeId)) {
+ fail(`subagent node "${subagent.nodeId}" has missing parent "${subagent.parentNodeId}"`);
+ }
+ const lineage = new Set<string>();
+ let nodeId = subagent.nodeId;
+ while (nodeId !== ROOT_COMPILED_AGENT_NODE_ID) {
+ if (lineage.has(nodeId)) {
+ fail(`subagent graph contains a cycle at node "${nodeId}"`);
+ }
+ lineage.add(nodeId);
+ const parentNodeId = parentByNodeId.get(nodeId);
+ if (parentNodeId === undefined) {
+ fail(`subagent node "${subagent.nodeId}" is not reachable from the root`);
+ }
+ nodeId = parentNodeId;
+ }
+ }
+}
+
+/** Validates exact module-map parity with the manifest's required binding tables. */
+export function validateCompiledModuleMap(
+ manifest: CompiledAgentManifest,
+ moduleMap: CompiledModuleMap,
+): void {
+ const expected = new Map<string, Set<string>>([
+ [
+ "__root__",
+ new Set(collectModuleBindingsForManifest(manifest).map((binding) => binding.sourceId)),
+ ],
+ ...manifest.subagents.map(
+ (subagent) =>
+ [
+ subagent.nodeId,
+ new Set(
+ collectModuleBindingsForManifest(subagent.agent).map((binding) => binding.sourceId),
+ ),
+ ] as const,
+ ),
+ ]);
+ const actualNodeIds = Object.keys(moduleMap.nodes);
+ if (
+ actualNodeIds.length !== expected.size ||
+ actualNodeIds.some((nodeId) => !expected.has(nodeId))
+ ) {
+ fail("compiled module map node set does not match the manifest");
+ }
+ for (const [nodeId, sourceIds] of expected) {
+ const actual = moduleMap.nodes[nodeId];
+ if (actual === undefined) fail(`compiled module map node "${nodeId}" is missing`);
+ const actualSourceIds = Object.keys(actual.modules);
+ if (
+ actualSourceIds.length !== sourceIds.size ||
+ actualSourceIds.some((sourceId) => !sourceIds.has(sourceId))
+ ) {
+ fail(`compiled module map sources for node "${nodeId}" do not match its bindings`);
+ }
+ }
+}
+
+/** Validates one node's bindings, composition, and route-plan integrity. */
+export function validateCompiledAgentResources(
+ node: CompiledNode,
+ options: {
+ readonly additionalModuleSources?: readonly {
+ readonly logicalPath: string;
+ readonly sourceId: string;
+ }[];
+ readonly activeResourceSourceIds?: readonly string[];
+ readonly allowUnknownResourceWinners?: boolean;
+ } = {},
+): void {
+ validateUniqueIdentities(
+ node.tools.map((entry) => ({ identity: entry.name, kind: "tool" })),
+ "tool name",
+ );
+ validateUniqueIdentities(
+ node.dynamicTools.map((entry) => ({ identity: entry.slug, kind: "dynamic tool" })),
+ "dynamic tool slug",
+ );
+ validateUniqueIdentities(
+ node.skills.map((entry) => ({ identity: entry.name, kind: "skill" })),
+ "skill name",
+ );
+ validateUniqueIdentities(
+ node.dynamicSkills.map((entry) => ({ identity: entry.slug, kind: "dynamic skill" })),
+ "dynamic skill slug",
+ );
+ validateUniqueIdentities(
+ node.instructions.map((entry) => ({ identity: entry.name, kind: "instructions" })),
+ "instructions name",
+ );
+ validateUniqueIdentities(
+ node.dynamicInstructions.map((entry) => ({
+ identity: entry.slug,
+ kind: "dynamic instructions",
+ })),
+ "dynamic instructions slug",
+ );
+ validateUniqueIdentities(
+ node.connections.map((entry) => ({ identity: entry.connectionName, kind: "connection" })),
+ "connection name",
+ );
+ validateUniqueIdentities(
+ node.hooks.map((entry) => ({ identity: entry.slug, kind: "hook" })),
+ "hook slug",
+ );
+ validateUniqueIdentities(
+ node.schedules.map((entry) => ({ identity: entry.name, kind: "schedule" })),
+ "schedule name",
+ );
+ const referencedModuleSources = collectReferencedModuleSources(node);
+ for (const source of options.additionalModuleSources ?? []) {
+ referencedModuleSources.set(source.sourceId, { logicalPath: source.logicalPath });
+ }
+ for (const [sourceId, reference] of referencedModuleSources) {
+ const binding = node.bindings[sourceId];
+ if (binding === undefined) fail(`module source "${sourceId}" has no compiled binding`);
+ validateBinding(sourceId, reference.logicalPath, binding);
+ }
+ for (const sourceId of Object.keys(node.bindings)) {
+ if (!referencedModuleSources.has(sourceId)) {
+ fail(`compiled binding "${sourceId}" is not referenced by its node manifest`);
+ }
+ }
+
+ const activeSourceIds = new Set([
+ ...referencedModuleSources.keys(),
+ ...collectActiveResourceSourceIds(node),
+ ...node.remoteAgents.map((remote) => remote.sourceId),
+ ...(options.activeResourceSourceIds ?? []),
+ ]);
+ const disabledSourceIds = new Set<string>();
+ for (const entry of node.sourceComposition.entries) {
+ if (entry.kind === "disabled") {
+ if (disabledSourceIds.has(entry.source.sourceId)) {
+ fail(`disabled composition source "${entry.source.sourceId}" is duplicated`);
+ }
+ disabledSourceIds.add(entry.source.sourceId);
+ if (node.bindings[entry.source.sourceId] !== undefined) {
+ fail(`disabled source "${entry.source.sourceId}" retains an active binding`);
+ }
+ continue;
+ }
+ if (
+ !activeSourceIds.has(entry.winnerSourceId) &&
+ !disabledSourceIds.has(entry.winnerSourceId) &&
+ !node.sourceComposition.entries.some(
+ (candidate) =>
+ candidate.kind === "disabled" && candidate.source.sourceId === entry.winnerSourceId,
+ ) &&
+ options.allowUnknownResourceWinners !== true
+ ) {
+ fail(
+ `shadowed source "${entry.source.sourceId}" has dangling winner "${entry.winnerSourceId}"`,
+ );
+ }
+ }
+ validateChannelRoutePlan(node);
+ for (const remote of node.remoteAgents) {
+ validateBinding(remote.sourceId, remote.logicalPath, remote.binding);
+ if (remote.parentNodeId.length === 0) fail(`remote agent "${remote.sourceId}" has no parent`);
+ }
+}
+
+function validateSubagentRecord(subagent: CompiledSubagentNode): void {
+ if (subagent.backing.kind !== "resource" || subagent.backing.sourcePath.length === 0) {
+ fail(`subagent "${subagent.nodeId}" has no physical resource backing`);
+ }
+ if (subagent.parentNodeId.length === 0) fail(`subagent "${subagent.nodeId}" has no parent`);
+ if (subagent.configResolver !== undefined) {
+ const binding = subagent.agent.bindings[subagent.configResolver.sourceId];
+ if (binding === undefined) {
+ fail(`dynamic subagent "${subagent.nodeId}" config resolver has no binding`);
+ }
+ validateBinding(subagent.configResolver.sourceId, subagent.configResolver.logicalPath, binding);
+ }
+}
+
+function validateBinding(
+ sourceId: string,
+ logicalPath: string,
+ binding: CompiledModuleBinding,
+): void {
+ if (binding.logicalPath !== logicalPath) {
+ fail(`compiled binding "${sourceId}" targets "${binding.logicalPath}", not "${logicalPath}"`);
+ }
+ if (
+ binding.owner.kind === "extension" &&
+ binding.backing.kind === "filesystem" &&
+ binding.backing.extensionScope === undefined
+ ) {
+ fail(`extension-owned filesystem binding "${sourceId}" has no extension scope`);
+ }
+}
+
+function collectReferencedModuleSources(
+ node: CompiledNode,
+): Map<string, { readonly logicalPath: string }> {
+ const sources = new Map<string, { readonly logicalPath: string }>();
+ const add = (source: { readonly sourceId: string; readonly logicalPath: string }) => {
+ const existing = sources.get(source.sourceId);
+ if (existing !== undefined && existing.logicalPath !== source.logicalPath) {
+ fail(`module source "${source.sourceId}" is referenced with two logical paths`);
+ }
+ sources.set(source.sourceId, { logicalPath: source.logicalPath });
+ };
+ if ("config" in node) {
+ add(node.config.source);
+ if (node.config.model?.source !== undefined) add(node.config.model.source);
+ if (node.config.dynamicModel !== undefined) add(node.config.dynamicModel);
+ }
+ for (const route of node.channelRoutes.effective) add(route);
+ for (const route of node.channelRoutes.shadowed) {
+ if (route.source.backing.kind !== "resource") add(route.source);
+ }
+ for (const value of node.connections) add(value);
+ for (const value of node.tools) add(value);
+ for (const value of node.dynamicInstructions) add(value);
+ for (const value of node.dynamicSkills) add(value);
+ for (const value of node.dynamicTools) add(value);
+ for (const value of node.hooks) add(value);
+ for (const value of node.instructions) if (value.sourceKind === "module") add(value);
+ if (node.instrumentation !== undefined) add(node.instrumentation);
+ if (node.workflowTool !== undefined) add(node.workflowTool);
+ for (const value of node.skills) if (value.sourceKind === "module") add(value);
+ for (const value of node.schedules) if (value.sourceKind === "module") add(value);
+ add(node.sandbox);
+ for (const mount of node.extensionMounts) {
+ add({ logicalPath: mount.mountLogicalPath, sourceId: mount.mountSourceId });
+ }
+ return sources;
+}
+
+function collectActiveResourceSourceIds(node: CompiledNode): string[] {
+ return [
+ ...node.instructions
+ .filter((value) => value.sourceKind !== "module")
+ .map((value) => value.sourceId),
+ ...node.skills.filter((value) => value.sourceKind !== "module").map((value) => value.sourceId),
+ ...node.schedules
+ .filter((value) => value.sourceKind !== "module")
+ .map((value) => value.sourceId),
+ ...node.sandboxWorkspaces.map((value) => value.sourceId),
+ ];
+}
+
+function validateChannelRoutePlan(node: CompiledNode): void {
+ const effectiveKeys = new Set<string>();
+ const effectiveSourceIds = new Set<string>();
+ for (const route of node.channelRoutes.effective) {
+ const key = routeIdentity(route);
+ if (effectiveKeys.has(key)) fail(`effective channel route "${key}" is duplicated`);
+ effectiveKeys.add(key);
+ effectiveSourceIds.add(route.sourceId);
+ if (node.bindings[route.sourceId] === undefined) {
+ fail(`effective channel route source "${route.sourceId}" has no binding`);
+ }
+ const reserved = HOST_HTTP_INVENTORY.find(
+ (host) =>
+ methodsOverlap(route.method, host.method) && patternsOverlap(route.urlPath, host.path),
+ );
+ if (reserved !== undefined) {
+ fail(`effective route ${route.method} ${route.urlPath} overlaps reserved host route`);
+ }
+ }
+ for (const route of node.channelRoutes.shadowed) {
+ if (!effectiveSourceIds.has(route.winnerSourceId)) {
+ fail(`shadowed channel route has dangling winner "${route.winnerSourceId}"`);
+ }
+ }
+ const preflightKeys = new Set<string>();
+ for (const preflight of node.channelRoutes.preflight) {
+ const key = normalizePattern(preflight.urlPath);
+ if (preflightKeys.has(key)) fail(`generated preflight "${key}" is duplicated`);
+ preflightKeys.add(key);
+ if (preflight.sourceIds.length === 0) fail(`generated preflight "${key}" has no causes`);
+ for (const sourceId of preflight.sourceIds) {
+ const cause = node.channelRoutes.effective.find(
+ (route) =>
+ route.sourceId === sourceId &&
+ route.cors !== undefined &&
+ route.method !== "WEBSOCKET" &&
+ patternsOverlap(route.urlPath, preflight.urlPath),
+ );
+ if (cause === undefined) fail(`generated preflight "${key}" has invalid cause "${sourceId}"`);
+ }
+ }
+}
+
+function routeIdentity(route: CompiledChannelDefinition): string {
+ return `${route.method} ${normalizePattern(route.urlPath)}`;
+}
+
+function normalizePattern(path: string): string {
+ return splitPath(path)
+ .map((segment) => (isParameter(segment) ? ":" : segment))
+ .join("/");
+}
+
+function patternsOverlap(left: string, right: string): boolean {
+ const leftParts = splitPath(left);
+ const rightParts = splitPath(right);
+ return (
+ leftParts.length === rightParts.length &&
+ leftParts.every(
+ (part, index) =>
+ part === rightParts[index] || isParameter(part) || isParameter(rightParts[index]!),
+ )
+ );
+}
+
+function splitPath(path: string): string[] {
+ return path.replace(/^\/+|\/+$/g, "").split("/");
+}
+
+function isParameter(segment: string): boolean {
+ return segment.startsWith(":") || /^\[[^\]]+\]$/.test(segment);
+}
+
+function methodsOverlap(left: string, right: string): boolean {
+ return left === "ALL" || right === "ALL" || left === right;
+}
+
+function validateUniqueIdentities(
+ entries: readonly { readonly identity: string; readonly kind: string }[],
+ label: string,
+): void {
+ const seen = new Map<string, string>();
+ for (const entry of entries) {
+ const existing = seen.get(entry.identity);
+ if (existing !== undefined) {
+ fail(`${label} "${entry.identity}" is shared by ${existing} and ${entry.kind}`);
+ }
+ seen.set(entry.identity, entry.kind);
+ }
+}
+
+function fail(message: string): never {
+ throw new Error(`Invalid compiled eve artifact: ${message}.`);
+}
diff --git a/packages/eve/src/compiler/workspace-resources.ts b/packages/eve/src/compiler/workspace-resources.ts
index 5244f8821..8a6cd9849 100644
--- a/packages/eve/src/compiler/workspace-resources.ts
+++ b/packages/eve/src/compiler/workspace-resources.ts
@@ -65,7 +65,6 @@ export async function materializeWorkspaceResources(input: {
...rootAgent,
kind: input.manifest.kind,
extensionMounts: input.manifest.extensionMounts,
- subagentEdges: input.manifest.subagentEdges,
subagents,
version: input.manifest.version,
};
diff --git a/packages/eve/src/context/accessors.integration.test.ts b/packages/eve/src/context/accessors.integration.test.ts
index 518a64f8d..4c2cf9233 100644
--- a/packages/eve/src/context/accessors.integration.test.ts
+++ b/packages/eve/src/context/accessors.integration.test.ts
@@ -22,7 +22,7 @@ describe("buildCallbackContext – session", () => {
});
it("returns the active session identity across async boundaries", async () => {
- const runtime = createTestRuntime();
+ const runtime = await createTestRuntime();
const session = await runtime.runAsSession(
{
@@ -50,7 +50,7 @@ describe("buildCallbackContext – session", () => {
});
it("preserves parent lineage on the public session", async () => {
- const runtime = createTestRuntime();
+ const runtime = await createTestRuntime();
const session = await runtime.runAsSession(
{
@@ -88,7 +88,7 @@ describe("buildCallbackContext – getSandbox", () => {
"echo ready": { exitCode: 0, stderr: "", stdout: "ready" },
},
});
- const runtime = createTestRuntime();
+ const runtime = await createTestRuntime();
const live = (await runtime.runAsSession({ sandbox }, async () => {
await Promise.resolve();
@@ -106,7 +106,7 @@ describe("buildCallbackContext – getSandbox", () => {
id: "sbx_public_sandbox_file",
initialFiles: { "note.txt": "file content" },
});
- const runtime = createTestRuntime();
+ const runtime = await createTestRuntime();
const live = (await runtime.runAsSession(
{ sandbox },
@@ -130,7 +130,7 @@ describe("buildCallbackContext – getSandbox", () => {
stops += 1;
},
});
- const runtime = createTestRuntime();
+ const runtime = await createTestRuntime();
await runtime.runAsSession({ sandbox }, async () => {
const live: RuntimeSandboxSession = await buildCallbackContext().getSandbox();
@@ -147,7 +147,7 @@ describe("buildCallbackContext – getSkill", () => {
});
it("throws when authored runtime execution does not include skill access", async () => {
- const runtime = createTestRuntime();
+ const runtime = await createTestRuntime();
await expect(
runtime.runAsSession({}, () => buildCallbackContext().getSkill("semantic-model")),
@@ -168,7 +168,7 @@ describe("buildCallbackContext – getSkill", () => {
"/workspace/skills/semantic-model/references/catalog.yml": "entities: []\n",
},
});
- const runtime = createTestRuntime({ skills: [skill.source] });
+ const runtime = await createTestRuntime({ skills: [skill.source] });
const result = await runtime.runAsSession({ sandbox }, async () => {
await Promise.resolve();
diff --git a/packages/eve/src/context/build-base-tool-context.integration.test.ts b/packages/eve/src/context/build-base-tool-context.integration.test.ts
index e4fb95dec..757e4753d 100644
--- a/packages/eve/src/context/build-base-tool-context.integration.test.ts
+++ b/packages/eve/src/context/build-base-tool-context.integration.test.ts
@@ -13,7 +13,7 @@ describe("buildBaseToolContext – getSandbox abort binding", () => {
return { exitCode: 0, stderr: "", stdout: "" };
},
});
- const runtime = createTestRuntime();
+ const runtime = await createTestRuntime();
const controller = new AbortController();
await runtime.runAsSession({ sandbox }, async () => {
@@ -41,7 +41,7 @@ describe("buildBaseToolContext – getSandbox abort binding", () => {
return { exitCode: 0, stderr: "", stdout: "" };
},
});
- const runtime = createTestRuntime();
+ const runtime = await createTestRuntime();
await runtime.runAsSession({ sandbox }, async () => {
const ctx = buildBaseToolContext({
diff --git a/packages/eve/src/context/build-callback-context.ts b/packages/eve/src/context/build-callback-context.ts
index 463e5ca4a..ffe97cb4b 100644
--- a/packages/eve/src/context/build-callback-context.ts
+++ b/packages/eve/src/context/build-callback-context.ts
@@ -1,5 +1,5 @@
import type { SessionContext } from "#public/definitions/callback-context.js";
-import type { SkillHandle } from "#execution/skills/types.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";
import { loadContext } from "#context/container.js";
diff --git a/packages/eve/src/context/dynamic-tool-lifecycle.test.ts b/packages/eve/src/context/dynamic-tool-lifecycle.test.ts
index c8cbac0a9..410ac84f0 100644
--- a/packages/eve/src/context/dynamic-tool-lifecycle.test.ts
+++ b/packages/eve/src/context/dynamic-tool-lifecycle.test.ts
@@ -1026,22 +1026,22 @@ describe("dispatchDynamicToolEvent", () => {
});
// ---------------------------------------------------------------------------
-// Framework dynamic tools — no bundler transform, auto-registered
+// Programmatic dynamic tools — no bundler transform, auto-registered
// ---------------------------------------------------------------------------
-function createFrameworkTool(
+function createProgrammaticTool(
description = "framework stub",
executeFn: (input: Record<string, unknown>) => unknown = () => ({ ok: true }),
): DynamicToolEntry {
return createReplayableTool(description, executeFn);
}
-describe("framework dynamic tools (no bundler transform)", () => {
- it("session-scoped framework tool is replayable across steps", async () => {
+describe("programmatic dynamic tools (no bundler transform)", () => {
+ it("session-scoped programmatic tool is replayable across steps", async () => {
const ctx = createCtx();
- const executeFn = vi.fn(() => ({ data: "from-framework" }));
+ const executeFn = vi.fn(() => ({ data: "from-programmatic" }));
const resolver = createResolver("fwk", ["session.started"], () => ({
- search: createFrameworkTool("framework search", executeFn),
+ search: createProgrammaticTool("programmatic search", executeFn),
}));
await dispatchDynamicToolEvent({
@@ -1070,11 +1070,11 @@ describe("framework dynamic tools (no bundler transform)", () => {
expect(executeFn).toHaveBeenCalledWith({ query: "test" });
});
- it("turn-scoped framework tool is replayable", async () => {
+ it("turn-scoped programmatic tool is replayable", async () => {
const ctx = createCtx();
const executeFn = vi.fn(() => ({ result: "turn-tool" }));
const resolver = createResolver("helper", ["turn.started"], () => ({
- assist: createFrameworkTool("turn helper", executeFn),
+ assist: createProgrammaticTool("turn helper", executeFn),
}));
await dispatchDynamicToolEvent({
@@ -1100,7 +1100,7 @@ describe("framework dynamic tools (no bundler transform)", () => {
it("framework and authored tools coexist in session scope", async () => {
const ctx = createCtx();
const frameworkResolver = createResolver("fwk", ["session.started"], () => ({
- search: createFrameworkTool("framework search"),
+ search: createProgrammaticTool("programmatic search"),
}));
const authoredResolver = createResolver("authored", ["session.started"], () => ({
query: createReplayableTool("authored query"),
@@ -1121,10 +1121,10 @@ describe("framework dynamic tools (no bundler transform)", () => {
expect(tools.map((t) => t.name).sort()).toEqual(["query", "search"]);
});
- it("single-entry framework tool uses slug as name", async () => {
+ it("single-entry programmatic tool uses slug as name", async () => {
const ctx = createCtx();
const resolver = createResolver("analytics", ["session.started"], () =>
- createFrameworkTool("single tool"),
+ createProgrammaticTool("single tool"),
);
await dispatchDynamicToolEvent({
@@ -1343,7 +1343,7 @@ describe("framework dynamic tools (no bundler transform)", () => {
it("leaves approval undefined when a step-scoped entry omits it", async () => {
const ctx = createCtx();
const resolver = createResolver("connection", ["step.started"], () => ({
- safe: createFrameworkTool("read-only op"),
+ safe: createProgrammaticTool("read-only op"),
}));
await dispatchDynamicToolEvent({
@@ -1365,7 +1365,7 @@ describe("framework dynamic tools (no bundler transform)", () => {
callCount++;
const current = callCount;
return {
- count: createFrameworkTool(`v${current}`, () => ({ version: current })),
+ count: createProgrammaticTool(`v${current}`, () => ({ version: current })),
};
});
diff --git a/packages/eve/src/context/providers/connection-key.ts b/packages/eve/src/context/providers/connection-key.ts
index 1a429399c..d265b51b3 100644
--- a/packages/eve/src/context/providers/connection-key.ts
+++ b/packages/eve/src/context/providers/connection-key.ts
@@ -1,5 +1,5 @@
import { ContextKey } from "#context/key.js";
-import type { ConnectionRegistry } from "#runtime/connections/types.js";
+import type { ConnectionRegistry } from "#runtime/connections/registry-types.js";
/**
* Context key for the per-session connection registry.
diff --git a/packages/eve/src/context/providers/connection.ts b/packages/eve/src/context/providers/connection.ts
index 9d1883a09..a27ae3a6c 100644
--- a/packages/eve/src/context/providers/connection.ts
+++ b/packages/eve/src/context/providers/connection.ts
@@ -1,6 +1,6 @@
import { ConnectionRegistryKey } from "#context/providers/connection-key.js";
import { ConnectionRegistryImpl } from "#runtime/connections/registry.js";
-import type { ConnectionRegistry } from "#runtime/connections/types.js";
+import type { ConnectionRegistry } from "#runtime/connections/registry-types.js";
import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";
import { getActiveRuntimeNode } from "#context/node.js";
import type { FrameworkContextProvider } from "#context/provider.js";
diff --git a/packages/eve/src/discover/agent.integration.test.ts b/packages/eve/src/discover/agent.integration.test.ts
index b333a3488..349cb6199 100644
--- a/packages/eve/src/discover/agent.integration.test.ts
+++ b/packages/eve/src/discover/agent.integration.test.ts
@@ -7,6 +7,8 @@ import {
EXTENSION_CAPABILITY_SUPPORT,
EXTENSION_CAPABILITY_VERSIONS,
} from "#compiler/extension-compatibility.js";
+import { projectAgentSources } from "#compiler/project-sources.js";
+import { composeAgentModuleCandidates } from "#compiler/source-graph.js";
import { discoverAgent } from "#discover/discover-agent.js";
import {
DISCOVER_EXTENSION_CAPABILITY_INCOMPATIBLE,
@@ -14,7 +16,6 @@ import {
DISCOVER_EXTENSION_MOUNT_AMBIGUOUS,
DISCOVER_EXTENSION_MOUNT_MISSING_DECLARATION,
DISCOVER_EXTENSION_NESTED_MOUNT_UNSUPPORTED,
- DISCOVER_EXTENSION_OVERRIDE_OUTSIDE_MOUNT,
} from "#discover/extensions.js";
import {
DISCOVER_DEPRECATED_SYSTEM_SLOT,
@@ -533,6 +534,29 @@ describe("discoverAgent (memory)", () => {
expect(result.diagnostics).toEqual([]);
});
+ it("discovers single-file instrumentation as a module source", async () => {
+ const project = buildMemoryAgentProject({
+ agentFiles: {
+ "instrumentation.mjs":
+ 'throw new Error("instrumentation modules should not execute during discovery");\n',
+ "instructions.md": "You are a precise assistant.",
+ },
+ });
+
+ const result = await discoverAgent({
+ agentRoot: project.agentRoot,
+ appRoot: project.appRoot,
+ source: project.source,
+ });
+
+ expect(result.diagnostics).toEqual([]);
+ expect(result.manifest.instrumentation).toEqual({
+ logicalPath: "instrumentation.mjs",
+ sourceId: "instrumentation.mjs",
+ sourceKind: "module",
+ });
+ });
+
it("rejects authored tool filenames that violate the tool-name charset", async () => {
const project = buildMemoryAgentProject({
agentFiles: {
@@ -976,7 +1000,7 @@ describe("discoverAgent (memory)", () => {
expect(result.manifest.resolvedExtensions).toEqual([]);
});
- it("rejects agent-root contributions that override a mounted extension's namespace", async () => {
+ it("allows agent-root contributions to override a mounted extension's qualified slots", async () => {
const project = buildMemoryAgentProject({
appFiles: {
"node_modules/@acme/crm/package.json": JSON.stringify({
@@ -984,12 +1008,17 @@ describe("discoverAgent (memory)", () => {
eve: { extension: { source: "source", dist: "extension" } },
}),
"node_modules/@acme/crm/extension/_manifest.json": EXTENSION_COMPATIBILITY_MANIFEST,
+ "node_modules/@acme/crm/extension/skills/foo/SKILL.md": [
+ "---",
+ "description: Use CRM context.",
+ "---",
+ "Load CRM context before replying.",
+ ].join("\n"),
"node_modules/@acme/crm/extension/tools/search.ts": "export default {};\n",
},
agentFiles: {
"extensions/crm.ts": 'export { default } from "@acme/crm";\n',
- // A root tool using the mounted `crm__` prefix would shadow the
- // extension from outside its mount directory.
+ "skills/crm__foo.ts": "export default {};\n",
"tools/crm__search.ts": "export default {};\n",
"subagents/crm__reviewer.ts": "export default {};\n",
"instructions.md": "You are a precise assistant.",
@@ -1002,11 +1031,49 @@ describe("discoverAgent (memory)", () => {
source: project.source,
});
- const collisions = result.diagnostics.filter(
- (diagnostic) => diagnostic.code === DISCOVER_EXTENSION_OVERRIDE_OUTSIDE_MOUNT,
+ expect(result.diagnostics).toEqual([]);
+ expect(result.manifest.tools).toContainEqual(
+ expect.objectContaining({ logicalPath: "tools/crm__search.ts" }),
+ );
+ expect(result.manifest.subagents).toContainEqual(
+ expect.objectContaining({ logicalPath: "subagents/crm__reviewer.ts" }),
+ );
+ const projected = projectAgentSources({
+ externalDependencies: [],
+ manifest: result.manifest,
+ nodeId: "root",
+ });
+ const composed = composeAgentModuleCandidates(projected.candidates);
+ expect(composed.selected.get("tools/crm__search")).toMatchObject({
+ layer: "application",
+ owner: { kind: "application" },
+ sourceId: "tools/crm__search.ts",
+ });
+ expect(composed.selected.get("skills/crm__foo")).toMatchObject({
+ layer: "application",
+ owner: { kind: "application" },
+ sourceId: "skills/crm__foo.ts",
+ });
+ expect(composed.composition.entries).toContainEqual(
+ expect.objectContaining({
+ kind: "shadowed",
+ source: expect.objectContaining({
+ layer: "extension-package",
+ logicalPath: "tools/crm__search.ts",
+ }),
+ winnerSourceId: "tools/crm__search.ts",
+ }),
+ );
+ expect(composed.composition.entries).toContainEqual(
+ expect.objectContaining({
+ kind: "shadowed",
+ source: expect.objectContaining({
+ layer: "extension-package",
+ logicalPath: "skills/crm__foo/SKILL.md",
+ }),
+ winnerSourceId: "skills/crm__foo.ts",
+ }),
);
- expect(collisions).toHaveLength(2);
- expect(collisions[0]?.message).toContain("extensions/crm/");
});
it("rejects a mounted extension that requires an unsupported capability version", async () => {
@@ -1176,11 +1243,7 @@ describe("discoverAgent (memory)", () => {
source: project.source,
});
- expect(
- result.diagnostics.some(
- (diagnostic) => diagnostic.code === DISCOVER_EXTENSION_OVERRIDE_OUTSIDE_MOUNT,
- ),
- ).toBe(false);
+ expect(result.diagnostics).toEqual([]);
});
it("rejects an extension distribution without generated compatibility metadata", async () => {
diff --git a/packages/eve/src/discover/discover-agent.ts b/packages/eve/src/discover/discover-agent.ts
index e401f2c7b..8b77d3fda 100644
--- a/packages/eve/src/discover/discover-agent.ts
+++ b/packages/eve/src/discover/discover-agent.ts
@@ -8,16 +8,11 @@ import {
DISCOVER_EXTENSION_MOUNT_AMBIGUOUS,
DISCOVER_EXTENSION_MOUNT_MISSING_DECLARATION,
DISCOVER_EXTENSION_NESTED_MOUNT_UNSUPPORTED,
- DISCOVER_EXTENSION_OVERRIDE_OUTSIDE_MOUNT,
DISCOVER_EXTENSION_SANDBOX_UNSUPPORTED,
locateExtensionMount,
mountNamespace,
} from "#discover/extensions.js";
-import {
- classifyAgentRootEntry,
- normalizeLogicalPath,
- SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS,
-} from "#discover/filesystem.js";
+import { classifyAgentRootEntry, normalizeLogicalPath } from "#discover/filesystem.js";
import {
createChannelNameDiagnostic,
createExtensionNameDiagnostic,
@@ -121,6 +116,13 @@ export async function discoverAgent(input: DiscoverAgentInput): Promise<Discover
});
diagnostics.push(...configModuleResult.diagnostics);
+ const instrumentationModuleResult = discoverFlatModuleSource({
+ rootEntries,
+ rootPath: agentRoot,
+ slotName: "instrumentation",
+ });
+ diagnostics.push(...instrumentationModuleResult.diagnostics);
+
const channelsResult = await discoverNamedSourceDirectory({
directoryName: "channels",
invalidDirectoryCode: DISCOVER_CHANNELS_DIRECTORY_INVALID,
@@ -240,23 +242,6 @@ export async function discoverAgent(input: DiscoverAgentInput): Promise<Discover
});
diagnostics.push(...mountCollection.diagnostics);
- // Overrides must be co-located in the mount directory. An agent-root
- // contribution using a mounted extension's `<ns>__` composed-name prefix would
- // shadow that extension from outside its mount directory, so reject it.
- diagnostics.push(
- ...detectRootNamespaceCollisions({
- agentRoot,
- namespaces: mountCollection.mounts.map((descriptor) => descriptor.namespace),
- sources: [
- ...toolsResult.sources,
- ...connectionsResult.connections,
- ...skillsResult.skills,
- ...schedulesResult.schedules,
- ...subagentsResult.subagents,
- ],
- }),
- );
-
let resolvedExtensions: readonly ResolvedExtensionMount[] = [];
if (role !== "agent") {
// Extensions cannot mount other extensions yet. Fail loudly instead of
@@ -306,6 +291,9 @@ export async function discoverAgent(input: DiscoverAgentInput): Promise<Discover
if (configModuleResult.module !== undefined) {
manifestInput.configModule = configModuleResult.module;
}
+ if (instrumentationModuleResult.module !== undefined) {
+ manifestInput.instrumentation = instrumentationModuleResult.module;
+ }
const manifest = createAgentSourceManifest(manifestInput);
@@ -526,54 +514,6 @@ async function collectExtensionMounts(input: {
return { diagnostics, mounts };
}
-/**
- * Flags agent-root contributions whose composed name uses a mounted extension's
- * `<ns>__` prefix. That prefix is reserved for the extension and its co-located
- * overrides, so a root-level `<ns>__…` file would override the extension from
- * outside its mount directory — rejected here.
- */
-export function detectRootNamespaceCollisions(input: {
- readonly agentRoot: string;
- readonly namespaces: readonly string[];
- readonly sources: ReadonlyArray<{ readonly logicalPath: string }>;
-}): DiscoverDiagnostic[] {
- if (input.namespaces.length === 0) {
- return [];
- }
-
- const diagnostics: DiscoverDiagnostic[] = [];
- for (const source of input.sources) {
- const name = rootContributionName(source.logicalPath);
- const namespace = input.namespaces.find((candidate) => name.startsWith(`${candidate}__`));
- if (namespace !== undefined) {
- diagnostics.push(
- createDiscoverErrorDiagnostic({
- code: DISCOVER_EXTENSION_OVERRIDE_OUTSIDE_MOUNT,
- message: `"${source.logicalPath}" uses the "${namespace}__" prefix reserved for the mounted extension "${namespace}". Override an extension's contributions inside its mount directory ("extensions/${namespace}/…"), not at the agent root.`,
- sourcePath: join(input.agentRoot, source.logicalPath),
- }),
- );
- }
- }
- return diagnostics;
-}
-
-/**
- * Derives a contribution's composed name from its slot-relative logical path:
- * the first path segment below the slot directory, minus any module extension
- * (`tools/crm__x.ts` → `crm__x`; `skills/crm__x/SKILL.md` → `crm__x`).
- */
-function rootContributionName(logicalPath: string): string {
- const afterSlot = logicalPath.slice(logicalPath.indexOf("/") + 1);
- const firstSegment = afterSlot.split("/")[0] ?? afterSlot;
- for (const extension of SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS) {
- if (firstSegment.toLowerCase().endsWith(extension)) {
- return firstSegment.slice(0, firstSegment.length - extension.length);
- }
- }
- return firstSegment;
-}
-
/**
* Reads the `name` field from the app root's package.json through `source`
* and strips the npm scope prefix when present (e.g. `"@org/my-agent"` →
diff --git a/packages/eve/src/discover/discover-subagent.ts b/packages/eve/src/discover/discover-subagent.ts
index c6def21d0..4a1e2fb98 100644
--- a/packages/eve/src/discover/discover-subagent.ts
+++ b/packages/eve/src/discover/discover-subagent.ts
@@ -2,7 +2,6 @@ import { join, relative, resolve } from "node:path";
import { discoverConnectionSources } from "#discover/connections.js";
import { createDiscoverErrorDiagnostic, type DiscoverDiagnostic } from "#discover/diagnostics.js";
import {
- detectRootNamespaceCollisions,
discoverExtensionMountDeclarations,
resolveExtensionMounts,
} from "#discover/discover-agent.js";
@@ -290,19 +289,6 @@ async function discoverLocalSubagentPackage(input: {
source: input.source,
});
diagnostics.push(...extensionsResult.diagnostics);
- diagnostics.push(
- ...detectRootNamespaceCollisions({
- agentRoot: input.subagentRoot,
- namespaces: extensionsResult.mounts.map((mount) => mount.namespace),
- sources: [
- ...toolsResult.sources,
- ...connectionsResult.connections,
- ...skillsResult.skills,
- ...subagentsResult.subagents,
- ],
- }),
- );
-
const resolvedExtensions = await resolveExtensionMounts({
agentRoot: input.subagentRoot,
appRoot: input.appRoot,
diff --git a/packages/eve/src/discover/extensions.ts b/packages/eve/src/discover/extensions.ts
index 1abce481c..6f69f4af2 100644
--- a/packages/eve/src/discover/extensions.ts
+++ b/packages/eve/src/discover/extensions.ts
@@ -38,14 +38,6 @@ export const DISCOVER_EXTENSION_MOUNT_MISSING_DECLARATION =
export const DISCOVER_EXTENSION_NESTED_MOUNT_UNSUPPORTED =
"discover/extension-nested-mount-unsupported";
-/**
- * Emitted when a consumer's agent-root contribution (e.g. `agent/tools/crm__x.ts`)
- * uses a mounted extension's `<ns>__` prefix. That prefix is reserved for the
- * extension and its co-located overrides, not the agent root.
- */
-export const DISCOVER_EXTENSION_OVERRIDE_OUTSIDE_MOUNT =
- "discover/extension-override-outside-mount";
-
/**
* Emitted when a resolved package is not a valid eve extension.
*/
diff --git a/packages/eve/src/discover/manifest.ts b/packages/eve/src/discover/manifest.ts
index 95f102ef6..dfef9a8fc 100644
--- a/packages/eve/src/discover/manifest.ts
+++ b/packages/eve/src/discover/manifest.ts
@@ -20,7 +20,7 @@ export const AGENT_SOURCE_MANIFEST_KIND = "eve-agent-discovery-manifest";
/**
* Current manifest schema version.
*/
-export const AGENT_SOURCE_MANIFEST_VERSION = 13;
+export const AGENT_SOURCE_MANIFEST_VERSION = 14;
/**
* Channel source reference preserved by the discovery manifest.
@@ -215,6 +215,8 @@ export interface AgentSourceManifest {
* Empty when no instructions are authored.
*/
instructions: InstructionsSourceRef[];
+ /** Authored single-file instrumentation module, when present. */
+ instrumentation?: ModuleSourceRef;
/**
* Authored sandbox module discovered for this agent, or `null` when
* the agent does not declare one. Every agent owns at most one
@@ -257,6 +259,7 @@ export interface CreateAgentSourceManifestInput {
*/
packageName?: string;
instructions?: readonly InstructionsSourceRef[];
+ instrumentation?: ModuleSourceRef;
sandbox?: SandboxSourceRef | null;
sandboxWorkspaces?: readonly SandboxWorkspaceFolderSourceRef[];
schedules?: readonly ScheduleSourceRef[];
@@ -338,6 +341,9 @@ export function createAgentSourceManifest(
if (input.configModule !== undefined) {
manifest.configModule = input.configModule;
}
+ if (input.instrumentation !== undefined) {
+ manifest.instrumentation = input.instrumentation;
+ }
return manifest;
}
diff --git a/packages/eve/src/discover/subagent.integration.test.ts b/packages/eve/src/discover/subagent.integration.test.ts
index e0366bf40..232445e98 100644
--- a/packages/eve/src/discover/subagent.integration.test.ts
+++ b/packages/eve/src/discover/subagent.integration.test.ts
@@ -92,7 +92,7 @@ describe("discoverSubagents (memory)", () => {
sourceId: "tools/search.js",
},
],
- version: 13,
+ version: 14,
},
rootPath: researcherRoot,
sourceId: "subagents/researcher",
@@ -138,7 +138,7 @@ describe("discoverSubagents (memory)", () => {
logicalPath: "agent.js",
sourceId: "agent.js",
},
- version: 13,
+ version: 14,
},
rootPath: reviewerRoot,
sourceId: "subagents/reviewer",
diff --git a/packages/eve/src/evals/index.ts b/packages/eve/src/evals/index.ts
index 8efc0096c..9fd291549 100644
--- a/packages/eve/src/evals/index.ts
+++ b/packages/eve/src/evals/index.ts
@@ -12,7 +12,7 @@ export { mockModel } from "#evals/mock-model.js";
// ---------------------------------------------------------------------------
export type { RuntimeIdentity, RuntimeTraceContext } from "#protocol/message.js";
-export type { InputRequest } from "#runtime/input/types.js";
+export type { InputRequest } from "#shared/input.js";
export type { CancelSessionResult } from "#client/types.js";
export type {
diff --git a/packages/eve/src/evals/match.ts b/packages/eve/src/evals/match.ts
index e7a63547a..4ef3381f9 100644
--- a/packages/eve/src/evals/match.ts
+++ b/packages/eve/src/evals/match.ts
@@ -1,5 +1,5 @@
import type { MessageStreamEvent } from "#protocol/message.js";
-import type { InputRequest } from "#runtime/input/types.js";
+import type { InputRequest } from "#shared/input.js";
import type { JsonObject, JsonValue } from "#shared/json.js";
import type { EveEvalSubagentCall, EveEvalToolCall } from "#evals/types.js";
diff --git a/packages/eve/src/evals/runner/derive-run-facts.ts b/packages/eve/src/evals/runner/derive-run-facts.ts
index 20578a54d..741e64385 100644
--- a/packages/eve/src/evals/runner/derive-run-facts.ts
+++ b/packages/eve/src/evals/runner/derive-run-facts.ts
@@ -1,6 +1,6 @@
import type { MessageStreamEvent } from "#protocol/message.js";
import { LOAD_SKILL_TOOL_NAME } from "#runtime/skills/fragment-context.js";
-import type { InputRequest } from "#runtime/input/types.js";
+import type { InputRequest } from "#shared/input.js";
import type { JsonObject, JsonValue } from "#shared/json.js";
import type { EveEvalDerivedFacts, EveEvalSubagentCall, EveEvalToolCall } from "#evals/types.js";
diff --git a/packages/eve/src/evals/session.ts b/packages/eve/src/evals/session.ts
index 67a6fccbe..dd7acb8dc 100644
--- a/packages/eve/src/evals/session.ts
+++ b/packages/eve/src/evals/session.ts
@@ -19,7 +19,7 @@ import type {
import { isCurrentTurnBoundaryEvent, isTurnFailureEvent } from "#protocol/message.js";
import { summarizeTurnEvents } from "#client/session-utils.js";
import { extractCompletedResult } from "#client/output-schema.js";
-import type { InputRequest, InputResponse } from "#runtime/input/types.js";
+import type { InputRequest, InputResponse } from "#shared/input.js";
import { deriveRunFacts } from "#evals/runner/derive-run-facts.js";
import { AssertionCollector } from "#evals/assertions/collector.js";
import { createOutputAssertions, createScopedAssertions } from "#evals/assertions/scoped.js";
diff --git a/packages/eve/src/evals/target.test.ts b/packages/eve/src/evals/target.test.ts
index 75c5be238..c65f7227e 100644
--- a/packages/eve/src/evals/target.test.ts
+++ b/packages/eve/src/evals/target.test.ts
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { Client } from "#client/client.js";
import { resolveEvalTargetHandle } from "#evals/target.js";
+import { createTestAgentInfoResult } from "#internal/testing/agent-info-fixture.js";
afterEach(() => {
vi.restoreAllMocks();
@@ -119,35 +120,5 @@ function fetchUrl(request: string | URL | Request): string {
}
function infoPayload(input: { readonly name: string }) {
- return {
- agent: {
- agentRoot: "/tmp/app/agent",
- appRoot: "/tmp/app",
- model: { id: "mock", routing: { kind: "gateway", target: "mock" } },
- name: input.name,
- },
- capabilities: { devRoutes: true },
- channels: { authored: [], available: [], disabledFramework: [], framework: [] },
- connections: [],
- diagnostics: { discoveryErrors: 0, discoveryWarnings: 0 },
- hooks: [],
- instructions: { dynamic: [], static: [] },
- kind: "eve-agent-info",
- mode: "development",
- sandbox: null,
- schedules: [],
- skills: { dynamic: [], static: [] },
- subagents: { local: [], total: 0 },
- tools: {
- authored: [],
- available: [],
- disabledFramework: [],
- dynamic: [],
- framework: [],
- reserved: [],
- },
- version: 2,
- workflow: { enabled: true, toolName: "workflow" },
- workspace: { resourceRoot: null, rootEntries: [] },
- };
+ return createTestAgentInfoResult({ name: input.name });
}
diff --git a/packages/eve/src/evals/target.ts b/packages/eve/src/evals/target.ts
index 624b125c5..bd42eca01 100644
--- a/packages/eve/src/evals/target.ts
+++ b/packages/eve/src/evals/target.ts
@@ -189,7 +189,7 @@ async function waitForTargetHealth(client: Client, url: string): Promise<void> {
}
function assertAgentInfoShape(info: AgentInfoResult, url: string): void {
- if (info.kind !== "eve-agent-info" || info.version !== 2) {
+ if (info.kind !== "eve-agent-info" || info.version !== 3) {
throw new Error(`Eval target ${url} returned an unrecognized /eve/v1/info payload.`);
}
}
diff --git a/packages/eve/src/evals/types.ts b/packages/eve/src/evals/types.ts
index 36e9dd9da..f3518e8fc 100644
--- a/packages/eve/src/evals/types.ts
+++ b/packages/eve/src/evals/types.ts
@@ -12,7 +12,7 @@ import type {
SendTurnInput,
SendTurnOptions,
} from "#client/types.js";
-import type { InputRequest, InputResponse } from "#runtime/input/types.js";
+import type { InputRequest, InputResponse } from "#shared/input.js";
import type { JsonObject, JsonValue } from "#shared/json.js";
import type { AgentModelOptionsDefinition } from "#shared/agent-definition.js";
import type { EvalReporter } from "#evals/runner/reporters/types.js";
diff --git a/packages/eve/src/eve-channel/index.ts b/packages/eve/src/eve-channel/index.ts
new file mode 100644
index 000000000..33bb58d64
--- /dev/null
+++ b/packages/eve/src/eve-channel/index.ts
@@ -0,0 +1,560 @@
+import type { SessionAuthContext } from "#channel/types.js";
+import type { Session } from "#channel/session.js";
+import { resolveForwardedPrincipal } from "#channel/forwarded-principal.js";
+import { isRuntimeSessionOwnershipConflictError } from "#execution/runtime-errors.js";
+import {
+ handleConnectionCallbackRequest,
+ handleLegacyConnectionCallbackRequest,
+} from "#execution/connections/callback-route.js";
+import { handleSessionCallbackRequest } from "#execution/session-callback-route.js";
+import { handleTaskInputResponseRequest } from "#execution/task-input-response-route.js";
+import { createLogger, logError } from "#internal/logging.js";
+import {
+ readAgentInfoRouteResponse,
+ readRemoteAgentStreamHeadersResolver,
+ readRouteSessionCreator,
+} from "#internal/nitro/routes/channel-route-context.js";
+import {
+ EVE_SESSION_ID_HEADER,
+ EVE_STREAM_FORMAT_HEADER,
+ EVE_STREAM_TAIL_INDEX_HEADER,
+ EVE_STREAM_VERSION_HEADER,
+ type SubagentCalledStreamEvent,
+} from "#protocol/message.js";
+import {
+ EVE_CALLBACK_ROUTE_PATTERN,
+ EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,
+ EVE_HEALTH_ROUTE_PATH,
+ EVE_INFO_ROUTE_PATH,
+ EVE_LEGACY_CONNECTION_CALLBACK_ROUTE_PATTERN,
+ EVE_SESSION_ROUTE_PATH,
+ EVE_SESSION_CANCEL_ROUTE_PATTERN,
+ EVE_SESSION_CLEAR_ROUTE_PATTERN,
+ EVE_SESSION_COMPACT_ROUTE_PATTERN,
+ EVE_SESSION_ROUTE_PATTERN,
+ EVE_SESSION_RESET_ROUTE_PATTERN,
+ EVE_SESSION_STREAM_ROUTE_PATTERN,
+ EVE_SUBAGENT_STREAM_ROUTE_PATTERN,
+ EVE_TASK_INPUT_ROUTE_PATTERN,
+ createEveSessionStreamRoutePath,
+ createEveSubagentStreamRoutePath,
+} from "#protocol/routes.js";
+import type { CancelTurnResponse } from "#protocol/cancel-turn.js";
+import type { ClearResponse } from "#protocol/clear-session.js";
+import type { CompactResponse } from "#protocol/compact-session.js";
+import type { ResetResponse } from "#protocol/reset-session.js";
+import { parseTraceparent } from "#protocol/traceparent.js";
+import { routeAuth } from "#public/channels/auth.js";
+import { mergeUploadPolicy } from "#public/channels/upload-policy.js";
+import { defineChannel, GET, HEAD, POST } from "#public/definitions/channel.js";
+import {
+ checkUploadPolicy,
+ createSessionStreamResponse,
+ deriveOperationContinuationToken,
+ mergeContext,
+ parseCancelTurnBody,
+ parseCreateBody,
+ parseIncludeTailIndex,
+ parseJsonRequest,
+ parseResetBody,
+ parseSessionControlBody,
+ parseSessionMessageBody,
+ parseStartIndex,
+ rejectSessionContinuationToken,
+ requireSessionId,
+} from "#eve-channel/request.js";
+import {
+ findRemoteSubagentBinding,
+ healthResponse,
+ normalizeEveCors,
+ resolveOnMessage,
+} from "#eve-channel/support.js";
+import type { EveChannel, EveChannelInput, EveEventContext } from "#eve-channel/types.js";
+
+export * from "#eve-channel/types.js";
+
+const log = createLogger("eve.channel");
+
+/**
+ * Builds the default eve HTTP channel: a {@link defineChannel} instance serving the
+ * built-in `/eve/v1` routes (GET inspects the agent, POST creates a session,
+ * ID-addressed POST routes deliver follow-ups and controls, and GET streams a
+ * session's NDJSON event feed). Every route
+ * runs {@link EveChannelInput.auth} via {@link routeAuth} before dispatching.
+ * Default-export the result as your `agent/channels/eve.ts` channel; reach for
+ * {@link defineChannel} directly only for a custom transport.
+ */
+export function eveChannel(input: EveChannelInput): EveChannel {
+ const uploadPolicy = mergeUploadPolicy(input.uploadPolicy);
+
+ return defineChannel<undefined, EveEventContext>({
+ cors: normalizeEveCors(input.cors),
+ turnPolicy: input.turnPolicy,
+ routes: [
+ GET(EVE_HEALTH_ROUTE_PATH, async () => healthResponse()),
+ HEAD(EVE_HEALTH_ROUTE_PATH, async () => healthResponse()),
+
+ GET(EVE_INFO_ROUTE_PATH, async (req, args) => {
+ const authResult = await routeAuth(req, input.auth);
+ if (authResult instanceof Response) return authResult;
+
+ const respond = readAgentInfoRouteResponse(args);
+ if (respond === undefined) {
+ return Response.json(
+ { error: "Agent info route requires internal channel dispatch context.", ok: false },
+ { status: 500 },
+ );
+ }
+
+ return await respond();
+ }),
+
+ GET(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN, handleConnectionCallbackRequest),
+ POST(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN, handleConnectionCallbackRequest),
+ GET(EVE_LEGACY_CONNECTION_CALLBACK_ROUTE_PATTERN, handleLegacyConnectionCallbackRequest),
+ POST(EVE_LEGACY_CONNECTION_CALLBACK_ROUTE_PATTERN, handleLegacyConnectionCallbackRequest),
+ POST(EVE_CALLBACK_ROUTE_PATTERN, handleSessionCallbackRequest),
+ POST(EVE_TASK_INPUT_ROUTE_PATTERN, handleTaskInputResponseRequest),
+
+ POST(EVE_SESSION_ROUTE_PATH, async (req, args) => {
+ const authResult = await routeAuth(req, input.auth);
+ if (authResult instanceof Response) return authResult;
+
+ const payload = await parseJsonRequest(req);
+ if (payload instanceof Response) return payload;
+ const tokenRejection = rejectSessionContinuationToken(payload);
+ if (tokenRejection !== null) return tokenRejection;
+
+ const forwarded = await resolveForwardedPrincipal({
+ trustedForwarders: input.trustedForwarders,
+ forwarder: authResult,
+ payload,
+ });
+ if (forwarded instanceof Response) return forwarded;
+
+ const body = parseCreateBody(payload);
+ if (body instanceof Response) return body;
+ // Top-level sessions own their trace. Callback sessions are delegated
+ // remote agents and intentionally continue the dispatching agent trace.
+ const parentTraceContext =
+ body.callback === undefined
+ ? undefined
+ : parseTraceparent(req.headers.get("traceparent"));
+
+ const policyRejection = checkUploadPolicy(body, uploadPolicy);
+ if (policyRejection !== null) return policyRejection;
+
+ if (body.operationId !== undefined && forwarded.auth.principalType === "anonymous") {
+ return Response.json(
+ { error: "operationId requires an authenticated principal.", ok: false },
+ { status: 400 },
+ );
+ }
+ const operationToken =
+ body.operationId === undefined
+ ? undefined
+ : await deriveOperationContinuationToken({
+ auth: forwarded.auth,
+ operationId: body.operationId,
+ });
+ if (operationToken !== undefined) {
+ const owner = await args.resolveSession(operationToken);
+ if (owner !== undefined) {
+ return Response.json(
+ { ok: true, sessionId: owner.id, status: "accepted" },
+ {
+ headers: {
+ "cache-control": "no-store",
+ [EVE_SESSION_ID_HEADER]: owner.id,
+ },
+ status: 202,
+ },
+ );
+ }
+ }
+
+ const messageResult = await resolveOnMessage({
+ auth: forwarded.auth,
+ config: input,
+ message: body.message,
+ request: req,
+ });
+ if (messageResult instanceof Response) return messageResult;
+ const createSession = readRouteSessionCreator(args);
+ if (createSession === undefined) {
+ return Response.json(
+ { error: "Session creation requires internal channel dispatch context.", ok: false },
+ { status: 500 },
+ );
+ }
+
+ let handle: Awaited<ReturnType<typeof createSession>>;
+ try {
+ handle = await createSession({
+ auth: messageResult.auth,
+ capabilities:
+ body.capabilities ?? (body.mode === "task" ? undefined : { requestInput: true }),
+ callback: body.callback,
+ continuationToken: operationToken,
+ initiatorAuth: forwarded.accepted ? forwarded.initiatorAuth : undefined,
+ input: {
+ message: body.message,
+ context: mergeContext(body.context, messageResult.context),
+ outputSchema: body.outputSchema,
+ },
+ mode: body.mode ?? "conversation",
+ parentTraceContext,
+ title: messageResult.title,
+ });
+ } catch (error) {
+ // A concurrent create-once request won the token: adopt its session
+ // without delivering this duplicate input.
+ if (operationToken !== undefined && isRuntimeSessionOwnershipConflictError(error)) {
+ return Response.json(
+ { ok: true, sessionId: error.ownerSessionId, status: "accepted" },
+ {
+ headers: {
+ "cache-control": "no-store",
+ [EVE_SESSION_ID_HEADER]: error.ownerSessionId,
+ },
+ status: 202,
+ },
+ );
+ }
+ const errorId = logError(log, "session-create request failed", error);
+ return Response.json(
+ { error: "Failed to create the session.", errorId, ok: false },
+ { status: 500 },
+ );
+ }
+
+ return Response.json(
+ { ok: true, sessionId: handle.sessionId, status: "accepted" },
+ {
+ headers: {
+ "cache-control": "no-store",
+ [EVE_SESSION_ID_HEADER]: handle.sessionId,
+ },
+ status: 202,
+ },
+ );
+ }),
+
+ POST(EVE_SESSION_ROUTE_PATTERN, async (req, { attachSession, params }) => {
+ const authResult = await routeAuth(req, input.auth);
+ if (authResult instanceof Response) return authResult;
+
+ const sessionId = requireSessionId(params);
+ if (sessionId instanceof Response) return sessionId;
+ const payload = await parseJsonRequest(req);
+ if (payload instanceof Response) return payload;
+ const forwarded = await resolveForwardedPrincipal({
+ trustedForwarders: input.trustedForwarders,
+ forwarder: authResult,
+ payload,
+ });
+ if (forwarded instanceof Response) return forwarded;
+ const body = parseSessionMessageBody(payload);
+ if (body instanceof Response) return body;
+
+ const policyRejection = checkUploadPolicy(body, uploadPolicy);
+ if (policyRejection !== null) return policyRejection;
+
+ let context = body.context;
+ let dispatchAuth: SessionAuthContext | null = forwarded.auth;
+ if (body.message !== undefined) {
+ const messageResult = await resolveOnMessage({
+ auth: forwarded.auth,
+ config: input,
+ message: body.message,
+ request: req,
+ sessionId,
+ });
+ if (messageResult instanceof Response) return messageResult;
+ context = mergeContext(body.context, messageResult.context);
+ dispatchAuth = messageResult.auth;
+ }
+
+ let result: Awaited<ReturnType<Session["send"]>>;
+ try {
+ const session = attachSession(sessionId);
+ const options = {
+ auth: dispatchAuth,
+ callback: body.callback,
+ context,
+ outputSchema: body.outputSchema,
+ turnPolicy: body.turnPolicy,
+ };
+ result =
+ body.inputResponses === undefined
+ ? await session.send(body.message!, options)
+ : await session.respond(body.inputResponses, options);
+ } catch (error) {
+ const errorId = logError(log, "session-message request failed", error, { sessionId });
+ return Response.json(
+ { error: "Failed to send the session message.", errorId, ok: false },
+ { status: 500 },
+ );
+ }
+ if (result.status === "session_not_active") {
+ return Response.json(
+ {
+ code: "session_not_active",
+ error: "The session is no longer active.",
+ ok: false,
+ },
+ { headers: { "cache-control": "no-store" }, status: 409 },
+ );
+ }
+
+ return Response.json(
+ { ok: true, sessionId: result.sessionId, status: "accepted" },
+ {
+ headers: {
+ "cache-control": "no-store",
+ [EVE_SESSION_ID_HEADER]: result.sessionId,
+ },
+ status: 202,
+ },
+ );
+ }),
+
+ POST(EVE_SESSION_CANCEL_ROUTE_PATTERN, async (req, { attachSession, params }) => {
+ const authResult = await routeAuth(req, input.auth);
+ if (authResult instanceof Response) return authResult;
+ const sessionId = requireSessionId(params);
+ if (sessionId instanceof Response) return sessionId;
+ const body = await parseCancelTurnBody(req);
+ if (body instanceof Response) return body;
+ let result: Awaited<ReturnType<Session["cancel"]>>;
+ try {
+ result = await attachSession(sessionId).cancel({
+ taskId: body.taskId,
+ turnId: body.turnId,
+ });
+ } catch (error) {
+ const errorId = logError(log, "cancel-turn request failed", error, { sessionId });
+ return Response.json(
+ { error: "Failed to cancel the turn.", errorId, ok: false },
+ { status: 500 },
+ );
+ }
+ return Response.json(
+ result.status === "accepted"
+ ? ({
+ ok: true,
+ sessionId: result.sessionId,
+ status: "accepted",
+ } satisfies CancelTurnResponse)
+ : ({ ok: true, status: "no_active_turn" } satisfies CancelTurnResponse),
+ {
+ headers: { "cache-control": "no-store" },
+ status: result.status === "accepted" ? 202 : 200,
+ },
+ );
+ }),
+
+ POST(EVE_SESSION_COMPACT_ROUTE_PATTERN, async (req, { attachSession, params }) => {
+ const authResult = await routeAuth(req, input.auth);
+ if (authResult instanceof Response) return authResult;
+ const sessionId = requireSessionId(params);
+ if (sessionId instanceof Response) return sessionId;
+ const body = await parseSessionControlBody(req);
+ if (body instanceof Response) return body;
+ let result: Awaited<ReturnType<Session["compact"]>>;
+ try {
+ result = await attachSession(sessionId).compact();
+ } catch (error) {
+ const errorId = logError(log, "session-compaction request failed", error, { sessionId });
+ return Response.json(
+ { error: "Failed to compact the session.", errorId, ok: false },
+ { status: 500 },
+ );
+ }
+ return Response.json(
+ result.status === "accepted"
+ ? ({
+ ok: true,
+ sessionId: result.sessionId,
+ status: "accepted",
+ } satisfies CompactResponse)
+ : ({ ok: true, status: "no_active_session" } satisfies CompactResponse),
+ {
+ headers: { "cache-control": "no-store" },
+ status: result.status === "accepted" ? 202 : 200,
+ },
+ );
+ }),
+
+ POST(EVE_SESSION_CLEAR_ROUTE_PATTERN, async (req, { attachSession, params }) => {
+ const authResult = await routeAuth(req, input.auth);
+ if (authResult instanceof Response) return authResult;
+ const sessionId = requireSessionId(params);
+ if (sessionId instanceof Response) return sessionId;
+ const body = await parseSessionControlBody(req);
+ if (body instanceof Response) return body;
+ let result: Awaited<ReturnType<Session["clear"]>>;
+ try {
+ result = await attachSession(sessionId).clear();
+ } catch (error) {
+ const errorId = logError(log, "session-clear request failed", error, { sessionId });
+ return Response.json(
+ { error: "Failed to clear the session context.", errorId, ok: false },
+ { status: 500 },
+ );
+ }
+ return Response.json(
+ result.status === "accepted"
+ ? ({
+ ok: true,
+ sessionId: result.sessionId,
+ status: "accepted",
+ } satisfies ClearResponse)
+ : ({ ok: true, status: "no_active_session" } satisfies ClearResponse),
+ {
+ headers: { "cache-control": "no-store" },
+ status: result.status === "accepted" ? 202 : 200,
+ },
+ );
+ }),
+
+ POST(EVE_SESSION_RESET_ROUTE_PATTERN, async (req, { attachSession, params }) => {
+ const authResult = await routeAuth(req, input.auth);
+ if (authResult instanceof Response) return authResult;
+ const sessionId = requireSessionId(params);
+ if (sessionId instanceof Response) return sessionId;
+ const body = await parseResetBody(req);
+ if (body instanceof Response) return body;
+ let result: Awaited<ReturnType<Session["reset"]>>;
+ try {
+ result = await attachSession(sessionId).reset({ reason: body.reason });
+ } catch (error) {
+ const errorId = logError(log, "session-reset request failed", error, { sessionId });
+ return Response.json(
+ { error: "Failed to reset the session.", errorId, ok: false },
+ { status: 500 },
+ );
+ }
+ return Response.json(
+ result.status === "reset"
+ ? ({
+ ok: true,
+ previousSessionId: result.previousSessionId,
+ status: "reset",
+ } satisfies ResetResponse)
+ : ({ ok: true, status: "no_active_session" } satisfies ResetResponse),
+ { headers: { "cache-control": "no-store" } },
+ );
+ }),
+
+ GET(EVE_SESSION_STREAM_ROUTE_PATTERN, async (req, { attachSession, params }) => {
+ const authResult = await routeAuth(req, input.auth);
+ if (authResult instanceof Response) return authResult;
+ const sessionId = requireSessionId(params);
+ if (sessionId instanceof Response) return sessionId;
+ return await createSessionStreamResponse(req, attachSession(sessionId));
+ }),
+
+ GET(EVE_SUBAGENT_STREAM_ROUTE_PATTERN, async (req, args) => {
+ const authResult = await routeAuth(req, input.auth);
+ if (authResult instanceof Response) return authResult;
+
+ const parentSessionId = args.params.parentSessionId;
+ const callId = args.params.callId;
+ const childSessionId = args.params.childSessionId;
+ if (!parentSessionId || !callId || !childSessionId) {
+ return Response.json(
+ { error: "Missing subagent stream coordinates.", ok: false },
+ { status: 400 },
+ );
+ }
+
+ const startIndex = parseStartIndex(req);
+ if (startIndex instanceof Response) return startIndex;
+ const includeTailIndex = parseIncludeTailIndex(req);
+
+ const childStreamPath = createEveSubagentStreamRoutePath({
+ callId,
+ childSessionId,
+ parentSessionId,
+ });
+ let binding: SubagentCalledStreamEvent;
+ try {
+ const parent = args.attachSession(parentSessionId);
+ const found = await findRemoteSubagentBinding({
+ callId,
+ childSessionId,
+ childStreamPath,
+ parentSessionId,
+ parent,
+ });
+ if (found === undefined) {
+ throw new Error("Remote subagent binding not found.");
+ }
+ binding = found;
+ } catch {
+ return Response.json({ error: "Subagent stream not found.", ok: false }, { status: 404 });
+ }
+
+ const resolveHeaders = readRemoteAgentStreamHeadersResolver(args);
+ if (resolveHeaders === undefined) {
+ return Response.json(
+ {
+ error: "Subagent stream proxy requires internal channel dispatch context.",
+ ok: false,
+ },
+ { status: 500 },
+ );
+ }
+
+ let headers: Record<string, string>;
+ try {
+ headers = await resolveHeaders({
+ name: binding.data.toolName,
+ resolverId: binding.data.remote!.resolverId,
+ url: binding.data.remote!.url,
+ });
+ } catch {
+ return Response.json({ error: "Subagent stream not found.", ok: false }, { status: 404 });
+ }
+
+ const upstreamUrl = new URL(
+ createEveSessionStreamRoutePath(childSessionId).replace(/^\/+/, ""),
+ `${binding.data.remote!.url.replace(/\/+$/, "")}/`,
+ );
+ if (startIndex !== undefined) {
+ upstreamUrl.searchParams.set("startIndex", String(startIndex));
+ }
+ if (includeTailIndex) {
+ upstreamUrl.searchParams.set("includeTailIndex", "1");
+ }
+
+ const upstream = await fetch(upstreamUrl, {
+ cache: "no-store",
+ headers,
+ redirect: "manual",
+ signal: req.signal,
+ });
+ const responseHeaders = new Headers();
+ for (const name of [
+ "cache-control",
+ "content-type",
+ "x-accel-buffering",
+ EVE_SESSION_ID_HEADER,
+ EVE_STREAM_FORMAT_HEADER,
+ EVE_STREAM_TAIL_INDEX_HEADER,
+ EVE_STREAM_VERSION_HEADER,
+ ]) {
+ const value = upstream.headers.get(name);
+ if (value !== null) responseHeaders.set(name, value);
+ }
+ return new Response(upstream.body, {
+ headers: responseHeaders,
+ status: upstream.status,
+ statusText: upstream.statusText,
+ });
+ }),
+ ],
+ events: input.events,
+ });
+}
diff --git a/packages/eve/src/eve-channel/request.ts b/packages/eve/src/eve-channel/request.ts
new file mode 100644
index 000000000..773044f75
--- /dev/null
+++ b/packages/eve/src/eve-channel/request.ts
@@ -0,0 +1,605 @@
+import type { FilePart, TextPart, UserContent } from "ai";
+
+import type {
+ SessionAuthContext,
+ SessionCallback,
+ SessionCapabilities,
+ TurnPolicy,
+} from "#channel/types.js";
+import type { Session } from "#channel/session.js";
+import { parseSessionCallback } from "#channel/session-callback.js";
+import { hasInternalRefScheme } from "#internal/attachments/url-refs.js";
+import {
+ EVE_MESSAGE_STREAM_CONTENT_TYPE,
+ EVE_MESSAGE_STREAM_FORMAT,
+ EVE_MESSAGE_STREAM_VERSION,
+ EVE_SESSION_ID_HEADER,
+ EVE_STREAM_FORMAT_HEADER,
+ EVE_STREAM_TAIL_INDEX_HEADER,
+ EVE_STREAM_VERSION_HEADER,
+} from "#protocol/message.js";
+import {
+ collectUploadPolicyViolations,
+ formatUploadPolicyViolation,
+ type UploadPolicy,
+} from "#public/channels/upload-policy.js";
+import { isInputResponse, type ValidatedInputResponse } from "#shared/input.js";
+import { parseJsonObject, type JsonObject } from "#shared/json.js";
+import type { RunMode } from "#shared/run-mode.js";
+
+interface ParsedCreateBody {
+ callback?: SessionCallback;
+ capabilities?: SessionCapabilities;
+ message: string | UserContent;
+ mode?: RunMode;
+ context?: readonly string[];
+ operationId?: string;
+ outputSchema?: JsonObject;
+}
+
+/** Replay-stable identity for one authenticated create operation. */
+export async function deriveOperationContinuationToken(input: {
+ readonly auth: SessionAuthContext;
+ readonly operationId: string;
+}): Promise<string> {
+ const identity = JSON.stringify([
+ "eve:create-session:v1",
+ input.auth.authenticator,
+ input.auth.issuer ?? null,
+ input.auth.principalType,
+ input.auth.principalId,
+ input.operationId,
+ ]);
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(identity));
+ const hex = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join(
+ "",
+ );
+ return `eve:op:${hex.slice(0, 32)}`;
+}
+
+export function parseCreateBody(payload: Record<string, unknown>): ParsedCreateBody | Response {
+ if (payload.inputResponses !== undefined) {
+ return Response.json(
+ { error: "'inputResponses' is only accepted for an existing session.", ok: false },
+ { status: 400 },
+ );
+ }
+ const message = parseMessageField(payload.message);
+ if (message instanceof Response) return message;
+
+ const context = parseClientContextField(payload.clientContext);
+ if (context instanceof Response) return context;
+
+ const callback = parseCallbackField(payload.callback);
+ if (callback instanceof Response) return callback;
+
+ const capabilities = parseCapabilitiesField(payload.capabilities);
+ if (capabilities instanceof Response) return capabilities;
+
+ const mode = parseModeField(payload.mode);
+ if (mode instanceof Response) return mode;
+
+ const outputSchema = parseOutputSchemaField(payload.outputSchema);
+ if (outputSchema instanceof Response) return outputSchema;
+
+ if (message === undefined) {
+ return Response.json(
+ { error: "Missing or empty 'message' field.", ok: false },
+ { status: 400 },
+ );
+ }
+
+ const rawOperationId = payload.operationId;
+ if (rawOperationId !== undefined && (typeof rawOperationId !== "string" || !rawOperationId)) {
+ return Response.json(
+ { error: "Expected 'operationId' to be a non-empty string.", ok: false },
+ { status: 400 },
+ );
+ }
+
+ const result: ParsedCreateBody = {
+ callback,
+ capabilities,
+ message,
+ mode,
+ context,
+ outputSchema,
+ };
+ if (typeof rawOperationId === "string") result.operationId = rawOperationId;
+ return result;
+}
+
+interface ParsedSessionMessageBody {
+ callback?: SessionCallback;
+ message?: string | UserContent;
+ inputResponses?: readonly ValidatedInputResponse[];
+ context?: readonly string[];
+ outputSchema?: JsonObject;
+ turnPolicy?: TurnPolicy;
+}
+
+export function parseSessionMessageBody(
+ payload: Record<string, unknown>,
+): ParsedSessionMessageBody | Response {
+ const tokenRejection = rejectSessionContinuationToken(payload);
+ if (tokenRejection !== null) return tokenRejection;
+
+ const message = parseMessageField(payload.message);
+ if (message instanceof Response) return message;
+ const callback = parseCallbackField(payload.callback);
+ if (callback instanceof Response) return callback;
+ const inputResponses = parseInputResponses(payload.inputResponses);
+ if (inputResponses instanceof Response) return inputResponses;
+ const context = parseClientContextField(payload.clientContext);
+ if (context instanceof Response) return context;
+ const outputSchema = parseOutputSchemaField(payload.outputSchema);
+ if (outputSchema instanceof Response) return outputSchema;
+ const turnPolicy = parseTurnPolicyField(payload.turnPolicy);
+ if (turnPolicy instanceof Response) return turnPolicy;
+
+ if (message === undefined && inputResponses === undefined) {
+ return Response.json(
+ {
+ error: "Expected a non-empty 'message' or a non-empty 'inputResponses' array.",
+ ok: false,
+ },
+ { status: 400 },
+ );
+ }
+
+ if (message !== undefined && inputResponses !== undefined) {
+ return Response.json(
+ { error: "'message' and 'inputResponses' are mutually exclusive.", ok: false },
+ { status: 400 },
+ );
+ }
+
+ return { callback, message, inputResponses, context, outputSchema, turnPolicy };
+}
+
+interface ParsedCancelTurnBody {
+ taskId?: string;
+ turnId?: string;
+}
+
+export async function parseCancelTurnBody(req: Request): Promise<ParsedCancelTurnBody | Response> {
+ const payload = await parseOptionalJsonRequest(req);
+ if (payload instanceof Response) return payload;
+ const tokenRejection = rejectSessionContinuationToken(payload);
+ if (tokenRejection !== null) return tokenRejection;
+
+ const turnId = payload.turnId;
+ const taskId = payload.taskId;
+ if (turnId !== undefined && (typeof turnId !== "string" || turnId.length === 0)) {
+ return Response.json(
+ { error: "Expected 'turnId' to be a non-empty string.", ok: false },
+ { status: 400 },
+ );
+ }
+ if (taskId !== undefined && (typeof taskId !== "string" || taskId.length === 0)) {
+ return Response.json(
+ { error: "Expected 'taskId' to be a non-empty string.", ok: false },
+ { status: 400 },
+ );
+ }
+ const result: ParsedCancelTurnBody = {};
+ if (typeof taskId === "string") result.taskId = taskId;
+ if (typeof turnId === "string") result.turnId = turnId;
+ return result;
+}
+
+export async function parseJsonRequest(req: Request): Promise<Record<string, unknown> | Response> {
+ let payload: unknown;
+ try {
+ payload = await req.json();
+ } catch {
+ return Response.json({ error: "Invalid JSON body.", ok: false }, { status: 400 });
+ }
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
+ return Response.json({ error: "Expected a JSON object.", ok: false }, { status: 400 });
+ }
+ return payload as Record<string, unknown>;
+}
+
+export async function parseResetBody(
+ req: Request,
+): Promise<{ readonly reason?: string } | Response> {
+ const payload = await parseOptionalJsonRequest(req);
+ if (payload instanceof Response) return payload;
+ const tokenRejection = rejectSessionContinuationToken(payload);
+ if (tokenRejection !== null) return tokenRejection;
+ const reason = payload.reason;
+ if (reason !== undefined && (typeof reason !== "string" || reason.length === 0)) {
+ return Response.json(
+ { error: "Expected 'reason' to be a non-empty string.", ok: false },
+ { status: 400 },
+ );
+ }
+ return reason === undefined ? {} : { reason };
+}
+
+export async function parseSessionControlBody(
+ req: Request,
+): Promise<Record<string, unknown> | Response> {
+ const payload = await parseOptionalJsonRequest(req);
+ if (payload instanceof Response) return payload;
+ return rejectSessionContinuationToken(payload) ?? payload;
+}
+
+async function parseOptionalJsonRequest(req: Request): Promise<Record<string, unknown> | Response> {
+ let text: string;
+ try {
+ text = await req.text();
+ } catch {
+ return Response.json({ error: "Unreadable request body.", ok: false }, { status: 400 });
+ }
+ if (text.trim().length === 0) return {};
+
+ let payload: unknown;
+ try {
+ payload = JSON.parse(text);
+ } catch {
+ return Response.json({ error: "Invalid JSON body.", ok: false }, { status: 400 });
+ }
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
+ return Response.json({ error: "Expected a JSON object.", ok: false }, { status: 400 });
+ }
+ return payload as Record<string, unknown>;
+}
+
+export function rejectSessionContinuationToken(payload: Record<string, unknown>): Response | null {
+ return "continuationToken" in payload
+ ? Response.json(
+ { error: "Session-ID routes do not accept 'continuationToken'.", ok: false },
+ { status: 400 },
+ )
+ : null;
+}
+
+export function requireSessionId(params: Readonly<Record<string, string>>): string | Response {
+ const sessionId = params.sessionId;
+ return sessionId || Response.json({ error: "Missing session id.", ok: false }, { status: 400 });
+}
+
+export async function createSessionStreamResponse(
+ request: Request,
+ session: Session,
+): Promise<Response> {
+ const startIndex = parseStartIndex(request);
+ if (startIndex instanceof Response) return startIndex;
+ const includeTailIndex = parseIncludeTailIndex(request);
+
+ try {
+ const tailIndex = includeTailIndex ? await session.getStreamTailIndex() : undefined;
+ const events = await session.getEventStream({ startIndex });
+ const headers = new Headers({
+ "cache-control": "no-store, no-transform",
+ "content-type": EVE_MESSAGE_STREAM_CONTENT_TYPE,
+ "x-accel-buffering": "no",
+ [EVE_SESSION_ID_HEADER]: session.id,
+ [EVE_STREAM_FORMAT_HEADER]: EVE_MESSAGE_STREAM_FORMAT,
+ [EVE_STREAM_VERSION_HEADER]: EVE_MESSAGE_STREAM_VERSION,
+ });
+ if (tailIndex !== undefined) {
+ headers.set(EVE_STREAM_TAIL_INDEX_HEADER, String(tailIndex));
+ }
+ return new Response(
+ serializeAsNdjson(events, request.signal, streamEventLimit(startIndex, tailIndex)),
+ { headers },
+ );
+ } catch {
+ return Response.json({ error: "Session not found.", ok: false }, { status: 404 });
+ }
+}
+
+function parseOutputSchemaField(value: unknown): JsonObject | Response | undefined {
+ if (value === undefined) return undefined;
+
+ try {
+ return parseJsonObject(value);
+ } catch {
+ return Response.json(
+ { error: "Expected 'outputSchema' to be a JSON-serializable object.", ok: false },
+ { status: 400 },
+ );
+ }
+}
+
+function parseCallbackField(value: unknown): SessionCallback | Response | undefined {
+ if (value === undefined) return undefined;
+ const parsed = parseSessionCallback(value);
+ if (parsed.ok) return parsed.callback;
+
+ return Response.json({ error: parsed.message, ok: false }, { status: 400 });
+}
+
+function parseCapabilitiesField(value: unknown): SessionCapabilities | Response | undefined {
+ if (value === undefined) return undefined;
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
+ return Response.json(
+ { error: "Expected 'capabilities' to be an object.", ok: false },
+ { status: 400 },
+ );
+ }
+
+ const keys = Object.keys(value);
+ const requestInput = Reflect.get(value, "requestInput");
+ if (
+ keys.some((key) => key !== "requestInput") ||
+ (requestInput !== undefined && typeof requestInput !== "boolean")
+ ) {
+ return Response.json(
+ { error: "Expected 'capabilities.requestInput' to be a boolean when provided.", ok: false },
+ { status: 400 },
+ );
+ }
+
+ return requestInput === undefined ? {} : { requestInput };
+}
+
+function parseModeField(value: unknown): RunMode | Response | undefined {
+ if (value === undefined) return undefined;
+ if (value === "conversation" || value === "task") return value;
+ return Response.json(
+ { error: "Expected 'mode' to be either 'conversation' or 'task'.", ok: false },
+ { status: 400 },
+ );
+}
+
+function parseTurnPolicyField(value: unknown): TurnPolicy | Response | undefined {
+ if (value === undefined) return undefined;
+ if (value === "queue" || value === "steer") return value;
+ return Response.json(
+ { error: "Expected 'turnPolicy' to be either 'queue' or 'steer'.", ok: false },
+ { status: 400 },
+ );
+}
+
+function parseMessageField(value: unknown): string | UserContent | undefined | Response {
+ if (value === undefined) return undefined;
+ if (typeof value === "string") return value.length > 0 ? value : undefined;
+
+ if (!Array.isArray(value)) {
+ return Response.json(
+ { error: "Expected 'message' to be a string or an array of text/file parts.", ok: false },
+ { status: 400 },
+ );
+ }
+
+ if (value.length === 0) return undefined;
+
+ const parts: Array<TextPart | FilePart> = [];
+ for (const raw of value) {
+ const parsed = parseMessagePart(raw);
+ if (parsed instanceof Response) return parsed;
+ parts.push(parsed);
+ }
+ return parts;
+}
+
+function parseMessagePart(raw: unknown): TextPart | FilePart | Response {
+ if (raw === null || typeof raw !== "object") {
+ return Response.json(
+ { error: "Expected each message part to be an object.", ok: false },
+ { status: 400 },
+ );
+ }
+
+ const part = raw as Record<string, unknown>;
+ if (part.type === "text") {
+ if (typeof part.text !== "string" || part.text.length === 0) {
+ return Response.json(
+ { error: "Text parts require a non-empty 'text' string.", ok: false },
+ { status: 400 },
+ );
+ }
+ return { type: "text", text: part.text };
+ }
+
+ if (part.type === "file") {
+ if (typeof part.mediaType !== "string" || part.mediaType.length === 0) {
+ return Response.json(
+ { error: "File parts require a non-empty 'mediaType' string.", ok: false },
+ { status: 400 },
+ );
+ }
+ if (typeof part.data !== "string") {
+ return Response.json(
+ { error: "File parts require a 'data' string (base64, data URL, or URL).", ok: false },
+ { status: 400 },
+ );
+ }
+ // Callers must never supply framework-internal refs (`eve-url:`,
+ // `eve-sandbox:`, `eve-attachment:`): the staging pipeline trusts the
+ // scheme and would reconstitute the string into a privileged sandbox read.
+ if (hasInternalRefScheme(part.data)) {
+ return Response.json(
+ { error: "File part 'data' must not use a framework-internal ref scheme.", ok: false },
+ { status: 400 },
+ );
+ }
+ const filePart: FilePart = { type: "file", mediaType: part.mediaType, data: part.data };
+ if (typeof part.filename === "string" && part.filename.length > 0) {
+ filePart.filename = part.filename;
+ }
+ return filePart;
+ }
+
+ return Response.json(
+ {
+ error: `Unsupported message part type "${String(part.type)}". Use 'text' or 'file'.`,
+ ok: false,
+ },
+ { status: 400 },
+ );
+}
+
+export function checkUploadPolicy(
+ body: ParsedCreateBody | ParsedSessionMessageBody,
+ policy: UploadPolicy,
+): Response | null {
+ if (!body.message) return null;
+ const violations = collectUploadPolicyViolations(body.message, policy);
+ if (violations.length === 0) return null;
+
+ const [first] = violations;
+ if (!first) return null;
+
+ const status = first.kind === "too-large" ? 413 : 415;
+ return Response.json(
+ {
+ error: formatUploadPolicyViolation(first),
+ ok: false,
+ violations: violations.map((v) =>
+ v.kind === "too-large"
+ ? {
+ byteLength: v.byteLength,
+ filename: v.filename,
+ kind: v.kind,
+ limit: v.limit,
+ mediaType: v.mediaType,
+ }
+ : {
+ allowedMediaTypes: v.allowedMediaTypes,
+ filename: v.filename,
+ kind: v.kind,
+ mediaType: v.mediaType,
+ },
+ ),
+ },
+ { status },
+ );
+}
+
+function parseInputResponses(
+ value: unknown,
+): readonly ValidatedInputResponse[] | Response | undefined {
+ if (value === undefined) return undefined;
+ if (!Array.isArray(value) || value.length === 0) {
+ return Response.json(
+ { error: "Expected 'inputResponses' to be a non-empty array.", ok: false },
+ { status: 400 },
+ );
+ }
+ const inputResponses = value.filter(isInputResponse);
+ if (inputResponses.length !== value.length) {
+ return Response.json(
+ {
+ error: "Expected every 'inputResponses' entry to match the HITL response schema.",
+ ok: false,
+ },
+ { status: 400 },
+ );
+ }
+ return inputResponses;
+}
+
+export function mergeContext(
+ existing: readonly string[] | undefined,
+ added: readonly string[] | undefined,
+): readonly string[] | undefined {
+ if (existing === undefined) return added;
+ if (added === undefined) return existing;
+ return [...existing, ...added];
+}
+
+const CLIENT_CONTEXT_PREFIX = "Client context:\n";
+
+function parseClientContextField(value: unknown): string[] | Response | undefined {
+ if (value === undefined) return undefined;
+
+ if (typeof value === "string") {
+ return value.length > 0 ? [toClientContextMessage(value)] : undefined;
+ }
+
+ if (Array.isArray(value)) {
+ if (value.length === 0) return undefined;
+
+ if (!value.every((entry) => typeof entry === "string" && entry.length > 0)) {
+ return Response.json(
+ { error: "Expected 'clientContext' array entries to be non-empty strings.", ok: false },
+ { status: 400 },
+ );
+ }
+
+ return value.map((entry) => toClientContextMessage(entry));
+ }
+
+ if (value === null || typeof value !== "object") {
+ return Response.json(
+ {
+ error: "Expected 'clientContext' to be a string, string array, or JSON object.",
+ ok: false,
+ },
+ { status: 400 },
+ );
+ }
+
+ try {
+ const json = parseJsonObject(value);
+ return [toClientContextMessage(JSON.stringify(json))];
+ } catch {
+ return Response.json(
+ { error: "Expected 'clientContext' to be a JSON-serializable object.", ok: false },
+ { status: 400 },
+ );
+ }
+}
+
+function toClientContextMessage(content: string): string {
+ return `${CLIENT_CONTEXT_PREFIX}${content}`;
+}
+
+export function parseIncludeTailIndex(request: Request): boolean {
+ const raw = new URL(request.url).searchParams.get("includeTailIndex");
+ return raw === "1" || raw === "true";
+}
+
+export function parseStartIndex(request: Request): number | undefined | Response {
+ const raw = new URL(request.url).searchParams.get("startIndex");
+ if (raw === null) return undefined;
+ const parsed = Number(raw);
+ if (!/^-?\d+$/.test(raw) || !Number.isSafeInteger(parsed)) {
+ return Response.json(
+ { error: "Expected startIndex to be an integer.", ok: false },
+ { status: 400 },
+ );
+ }
+ return parsed;
+}
+
+function streamEventLimit(
+ startIndex: number | undefined,
+ tailIndex: number | undefined,
+): number | undefined {
+ if (tailIndex === undefined) return undefined;
+ const resolvedStartIndex =
+ startIndex === undefined
+ ? 0
+ : startIndex < 0
+ ? Math.max(0, tailIndex + 1 + startIndex)
+ : startIndex;
+ return Math.max(0, tailIndex - resolvedStartIndex + 1);
+}
+
+function serializeAsNdjson(
+ events: ReadableStream<unknown>,
+ signal: AbortSignal,
+ eventLimit?: number,
+): ReadableStream<Uint8Array> {
+ const encoder = new TextEncoder();
+ let eventCount = 0;
+ const transform = new TransformStream<unknown, Uint8Array>({
+ start(controller) {
+ controller.enqueue(encoder.encode("\n"));
+ if (eventLimit === 0) controller.terminate();
+ },
+ transform(event, controller) {
+ controller.enqueue(encoder.encode(`${JSON.stringify(event)}\n`));
+ eventCount += 1;
+ if (eventCount === eventLimit) controller.terminate();
+ },
+ });
+ void events.pipeTo(transform.writable, { signal }).catch(() => {});
+ return transform.readable;
+}
diff --git a/packages/eve/src/eve-channel/support.ts b/packages/eve/src/eve-channel/support.ts
new file mode 100644
index 000000000..b9b5a28fb
--- /dev/null
+++ b/packages/eve/src/eve-channel/support.ts
@@ -0,0 +1,164 @@
+import type { UserContent } from "ai";
+
+import type { SessionAuthContext } from "#channel/types.js";
+import { workflowEntryReference } from "#execution/workflow-runtime.js";
+import { createLogger, logError } from "#internal/logging.js";
+import type { MessageStreamEvent, SubagentCalledStreamEvent } from "#protocol/message.js";
+import type { ChannelCors } from "#public/definitions/channel.js";
+import {
+ defaultEveAuth,
+ type EveChannelCors,
+ type EveChannelCorsOptions,
+ type EveChannelInput,
+ type EveHandle,
+ type EveMessageContext,
+ type EveMessageResult,
+} from "#eve-channel/types.js";
+
+const log = createLogger("eve.channel");
+
+export function healthResponse(): Response {
+ return Response.json({
+ ok: true,
+ status: "ready",
+ workflowId: workflowEntryReference.workflowId,
+ });
+}
+
+export async function findRemoteSubagentBinding(input: {
+ readonly callId: string;
+ readonly childSessionId: string;
+ readonly childStreamPath: string;
+ readonly parentSessionId: string;
+ readonly parent: {
+ getEventStream(options?: { startIndex?: number }): Promise<ReadableStream<MessageStreamEvent>>;
+ getStreamTailIndex(): Promise<number>;
+ };
+}): Promise<SubagentCalledStreamEvent | undefined> {
+ const tailIndex = await input.parent.getStreamTailIndex();
+ if (tailIndex < 0) return undefined;
+
+ const events = await input.parent.getEventStream({ startIndex: 0 });
+ const reader = events.getReader();
+ let binding: SubagentCalledStreamEvent | undefined;
+ try {
+ for (let index = 0; index <= tailIndex; index += 1) {
+ const next = await reader.read();
+ if (next.done) break;
+ const event = next.value;
+ if (
+ event.type === "subagent.called" &&
+ event.data.sessionId === input.parentSessionId &&
+ event.data.callId === input.callId &&
+ event.data.childSessionId === input.childSessionId &&
+ event.data.childStreamPath === input.childStreamPath &&
+ event.data.remote !== undefined
+ ) {
+ binding = event;
+ }
+ }
+ } finally {
+ await reader.cancel().catch(() => {});
+ }
+ return binding;
+}
+
+export function normalizeEveCors(cors: EveChannelCors | undefined): ChannelCors {
+ if (cors === undefined || cors === false) {
+ return false;
+ }
+ if (cors === true) {
+ return true;
+ }
+
+ const result: {
+ origin?: "*" | "null" | readonly string[];
+ methods?: "*" | readonly string[];
+ allowHeaders?: "*" | readonly string[];
+ exposeHeaders?: "*" | readonly string[];
+ credentials?: boolean;
+ maxAge?: number | false;
+ preflight?: {
+ statusCode?: number;
+ };
+ } = {};
+
+ if (cors.origin !== undefined) {
+ result.origin = normalizeEveCorsOrigin(cors.origin);
+ }
+ if (cors.methods !== undefined) {
+ result.methods = cors.methods;
+ }
+ if (cors.allowedHeaders !== undefined) {
+ result.allowHeaders = cors.allowedHeaders;
+ }
+ if (cors.exposedHeaders !== undefined) {
+ result.exposeHeaders = cors.exposedHeaders;
+ }
+ if (cors.credentials !== undefined) {
+ result.credentials = cors.credentials;
+ }
+ if (cors.maxAge !== undefined) {
+ result.maxAge = cors.maxAge;
+ }
+ if (cors.preflightStatus !== undefined) {
+ result.preflight = { statusCode: cors.preflightStatus };
+ }
+
+ return result;
+}
+
+export function normalizeEveCorsOrigin(
+ origin: NonNullable<EveChannelCorsOptions["origin"]>,
+): "*" | "null" | readonly string[] {
+ if (origin === "*" || origin === "null") {
+ return origin;
+ }
+ if (typeof origin === "string") {
+ return [origin];
+ }
+ return origin;
+}
+
+interface OnMessageOutcome {
+ readonly auth: SessionAuthContext | null;
+ readonly context?: readonly string[];
+ readonly title?: string;
+}
+
+export async function resolveOnMessage(input: {
+ readonly auth: SessionAuthContext | null;
+ readonly config: EveChannelInput;
+ readonly message: string | UserContent;
+ readonly request: Request;
+ readonly sessionId?: string;
+}): Promise<OnMessageOutcome | Response> {
+ const handler = input.config.onMessage ?? defaultOnMessage;
+
+ let result: EveMessageResult;
+ try {
+ const eve: EveHandle =
+ input.sessionId === undefined
+ ? { caller: input.auth, request: input.request }
+ : { caller: input.auth, request: input.request, sessionId: input.sessionId };
+ const ctx: EveMessageContext = { eve };
+ result = await handler(ctx, input.message);
+ if (result === null || result === undefined) {
+ throw new TypeError("eveChannel onMessage must return an auth result.");
+ }
+ } catch (error) {
+ const errorId = logError(log, "onMessage handler failed", error, {
+ sessionId: input.sessionId,
+ });
+ return Response.json(
+ { error: "onMessage handler failed.", errorId, ok: false },
+ { status: 500 },
+ );
+ }
+
+ return { auth: result.auth, context: result.context, title: result.title };
+}
+
+export function defaultOnMessage(ctx: EveMessageContext): EveMessageResult {
+ return { auth: defaultEveAuth(ctx) };
+}
diff --git a/packages/eve/src/eve-channel/types.ts b/packages/eve/src/eve-channel/types.ts
new file mode 100644
index 000000000..d643f3754
--- /dev/null
+++ b/packages/eve/src/eve-channel/types.ts
@@ -0,0 +1,149 @@
+import type { UserContent } from "ai";
+
+import type { SessionAuthContext, TurnPolicy } from "#channel/types.js";
+import type { TrustedForwarders } from "#channel/forwarded-principal.js";
+import type { AuthFn } from "#public/channels/auth.js";
+import type { UploadPolicyInput } from "#public/channels/upload-policy.js";
+import type {
+ Channel,
+ ChannelContinuationOps,
+ ChannelEvents,
+ ChannelMethod,
+} from "#public/definitions/channel.js";
+
+/**
+ * Event-handler channel context exposed by `eveChannel({ events })`. The default eve HTTP channel
+ * has no platform-specific state, so handlers receive optional continuation routing here and the
+ * `SessionContext` third argument from {@link ChannelEvents}.
+ */
+export type EveEventContext = ChannelContinuationOps;
+
+/** Runtime stream-event handlers supported by `eveChannel({ events })`. */
+export type EveChannelEvents = ChannelEvents<EveEventContext>;
+
+export interface EveChannelCorsOptions {
+ /**
+ * Allowed request origin. Pass a single origin string, an exact-origin list,
+ * `"null"`, or `"*"`. Omit for `"*"`.
+ */
+ readonly origin?: "*" | "null" | string | readonly string[];
+ /** Methods emitted on preflight responses. Omit for `"*"`. */
+ readonly methods?: "*" | readonly ChannelMethod[];
+ /** Request headers emitted on preflight responses. Omit for `"*"`. */
+ readonly allowedHeaders?: "*" | readonly string[];
+ /** Response headers exposed to browser callers. Omit for `"*"`. */
+ readonly exposedHeaders?: "*" | readonly string[];
+ /** Whether to emit `access-control-allow-credentials: true`. */
+ readonly credentials?: boolean;
+ /** Max age, in seconds, emitted on preflight responses. */
+ readonly maxAge?: number | false;
+ /** Preflight response status code. Defaults to 204. */
+ readonly preflightStatus?: number;
+}
+
+/**
+ * Higher-level CORS policy for the default eve HTTP channel. Pass `true` for
+ * fully permissive browser access, or pass an options object to narrow it.
+ */
+export type EveChannelCors = boolean | EveChannelCorsOptions;
+
+/** Low-level eve HTTP handle exposed to `eveChannel({ onMessage })`. */
+export interface EveHandle {
+ /** Route-auth result for the request; `onMessage` chooses session auth by returning `{ auth }`. */
+ readonly caller: SessionAuthContext | null;
+ readonly request: Request;
+ /** Existing runtime session id for follow-up requests. */
+ readonly sessionId?: string;
+}
+
+/** Pre-dispatch context passed to `eveChannel({ onMessage })`. */
+export interface EveMessageContext {
+ readonly eve: EveHandle;
+}
+
+/**
+ * Result of `eveChannel({ onMessage })`. The object dispatches the inbound message,
+ * optionally prepending `context` strings as user messages.
+ */
+export type EveMessageResult = {
+ readonly auth: SessionAuthContext | null;
+ readonly context?: readonly string[];
+ /** Overrides the workflow run title without changing the message sent to the model. */
+ readonly title?: string;
+};
+
+/** Synchronous or asynchronous `onMessage` result. */
+export type EveMessageResultOrPromise = EveMessageResult | Promise<EveMessageResult>;
+
+/**
+ * Default `onMessage` auth projection: returns {@link EveHandle.caller} unchanged as the
+ * runtime session auth when {@link EveChannelInput.onMessage} is omitted. Call it from a custom `onMessage` to inherit the default while adding `context`.
+ */
+export function defaultEveAuth(ctx: EveMessageContext): SessionAuthContext | null {
+ return ctx.eve.caller;
+}
+
+/**
+ * Configuration for {@link eveChannel}. Only {@link auth} is required;
+ * `uploadPolicy`, `onMessage`, and `events` refine the default HTTP behavior.
+ */
+export interface EveChannelInput {
+ /**
+ * Route auth policy: a single {@link AuthFn} or an ordered array walked by {@link routeAuth}.
+ * The first entry returning a {@link SessionAuthContext} wins; `null` / `undefined` skips to
+ * the next; exhaustion (including the empty array) rejects with 401. Include `none()` last for anonymous traffic.
+ */
+ readonly auth: AuthFn<Request> | readonly AuthFn<Request>[];
+ /**
+ * The trusted-forwarders policy: which transport-authenticated callers may
+ * assert a forwarded principal on the create-session or continuation route (the
+ * `forwardedPrincipal` body field a `defineRemoteAgent({ forwardPrincipal:
+ * true })` sender emits). The predicate receives the *verified* route-auth
+ * principal of the forwarder — who is asserting, never what is asserted —
+ * and must match it precisely (for example
+ * `(forwarder) => forwarder.subject === vercelSubject({ teamSlug, projectName })`).
+ * A permissive predicate lets any authenticated forwarder assert any
+ * principal.
+ *
+ * When a trusted forwarder's assertion is accepted on session creation, the
+ * forwarded principal replaces `session.auth.current` and
+ * `session.auth.initiator`. On continuation, only `session.auth.current`
+ * changes; the initiator remains pinned to the session's creator. The
+ * forwarder is recorded on accepted contexts as the `eve:forwarded-by`
+ * attribute. Omit the option to reject every forwarded assertion with 403.
+ */
+ readonly trustedForwarders?: TrustedForwarders;
+ /**
+ * Attachment policy for inbound file parts. Omit for the framework default (25 MB cap, all media
+ * types); `"disabled"` rejects every attachment; a partial config is merged onto the default. Violations reject with 413 (too large) or 415 (bad type).
+ */
+ readonly uploadPolicy?: UploadPolicyInput;
+ /**
+ * Browser CORS policy for the eve HTTP routes. Omit or pass `false` to leave
+ * CORS untouched, pass `true` for fully permissive CORS, or pass an options
+ * object to narrow the policy.
+ */
+ readonly cors?: EveChannelCors;
+ /** Policy for follow-up messages that arrive while a turn is active. */
+ readonly turnPolicy?: TurnPolicy;
+ /**
+ * Pre-dispatch hook for inbound eve HTTP messages. Runs after route auth and body
+ * parsing, before runtime dispatch.
+ */
+ readonly onMessage?: (
+ ctx: EveMessageContext,
+ message: string | UserContent,
+ ) => EveMessageResultOrPromise;
+ /**
+ * Runtime stream-event handlers for the default eve HTTP channel. Handlers receive
+ * the event data, {@link EveEventContext}, and `SessionContext` (the same shape as custom channels).
+ */
+ readonly events?: EveChannelEvents;
+}
+
+/**
+ * Concrete return type of {@link eveChannel}. Named so consumers can default-export an
+ * `eveChannel(...)` call under `declaration: true` without TypeScript falling back to an
+ * internal path for `Channel`.
+ */
+export interface EveChannel extends Channel {}
diff --git a/packages/eve/src/execution/agent-handle-dispatch.ts b/packages/eve/src/execution/agent-handle-dispatch.ts
index be7beb776..b10faecb1 100644
--- a/packages/eve/src/execution/agent-handle-dispatch.ts
+++ b/packages/eve/src/execution/agent-handle-dispatch.ts
@@ -28,7 +28,7 @@ import type {
RuntimeRemoteAgentCallActionRequest,
RuntimeSubagentCallActionRequest,
RuntimeSubagentDispatchFailure,
-} from "#runtime/actions/types.js";
+} from "#shared/action-types.js";
import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
import {
continueRemoteAgentSession,
diff --git a/packages/eve/src/execution/authorization-callback-match.ts b/packages/eve/src/execution/authorization-callback-match.ts
index ade9e9b1a..d780f3538 100644
--- a/packages/eve/src/execution/authorization-callback-match.ts
+++ b/packages/eve/src/execution/authorization-callback-match.ts
@@ -1,7 +1,7 @@
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 { AuthorizationCallback } from "#runtime/connections/types.js";
+import type { AuthorizationCallback } from "#shared/connection-types.js";
export interface MatchedAuthorizationCallback {
readonly authorization: ConnectionAuthorizationChallenge;
diff --git a/packages/eve/src/execution/compaction.test.ts b/packages/eve/src/execution/compaction.test.ts
index 35f3b2d84..7c0fd391f 100644
--- a/packages/eve/src/execution/compaction.test.ts
+++ b/packages/eve/src/execution/compaction.test.ts
@@ -2,8 +2,8 @@ import { describe, expect, it } from "vitest";
import { ContextContainer, contextStorage } from "#context/container.js";
import { preserveFrameworkStateOnCompaction } from "#execution/compaction.js";
-import { ReadFileStateKey } from "#runtime/framework-tools/file-state.js";
-import { TodoStateKey } from "#runtime/framework-tools/todo.js";
+import { ReadFileStateKey } from "#execution/tools/file-state.js";
+import { TodoStateKey } from "#execution/tools/todo.js";
function run(setup: (ctx: ContextContainer) => void): {
ctx: ContextContainer;
diff --git a/packages/eve/src/execution/compaction.ts b/packages/eve/src/execution/compaction.ts
index 1544642da..7da2a689a 100644
--- a/packages/eve/src/execution/compaction.ts
+++ b/packages/eve/src/execution/compaction.ts
@@ -1,7 +1,7 @@
import type { ModelMessage } from "ai";
-import { clearReadFileState } from "#runtime/framework-tools/file-state.js";
-import { getTodoCompactionMessage } from "#runtime/framework-tools/todo.js";
+import { clearReadFileState } from "#execution/tools/file-state.js";
+import { getTodoCompactionMessage } from "#execution/tools/todo.js";
/**
* Re-applies framework-owned state preservation after the harness compacts
diff --git a/packages/eve/src/runtime/connections/callback-route.ts b/packages/eve/src/execution/connections/callback-route.ts
similarity index 60%
rename from packages/eve/src/runtime/connections/callback-route.ts
rename to packages/eve/src/execution/connections/callback-route.ts
index a84686d44..c688ded5e 100644
--- a/packages/eve/src/runtime/connections/callback-route.ts
+++ b/packages/eve/src/execution/connections/callback-route.ts
@@ -2,7 +2,7 @@
* Framework-shipped callback route used by in-turn interactive
* connection authorization.
*
- * The route at {@link EVE_CONNECTION_CALLBACK_ROUTE_PATTERN} is the
+ * The connection callback route is the
* redirect target the workflow body hands to the IdP via
* `startAuthorization`. When the IdP redirects the user's browser back
* with the OAuth `code`/`state` (or whatever payload the protocol
@@ -23,85 +23,15 @@
*/
import { resumeHook } from "#internal/workflow/runtime.js";
-import {
- EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,
- EVE_LEGACY_CONNECTION_CALLBACK_ROUTE_PATTERN,
-} from "#protocol/routes.js";
-import type { ChannelMethod, RouteContext } from "#public/definitions/channel.js";
-import type { ResolvedChannelDefinition } from "#runtime/types.js";
+import type { RouteContext } from "#public/definitions/channel.js";
import { buildAuthorizationCompletePage } from "#runtime/connections/authorization-complete-page.js";
-import type { AuthorizationCallback } from "#runtime/connections/types.js";
+import type { AuthorizationCallback } from "#shared/connection-types.js";
/**
* Logical name prefix of the framework-shipped connection callback
* channel. The trailing method segment (`get` or `post`) keeps each
* `(method, urlPath)` pair distinct in the channel registry.
*/
-export const HTTP_CONNECTION_CALLBACK_CHANNEL_NAME_PREFIX = "eve/v1/connections/callback";
-
-/**
- * HTTP methods accepted by the connection callback route.
- *
- * Most OAuth IdPs redirect back over `GET` (authorization code in the
- * query string). Some `form_post` response modes deliver the callback
- * over `POST` instead, so the framework registers both. Both
- * methods route through the same handler.
- */
-const HANDLED_METHODS: readonly ChannelMethod[] = ["GET", "POST"];
-const ROUTE_KINDS = ["attempt", "legacy"] as const;
-type CallbackRouteKind = (typeof ROUTE_KINDS)[number];
-
-/**
- * Returns the framework-shipped channel definitions that mount the
- * connection callback route at {@link EVE_CONNECTION_CALLBACK_ROUTE_PATTERN}.
- *
- * Returns one definition per accepted HTTP method and route generation. The
- * legacy shape remains mounted for callbacks minted by already-pinned runs.
- * The framework channel resolver mounts each `(method, urlPath)` pair as a
- * separate Nitro route.
- */
-export function getConnectionCallbackChannelDefinitions(): readonly ResolvedChannelDefinition[] {
- return ROUTE_KINDS.flatMap((kind) =>
- HANDLED_METHODS.map((method) => buildCallbackChannelDefinition(method, kind)),
- );
-}
-
-/**
- * Returns the set of logical channel names registered by the connection
- * callback route. Used by `getAllFrameworkChannelNames` so authors who
- * `disableRoute()` one of these names get a useful diagnostic instead
- * of a silent no-op.
- */
-export function getConnectionCallbackChannelNames(): ReadonlySet<string> {
- return new Set(getConnectionCallbackChannelDefinitions().map((definition) => definition.name));
-}
-
-function buildCallbackChannelDefinition(
- method: ChannelMethod,
- kind: CallbackRouteKind,
-): ResolvedChannelDefinition {
- const name = channelNameForMethod(method, kind);
- return {
- name,
- method,
- urlPath:
- kind === "attempt"
- ? EVE_CONNECTION_CALLBACK_ROUTE_PATTERN
- : EVE_LEGACY_CONNECTION_CALLBACK_ROUTE_PATTERN,
- fetch:
- kind === "attempt" ? handleConnectionCallbackRequest : handleLegacyConnectionCallbackRequest,
- logicalPath: `framework://channels/${name}`,
- sourceId: `eve:framework:connection-callback-${kind}-${method.toLowerCase()}`,
- sourceKind: "module",
- };
-}
-
-function channelNameForMethod(method: ChannelMethod, kind: CallbackRouteKind): string {
- const suffix = method.toLowerCase();
- return kind === "attempt"
- ? `${HTTP_CONNECTION_CALLBACK_CHANNEL_NAME_PREFIX}/${suffix}`
- : `${HTTP_CONNECTION_CALLBACK_CHANNEL_NAME_PREFIX}/legacy/${suffix}`;
-}
/**
* Inbound handler for the connection callback route. Exported for test
@@ -115,7 +45,7 @@ export async function handleConnectionCallbackRequest(
return handleCallbackRequest(request, ctx, false);
}
-async function handleLegacyConnectionCallbackRequest(
+export async function handleLegacyConnectionCallbackRequest(
request: Request,
ctx: RouteContext,
): Promise<Response> {
diff --git a/packages/eve/src/execution/create-session-step.test.ts b/packages/eve/src/execution/create-session-step.test.ts
index 19643f55a..f06b2fc27 100644
--- a/packages/eve/src/execution/create-session-step.test.ts
+++ b/packages/eve/src/execution/create-session-step.test.ts
@@ -3,6 +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 type { RuntimeTurnAgent } from "#runtime/agent/bootstrap.js";
vi.mock("#runtime/sessions/compiled-agent-cache.js", () => ({
@@ -22,9 +23,21 @@ describe("createSessionStep", () => {
vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({
resolvedAgent: {
config: { experimental: { tasks: true } },
- disabledFrameworkTools: [],
},
- turnAgent: TestTurnAgent,
+ turnAgent: {
+ ...TestTurnAgent,
+ tools: [
+ {
+ description: "Report task progress.",
+ inputSchema: null,
+ kind: "authored-tool",
+ logicalPath: `tools/${TASK_UPDATE_TOOL_NAME}.ts`,
+ name: TASK_UPDATE_TOOL_NAME,
+ owner: { feature: "tasks", kind: "framework" },
+ sourceId: `framework:tools/${TASK_UPDATE_TOOL_NAME}.ts`,
+ },
+ ],
+ },
} as never);
const { state } = await createSessionStep({
@@ -43,7 +56,6 @@ describe("createSessionStep", () => {
vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({
resolvedAgent: {
config: {},
- disabledFrameworkTools: [],
},
turnAgent: TestTurnAgent,
} as never);
diff --git a/packages/eve/src/execution/create-session-step.ts b/packages/eve/src/execution/create-session-step.ts
index 375c429dd..135de2cd4 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 { isTaskToolAvailable, TASK_UPDATE_TOOL_NAME } from "#runtime/framework-tools/tasks.js";
+import { TASK_UPDATE_TOOL_NAME } from "#shared/task-tool.js";
/**
* Result returned by {@link createSessionStep}.
@@ -56,14 +56,13 @@ export async function createSessionStep(input: {
);
const taskUpdatesEnabled =
input.taskOwned === true &&
- isTaskToolAvailable({
- disabledFrameworkTools: bundle.resolvedAgent.disabledFrameworkTools ?? [],
- hasAuthoredTool: effectiveAgent.turnAgent.tools.some(
- (tool) => tool.name === TASK_UPDATE_TOOL_NAME,
- ),
- tasksEnabled: bundle.resolvedAgent.config?.experimental?.tasks === true,
- toolName: TASK_UPDATE_TOOL_NAME,
- });
+ bundle.resolvedAgent.config?.experimental?.tasks === true &&
+ effectiveAgent.turnAgent.tools.some(
+ (tool) =>
+ tool.kind === "authored-tool" &&
+ tool.owner.kind === "framework" &&
+ tool.name === TASK_UPDATE_TOOL_NAME,
+ );
// Both token axes resolve tighter-wins against the cap inherited from the
// delegating parent: a child may narrow what its parent granted, never widen
diff --git a/packages/eve/src/execution/delegated-parent-notification.test.ts b/packages/eve/src/execution/delegated-parent-notification.test.ts
index 8b6373549..31fe8cea3 100644
--- a/packages/eve/src/execution/delegated-parent-notification.test.ts
+++ b/packages/eve/src/execution/delegated-parent-notification.test.ts
@@ -16,7 +16,7 @@ import { SUBAGENT_ADAPTER } from "#execution/subagent-adapter.js";
import { SUBAGENT_ADAPTER_KIND } from "#execution/subagent-adapter-state.js";
import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";
import { resumeHook } from "#internal/workflow/runtime.js";
-import type { RuntimeSubagentChildResult } from "#runtime/actions/types.js";
+import type { RuntimeSubagentChildResult } from "#shared/action-types.js";
vi.mock("../runtime/sessions/compiled-agent-cache.js", () => ({
getCompiledRuntimeAgentBundle: vi.fn(),
diff --git a/packages/eve/src/execution/delegated-parent-notification.ts b/packages/eve/src/execution/delegated-parent-notification.ts
index 7c89a0c87..350d6a30f 100644
--- a/packages/eve/src/execution/delegated-parent-notification.ts
+++ b/packages/eve/src/execution/delegated-parent-notification.ts
@@ -7,7 +7,7 @@ import { ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
import { deserializeContext } from "#context/serialize.js";
import { parseSessionCallback } from "#channel/session-callback.js";
import type { TurnCaller } from "#channel/types.js";
-import type { RuntimeSubagentChildResult } from "#runtime/actions/types.js";
+import type { RuntimeSubagentChildResult } from "#shared/action-types.js";
import { SessionCallbackKey } from "#context/keys.js";
import {
isSubagentAdapterState,
diff --git a/packages/eve/src/execution/delegated-parent-result.ts b/packages/eve/src/execution/delegated-parent-result.ts
index fa0c3c4ad..2b162a8d0 100644
--- a/packages/eve/src/execution/delegated-parent-result.ts
+++ b/packages/eve/src/execution/delegated-parent-result.ts
@@ -6,7 +6,7 @@
*/
import { SUBAGENT_EXECUTION_FAILED } from "#harness/agent-handle-errors.js";
-import type { RuntimeSubagentChildResult } from "#runtime/actions/types.js";
+import type { RuntimeSubagentChildResult } from "#shared/action-types.js";
import type { JsonValue } from "#shared/json.js";
import { toErrorMessage } from "#shared/errors.js";
import type { TokenUsage } from "#shared/token-usage.js";
diff --git a/packages/eve/src/execution/delegation-tool.ts b/packages/eve/src/execution/delegation-tool.ts
index 5e68b7ed5..7931ff9f6 100644
--- a/packages/eve/src/execution/delegation-tool.ts
+++ b/packages/eve/src/execution/delegation-tool.ts
@@ -1,10 +1,7 @@
import type { HarnessToolDefinition } from "#harness/execute-tool.js";
import { createToolExecuteWithAuth } from "#execution/tool-auth.js";
-import {
- defineSubagent,
- registerLocalSubagentExecutor,
-} from "#runtime/framework-tools/subagent/local.js";
-import { defineRemoteSubagent } from "#runtime/framework-tools/subagent/remote.js";
+import { defineSubagent, registerLocalSubagentExecutor } from "#execution/tools/subagent/local.js";
+import { defineRemoteSubagent } from "#execution/tools/subagent/remote.js";
import type { PreparedRuntimeDelegationTool } from "#runtime/sessions/turn.js";
import {
UNSPECIFIED_INPUT_SCHEMA,
diff --git a/packages/eve/src/execution/dispatch-action-failures.ts b/packages/eve/src/execution/dispatch-action-failures.ts
index 2aa980b9b..d2b357aae 100644
--- a/packages/eve/src/execution/dispatch-action-failures.ts
+++ b/packages/eve/src/execution/dispatch-action-failures.ts
@@ -3,7 +3,7 @@ import type {
RuntimeRemoteAgentCallActionRequest,
RuntimeSubagentCallActionRequest,
RuntimeSubagentDispatchFailure,
-} from "#runtime/actions/types.js";
+} from "#shared/action-types.js";
import { toErrorMessage } from "#shared/errors.js";
export function createUnavailableDynamicSubagentResult(
diff --git a/packages/eve/src/execution/dispatch-runtime-actions-shared.ts b/packages/eve/src/execution/dispatch-runtime-actions-shared.ts
index 0cdb3095d..8f483b8f9 100644
--- a/packages/eve/src/execution/dispatch-runtime-actions-shared.ts
+++ b/packages/eve/src/execution/dispatch-runtime-actions-shared.ts
@@ -52,7 +52,7 @@ import type {
RuntimeSubagentCallActionRequest,
RuntimeSubagentDispatchFailure,
RuntimeToolCallActionRequest,
-} from "#runtime/actions/types.js";
+} from "#shared/action-types.js";
import { type DurableSessionState, readDurableSession } from "#execution/durable-session-store.js";
import {
createRecursiveAgentRootOnlyResult,
diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.ts
index 8a3ee9474..9afdc5a8f 100644
--- a/packages/eve/src/execution/dispatch-runtime-actions-step.ts
+++ b/packages/eve/src/execution/dispatch-runtime-actions-step.ts
@@ -25,7 +25,7 @@ import {
startSubagent,
} from "#execution/dispatch-runtime-actions-shared.js";
import { createDurableSessionState } from "#execution/durable-session-store.js";
-import type { RuntimeActionResult } from "#runtime/actions/types.js";
+import type { RuntimeActionResult } from "#shared/action-types.js";
export async function dispatchRuntimeActionsStep(
input: RuntimeActionDispatchInput,
diff --git a/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts b/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts
index 6606c015e..ddc9c33b0 100644
--- a/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts
+++ b/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts
@@ -21,7 +21,7 @@ import type {
RuntimeActionRequest,
RuntimeSubagentDispatchFailure,
RuntimeActionResult,
-} from "#runtime/actions/types.js";
+} from "#shared/action-types.js";
import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";
const log = createLogger("execution.dispatch-workflow-runtime-actions");
diff --git a/packages/eve/src/execution/durable-session-migrations/turn-workflow.ts b/packages/eve/src/execution/durable-session-migrations/turn-workflow.ts
index 31aa9cf27..d8119e5a2 100644
--- a/packages/eve/src/execution/durable-session-migrations/turn-workflow.ts
+++ b/packages/eve/src/execution/durable-session-migrations/turn-workflow.ts
@@ -16,7 +16,7 @@ import type {
SessionCapabilities,
} from "#channel/types.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
-import type { RuntimeActionResult } from "#runtime/actions/types.js";
+import type { RuntimeActionResult } from "#shared/action-types.js";
import type { RunMode } from "#shared/run-mode.js";
import { runMigrationChain, type VersionMigration } from "./chain.js";
diff --git a/packages/eve/src/execution/durable-session-store.integration.test.ts b/packages/eve/src/execution/durable-session-store.integration.test.ts
index 9daf8db46..5826776d9 100644
--- a/packages/eve/src/execution/durable-session-store.integration.test.ts
+++ b/packages/eve/src/execution/durable-session-store.integration.test.ts
@@ -13,7 +13,7 @@ import {
*/
describe("durableSessionStore integration", () => {
it("each step's readDurableSession returns the immediately-preceding write", async () => {
- const runtime = createTestRuntime({ agent: { name: "durable-session-store-fixture" } });
+ const runtime = await createTestRuntime({ agent: { name: "durable-session-store-fixture" } });
await runtime.run(async () => {
const run = await start(durableSessionStoreFixtureWorkflow, [
@@ -37,7 +37,9 @@ describe("durableSessionStore integration", () => {
});
it("a standalone read step after several writes returns the latest returned state", async () => {
- const runtime = createTestRuntime({ agent: { name: "durable-session-store-fixture-tail" } });
+ const runtime = await createTestRuntime({
+ agent: { name: "durable-session-store-fixture-tail" },
+ });
await runtime.run(async () => {
const run = await start(durableSessionStoreFixtureWorkflow, [
@@ -65,7 +67,9 @@ describe("durableSessionStore integration", () => {
});
it("a write-step retry's returned state is what the subsequent read returns", async () => {
- const runtime = createTestRuntime({ agent: { name: "durable-session-store-fixture-retry" } });
+ const runtime = await createTestRuntime({
+ agent: { name: "durable-session-store-fixture-retry" },
+ });
await runtime.run(async () => {
const run = await start(durableSessionRetryFixtureWorkflow, []);
diff --git a/packages/eve/src/execution/harness-tool-execution.integration.test.ts b/packages/eve/src/execution/harness-tool-execution.integration.test.ts
index 961d77872..af5f428c9 100644
--- a/packages/eve/src/execution/harness-tool-execution.integration.test.ts
+++ b/packages/eve/src/execution/harness-tool-execution.integration.test.ts
@@ -41,7 +41,7 @@ describe("authored tool execution", () => {
};
},
});
- const runtime = createTestRuntime({ tools: [weatherTool] });
+ const runtime = await createTestRuntime({ tools: [weatherTool] });
const result = await runtime.runAsSession(undefined, async () => {
return await runtime.executeTool(weatherTool, { city: "Brooklyn" });
@@ -62,7 +62,7 @@ describe("authored tool execution", () => {
throw new Error("weather upstream unavailable");
},
});
- const runtime = createTestRuntime({ tools: [weatherTool] });
+ const runtime = await createTestRuntime({ tools: [weatherTool] });
await expect(
runtime.runAsSession(undefined, async () => {
@@ -79,7 +79,7 @@ describe("authored tool execution", () => {
return ctx.session;
},
});
- const runtime = createTestRuntime({ tools: [sessionProbe] });
+ const runtime = await createTestRuntime({ tools: [sessionProbe] });
const result = await runtime.runAsSession(
{
@@ -109,7 +109,7 @@ describe("authored tool execution", () => {
return ctx.session;
},
});
- const runtime = createTestRuntime({ tools: [sessionProbe] });
+ const runtime = await createTestRuntime({ tools: [sessionProbe] });
const result = await runtime.runAsSession(
{
@@ -157,7 +157,7 @@ describe("authored tool execution", () => {
return await ctx.getSkill("semantic-model").file("references/catalog.yml").text();
},
});
- const runtime = createTestRuntime({
+ const runtime = await createTestRuntime({
tools: [skillReader],
skills: [semanticModel.source],
});
@@ -187,7 +187,7 @@ describe("authored tool execution", () => {
return { content, id: live.id };
},
});
- const runtime = createTestRuntime({ tools: [sandboxTool] });
+ const runtime = await createTestRuntime({ tools: [sandboxTool] });
const result = (await runtime.runAsSession({ sandbox }, async () =>
runtime.executeTool(sandboxTool, {}),
@@ -222,7 +222,7 @@ describe("authored tool execution", () => {
return { reportPath, stdout: result.stdout.trim() };
},
});
- const runtime = createTestRuntime({ tools: [resolveTool] });
+ const runtime = await createTestRuntime({ tools: [resolveTool] });
const result = await runtime.runAsSession({ sandbox }, async () =>
runtime.executeTool(resolveTool, {}),
diff --git a/packages/eve/src/execution/node-step.test.ts b/packages/eve/src/execution/node-step.test.ts
index 5cfb11595..8a666e0c0 100644
--- a/packages/eve/src/execution/node-step.test.ts
+++ b/packages/eve/src/execution/node-step.test.ts
@@ -13,7 +13,7 @@ import { createEmptyHookRegistry } from "#runtime/hooks/registry.js";
import type { RuntimeToolRegistry } from "#runtime/tools/registry.js";
import { createRuntimeToolRegistry } from "#runtime/tools/registry.js";
import { createExecutionNodeStep, createNodeHarnessTools } from "#execution/node-step.js";
-import { countLocalSubagentCalls } from "#runtime/framework-tools/subagent/local.js";
+import { 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";
@@ -198,10 +198,7 @@ function createTestNode(
const agent = {} as ResolvedRuntimeAgentNode["agent"];
return {
- agent: {
- ...agent,
- disabledFrameworkTools: [],
- },
+ agent,
channels: [],
hookRegistry: createEmptyHookRegistry(),
nodeId: ROOT_RUNTIME_AGENT_NODE_ID,
@@ -219,6 +216,42 @@ function createTestNode(
};
}
+async function createNodeWithSourceOwnedTools(input: {
+ readonly names: readonly string[];
+ readonly tasks?: boolean;
+ readonly turnTools?: StaticRuntimeTurnAgent["tools"];
+}): Promise<ResolvedRuntimeAgentNode> {
+ const toolRegistry = await createRuntimeToolRegistry({
+ tools: input.names.map((name) => ({
+ description: `${name} programmatic tool.`,
+ execute: async () => `${name}-sentinel`,
+ inputSchema: null,
+ logicalPath: `tools/${name}.ts`,
+ name,
+ owner: { feature: "test", kind: "framework" },
+ sourceId: `framework:tools/${name}.ts`,
+ sourceKind: "module",
+ })),
+ });
+ const node = createTestNode(
+ createTestTurnAgent({
+ tools: [...toolRegistry.preparedTools, ...(input.turnTools ?? [])],
+ }),
+ { toolRegistry },
+ );
+ return {
+ ...node,
+ agent: {
+ ...node.agent,
+ config: {
+ experimental: { tasks: input.tasks === true },
+ model: { id: "test-model" },
+ name: "test",
+ },
+ },
+ };
+}
+
function createNoopRuntime(): Runtime {
return {
createSession: vi
@@ -237,8 +270,15 @@ function createNoopRuntime(): Runtime {
}
describe("createNodeHarnessTools", () => {
- it("guides the model to split large tasks across parallel agent calls", () => {
- const agentTool = createNodeHarnessTools({ node: createTestNode() }).get("agent");
+ it("keeps the compiled framework question tool client-side", async () => {
+ const node = await createNodeWithSourceOwnedTools({ names: ["ask_question"] });
+
+ expect(createNodeHarnessTools({ node }).get("ask_question")?.execute).toBeUndefined();
+ });
+
+ it("lowers the compiled framework agent tool to the canonical dispatch action", async () => {
+ const node = await createNodeWithSourceOwnedTools({ names: ["agent"] });
+ const agentTool = createNodeHarnessTools({ node }).get("agent");
expect(agentTool?.description).toContain("split a large task into independent pieces");
expect(agentTool?.description).toContain("multiple `agent` calls in one response");
@@ -253,47 +293,23 @@ describe("createNodeHarnessTools", () => {
});
});
- it("does not give declared subagent nodes the built-in agent tool", () => {
- const tools = createNodeHarnessTools({
- node: createTestNode(undefined, { nodeId: "subagents/researcher" }),
- });
-
- expect(tools.has("agent")).toBe(false);
- });
-
- it("does not give the root node the built-in agent tool when it is disabled", () => {
- const node = createTestNode();
- const tools = createNodeHarnessTools({
- node: {
- ...node,
- agent: {
- ...node.agent,
- disabledFrameworkTools: ["agent"],
- },
- },
+ it("omits compiled task-control tools unless experimental.tasks is on", async () => {
+ const node = await createNodeWithSourceOwnedTools({
+ names: ["task_cancel", "task_update"],
});
-
- expect(tools.has("agent")).toBe(false);
- });
-
- it("does not inject task tools without experimental.tasks", () => {
- const tools = createNodeHarnessTools({ node: createTestNode() });
+ const tools = createNodeHarnessTools({ node });
for (const name of ["task_cancel", "task_update"]) {
expect(tools.has(name)).toBe(false);
}
});
- it("injects the task tools when experimental.tasks is on", () => {
- const node = createTestNode();
+ it("lowers compiled task-control tools when experimental.tasks is on", async () => {
const tools = createNodeHarnessTools({
- node: {
- ...node,
- agent: {
- ...node.agent,
- config: { experimental: { tasks: true }, model: { id: "test-model" }, name: "test" },
- },
- },
+ node: await createNodeWithSourceOwnedTools({
+ names: ["task_cancel", "task_update"],
+ tasks: true,
+ }),
});
for (const name of ["task_cancel", "task_update"]) {
@@ -303,7 +319,7 @@ describe("createNodeHarnessTools", () => {
expect(tools.has("task_sleep")).toBe(false);
});
- it("executes local and remote subagents as background tools only with experimental.tasks", () => {
+ it("executes compiled local and remote delegation tools in the selected task mode", async () => {
const delegationTools: StaticRuntimeTurnAgent["tools"] = [
{
description: "Delegate local research.",
@@ -324,28 +340,24 @@ describe("createNodeHarnessTools", () => {
sourceId: "remote-agents/reviewer",
},
];
- const createNode = (tasks: boolean) => {
- const node = createTestNode(createTestTurnAgent({ tools: delegationTools }));
- return {
- ...node,
- agent: {
- ...node.agent,
- config: {
- experimental: { tasks },
- model: { id: "test-model" },
- name: "test",
- },
- },
- };
- };
-
- const legacy = createNodeHarnessTools({ node: createNode(false) });
+ const legacy = createNodeHarnessTools({
+ node: await createNodeWithSourceOwnedTools({
+ names: ["agent"],
+ turnTools: delegationTools,
+ }),
+ });
expect(legacy.get("research")?.runtimeAction?.kind).toBe("subagent-call");
expect(legacy.get("reviewer")?.runtimeAction?.kind).toBe("remote-agent-call");
expect(legacy.get("research")?.execution).toBeUndefined();
expect(legacy.get("reviewer")?.execution).toBeUndefined();
- const background = createNodeHarnessTools({ node: createNode(true) });
+ const background = createNodeHarnessTools({
+ node: await createNodeWithSourceOwnedTools({
+ names: ["agent"],
+ tasks: true,
+ turnTools: delegationTools,
+ }),
+ });
for (const name of ["agent", "research", "reviewer"]) {
expect(background.get(name)?.execution).toBe("background");
expect(background.get(name)?.execute).toBeDefined();
@@ -362,17 +374,9 @@ describe("createNodeHarnessTools", () => {
).toBe(2);
});
- it("respects disableTool for individual task tools", () => {
- const node = createTestNode();
+ it("does not recreate task tools absent from the compiled graph", async () => {
const tools = createNodeHarnessTools({
- node: {
- ...node,
- agent: {
- ...node.agent,
- config: { experimental: { tasks: true }, model: { id: "test-model" }, name: "test" },
- disabledFrameworkTools: ["task_cancel"],
- },
- },
+ node: await createNodeWithSourceOwnedTools({ names: ["task_update"], tasks: true }),
});
expect(tools.has("task_update")).toBe(true);
@@ -392,6 +396,7 @@ describe("createExecutionNodeStep", () => {
inputSchema: toInputSchema({ type: "object" }),
logicalPath: "tools/regular-tool.ts",
name: "regular-tool",
+ owner: { kind: "application" },
sourceId: "tools/regular-tool.ts",
sourceKind: "module",
},
diff --git a/packages/eve/src/execution/node-step.ts b/packages/eve/src/execution/node-step.ts
index eb40d0cee..be77d32fb 100644
--- a/packages/eve/src/execution/node-step.ts
+++ b/packages/eve/src/execution/node-step.ts
@@ -21,27 +21,21 @@ import {
type RuntimeModelResolutionScope,
} from "#runtime/agent/resolve-model.js";
import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
-import {
- AGENT_TOOL_DESCRIPTION,
- AGENT_TOOL_NAME,
- isImplicitAgentToolAvailable,
-} from "#runtime/framework-tools/agent.js";
-import {
- createTaskToolHarnessDefinitions,
- isTaskToolAvailable,
-} from "#runtime/framework-tools/tasks.js";
+import { AGENT_TOOL_DESCRIPTION, AGENT_TOOL_NAME } from "#shared/agent-tool.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 type { PreparedRuntimeTool } from "#runtime/sessions/turn.js";
import {
PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA,
SUBAGENT_TOOL_INPUT_SCHEMA,
-} from "#runtime/subagents/registry.js";
+} from "#shared/agent-tool.js";
+
+import type { PreparedRuntimeTool } from "#runtime/sessions/turn.js";
import { findRegisteredRuntimeTool } from "#runtime/tools/registry.js";
import type { ResolvedToolDefinition } from "#runtime/types.js";
import { preserveFrameworkStateOnCompaction } from "#execution/compaction.js";
import { createToolExecuteWithAuth } from "#execution/tool-auth.js";
+import { ASK_QUESTION_TOOL_NAME } from "#harness/request-input-tool.js";
const log = createLogger("execution.node-step");
@@ -215,45 +209,6 @@ export function createNodeHarnessTools(input: {
}
}
- if (
- isImplicitAgentToolAvailable({
- disabledFrameworkTools: input.node.agent.disabledFrameworkTools,
- hasAuthoredAgentTool: tools.has(AGENT_TOOL_NAME),
- nodeId: input.node.nodeId,
- })
- ) {
- const implicitAgent = {
- description: AGENT_TOOL_DESCRIPTION,
- inputSchema:
- tasksEnabled || input.node.agent.config?.experimental?.subagentPersistentSessions === true
- ? PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA
- : SUBAGENT_TOOL_INPUT_SCHEMA,
- kind: "subagent" as const,
- name: AGENT_TOOL_NAME,
- nodeId: input.node.nodeId,
- rootOnly: true,
- };
- tools.set(
- AGENT_TOOL_NAME,
- tasksEnabled
- ? createBackgroundSubagentHarnessDefinition(implicitAgent)
- : createHarnessDelegationToolDefinition(implicitAgent),
- );
- }
-
- for (const definition of createTaskToolHarnessDefinitions()) {
- if (
- isTaskToolAvailable({
- disabledFrameworkTools: input.node.agent.disabledFrameworkTools,
- hasAuthoredTool: tools.has(definition.name),
- tasksEnabled,
- toolName: definition.name,
- })
- ) {
- tools.set(definition.name, definition);
- }
- }
-
return tools;
}
@@ -280,20 +235,49 @@ function resolveHarnessToolDefinition(input: {
}
const def = registeredTool.definition;
- const isFrameworkTool = def.sourceId.startsWith("eve:");
+ if (def.owner.kind === "framework" && def.name === AGENT_TOOL_NAME) {
+ const delegation = {
+ description: AGENT_TOOL_DESCRIPTION,
+ inputSchema:
+ input.tasksEnabled ||
+ input.node.agent.config?.experimental?.subagentPersistentSessions === true
+ ? PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA
+ : SUBAGENT_TOOL_INPUT_SCHEMA,
+ kind: "subagent" as const,
+ name: AGENT_TOOL_NAME,
+ nodeId: input.node.nodeId,
+ rootOnly: true,
+ };
+ return input.tasksEnabled
+ ? createBackgroundSubagentHarnessDefinition(delegation)
+ : createHarnessDelegationToolDefinition(delegation);
+ }
+ if (def.owner.kind === "framework") {
+ const taskDefinition = createTaskToolHarnessDefinitions().find(
+ (definition) => definition.name === def.name,
+ );
+ if (taskDefinition !== undefined) {
+ return input.tasksEnabled ? taskDefinition : null;
+ }
+ }
const rawExecute = def.execute;
+ const isFrameworkRequestInput =
+ def.owner.kind === "framework" && def.name === ASK_QUESTION_TOOL_NAME;
return {
approvalKey: def.approvalKey,
description: def.description,
execution: def.execution,
- execute: resolveAuthoredExecute({
- isFrameworkTool,
- rawExecute,
- scope: def.name,
- }),
+ execute: isFrameworkRequestInput
+ ? undefined
+ : resolveAuthoredExecute({
+ rawExecute,
+ scope: def.name,
+ }),
frameworkAction:
- isFrameworkTool && def.name === LOAD_SKILL_TOOL_NAME ? "load-skill" : undefined,
+ def.owner.kind === "framework" && def.name === LOAD_SKILL_TOOL_NAME
+ ? "load-skill"
+ : undefined,
inputSchema: def.inputSchema ?? UNSPECIFIED_INPUT_SCHEMA,
name: def.name,
approval: def.approval,
@@ -305,26 +289,19 @@ function resolveHarnessToolDefinition(input: {
/**
* Selects the harness-facing `execute` for one authored tool.
*
- * - Framework tools (`eve:` source) run their `execute` verbatim — they
- * manage their own context and never receive an authored
- * {@link ToolContext}.
- * - Authored tools are wrapped by {@link createToolExecuteWithAuth},
+ * - Source-backed tools are wrapped by {@link createToolExecuteWithAuth},
* which builds a token-aware context. Providers passed to
* `ctx.getToken(provider)` use tool-qualified auth scopes.
* - Tools without `execute` (provider-managed) stay `undefined`.
*/
function resolveAuthoredExecute(input: {
- readonly isFrameworkTool: boolean;
readonly rawExecute: ResolvedToolDefinition["execute"];
readonly scope: string;
}): HarnessToolDefinition["execute"] {
- const { isFrameworkTool, rawExecute, scope } = input;
+ const { rawExecute, scope } = input;
if (rawExecute === undefined) {
return undefined;
}
- if (isFrameworkTool) {
- return rawExecute;
- }
const authored = rawExecute as (
toolInput: unknown,
ctx: unknown,
diff --git a/packages/eve/src/execution/proxied-deliver-step.ts b/packages/eve/src/execution/proxied-deliver-step.ts
index 8cf692f7c..75641ac5e 100644
--- a/packages/eve/src/execution/proxied-deliver-step.ts
+++ b/packages/eve/src/execution/proxied-deliver-step.ts
@@ -8,7 +8,7 @@ import {
import { routeDeliverPayload } from "#execution/subagent-hitl-proxy.js";
import { sendTaskInboundPayload } from "#execution/tasks/parent/run-parent.js";
import { resumeSessionInbox } from "#execution/wire/session-inbox-resume.js";
-import type { InputResponse } from "#runtime/input/types.js";
+import type { InputResponse } from "#shared/input.js";
import { findSessionTaskEntry } from "#tasks/session-index.js";
import {
createTaskInputRequestId,
diff --git a/packages/eve/src/execution/remote-agent-dispatch.test.ts b/packages/eve/src/execution/remote-agent-dispatch.test.ts
index c646ccb21..843769038 100644
--- a/packages/eve/src/execution/remote-agent-dispatch.test.ts
+++ b/packages/eve/src/execution/remote-agent-dispatch.test.ts
@@ -11,7 +11,7 @@ import {
resolveRemoteAgentStreamHeaders,
startRemoteAgentSession,
} from "#execution/remote-agent-dispatch.js";
-import type { RuntimeRemoteAgentCallActionRequest } from "#runtime/actions/types.js";
+import type { RuntimeRemoteAgentCallActionRequest } from "#shared/action-types.js";
import type { ResolvedRuntimeRemoteAgentNode } from "#runtime/types.js";
describe("resolveRemoteAgentForAction", () => {
diff --git a/packages/eve/src/execution/remote-agent-dispatch.ts b/packages/eve/src/execution/remote-agent-dispatch.ts
index 269428806..57a75d0d7 100644
--- a/packages/eve/src/execution/remote-agent-dispatch.ts
+++ b/packages/eve/src/execution/remote-agent-dispatch.ts
@@ -17,7 +17,7 @@ import {
normalizeRequestedOutputSchema,
} from "#execution/subagent-invocation.js";
import type { HarnessSession } from "#harness/types.js";
-import type { RuntimeRemoteAgentCallActionRequest } from "#runtime/actions/types.js";
+import type { RuntimeRemoteAgentCallActionRequest } from "#shared/action-types.js";
import type { RuntimeSubagentRegistry } from "#runtime/subagents/registry.js";
import type { DynamicRemoteAgentConfig } from "#runtime/subagents/dynamic-remote-agent-config.js";
import type { CompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";
diff --git a/packages/eve/src/execution/sandbox/glob-tool.ts b/packages/eve/src/execution/sandbox/glob-tool.ts
index 08b84ebe5..1baffbf25 100644
--- a/packages/eve/src/execution/sandbox/glob-tool.ts
+++ b/packages/eve/src/execution/sandbox/glob-tool.ts
@@ -1,4 +1,4 @@
-import { normalizeModelPath } from "#runtime/framework-tools/file-state.js";
+import { normalizeModelPath } from "#execution/tools/file-state.js";
import { resolveAbsoluteFilePath } from "#execution/sandbox/require-sandbox.js";
import type { SandboxSession } from "#shared/sandbox-session.js";
import { ripgrepIsAvailable } from "#execution/sandbox/ripgrep-probe.js";
diff --git a/packages/eve/src/execution/sandbox/grep-tool.ts b/packages/eve/src/execution/sandbox/grep-tool.ts
index 3fdb4413d..f06886548 100644
--- a/packages/eve/src/execution/sandbox/grep-tool.ts
+++ b/packages/eve/src/execution/sandbox/grep-tool.ts
@@ -1,4 +1,4 @@
-import { normalizeModelPath } from "#runtime/framework-tools/file-state.js";
+import { normalizeModelPath } from "#execution/tools/file-state.js";
import { resolveAbsoluteFilePath } from "#execution/sandbox/require-sandbox.js";
import type { SandboxSession } from "#shared/sandbox-session.js";
import { ripgrepIsAvailable } from "#execution/sandbox/ripgrep-probe.js";
diff --git a/packages/eve/src/execution/sandbox/read-file-tool.ts b/packages/eve/src/execution/sandbox/read-file-tool.ts
index 34868f288..19ed93ad2 100644
--- a/packages/eve/src/execution/sandbox/read-file-tool.ts
+++ b/packages/eve/src/execution/sandbox/read-file-tool.ts
@@ -4,7 +4,7 @@ import {
createReadFileStamp,
normalizeModelPath,
setReadFileStamp,
-} from "#runtime/framework-tools/file-state.js";
+} from "#execution/tools/file-state.js";
import { resolveAbsoluteFilePath } from "#execution/sandbox/require-sandbox.js";
import type { SandboxSession } from "#shared/sandbox-session.js";
import { capLineLength, MAX_OUTPUT_BYTES } from "#execution/sandbox/truncate-output.js";
diff --git a/packages/eve/src/execution/sandbox/write-file-tool.ts b/packages/eve/src/execution/sandbox/write-file-tool.ts
index e3727cdbc..38632f7f4 100644
--- a/packages/eve/src/execution/sandbox/write-file-tool.ts
+++ b/packages/eve/src/execution/sandbox/write-file-tool.ts
@@ -6,7 +6,7 @@ import {
type ReadFileState,
ReadFileStateKey,
setReadFileStamp,
-} from "#runtime/framework-tools/file-state.js";
+} from "#execution/tools/file-state.js";
import { resolveAbsoluteFilePath } from "#execution/sandbox/require-sandbox.js";
import type { SandboxSession } from "#shared/sandbox-session.js";
diff --git a/packages/eve/src/runtime/session-callback-route.ts b/packages/eve/src/execution/session-callback-route.ts
similarity index 90%
rename from packages/eve/src/runtime/session-callback-route.ts
rename to packages/eve/src/execution/session-callback-route.ts
index a73135362..d1122a7e4 100644
--- a/packages/eve/src/runtime/session-callback-route.ts
+++ b/packages/eve/src/execution/session-callback-route.ts
@@ -1,15 +1,13 @@
import { resumeHook } from "#internal/workflow/runtime.js";
import { z } from "#compiled/zod/index.js";
import { REMOTE_AGENT_FAILED } from "#harness/agent-handle-errors.js";
-import { EVE_CALLBACK_ROUTE_PATTERN } from "#protocol/routes.js";
-import type { ChannelMethod, RouteContext } from "#public/definitions/channel.js";
+import type { RouteContext } from "#public/definitions/channel.js";
import type { SubagentAuthorizationEvent } from "#channel/types.js";
-import type { ResolvedChannelDefinition } from "#runtime/types.js";
-import type { RuntimeSubagentChildResult } from "#runtime/actions/types.js";
+import type { RuntimeSubagentChildResult } from "#shared/action-types.js";
import { agentTurnOutcomeSchema } from "#shared/agent-turn-outcome.js";
import { jsonValueSchema } from "#shared/json-schemas.js";
import type { JsonValue } from "#shared/json.js";
-import { isInputRequest } from "#runtime/input/types.js";
+import { isInputRequest } from "#shared/input.js";
import { tokenUsageSchema, type TokenUsage } from "#shared/token-usage.js";
import type {
TaskInboundAuthorizationEvent,
@@ -19,10 +17,6 @@ import type {
} from "#tasks/types.js";
import { readTaskIdFromInboxToken } from "#tasks/task-id.js";
-export const HTTP_SESSION_CALLBACK_CHANNEL_NAME_PREFIX = "eve/v1/callback";
-
-const HANDLED_METHODS: readonly ChannelMethod[] = ["POST"];
-
const ZERO_TOKEN_USAGE: TokenUsage = {
cacheReadTokens: 0,
cacheWriteTokens: 0,
@@ -167,31 +161,6 @@ const sessionResultCallbackSchema = z.discriminatedUnion("kind", [
}),
]);
-export function getSessionCallbackChannelDefinitions(): readonly ResolvedChannelDefinition[] {
- return HANDLED_METHODS.map((method) => buildCallbackChannelDefinition(method));
-}
-
-export function getSessionCallbackChannelNames(): ReadonlySet<string> {
- return new Set(HANDLED_METHODS.map(channelNameForMethod));
-}
-
-function buildCallbackChannelDefinition(method: ChannelMethod): ResolvedChannelDefinition {
- const name = channelNameForMethod(method);
- return {
- name,
- method,
- urlPath: EVE_CALLBACK_ROUTE_PATTERN,
- fetch: handleSessionCallbackRequest,
- logicalPath: `framework://channels/${name}`,
- sourceId: `eve:framework:session-callback-${method.toLowerCase()}`,
- sourceKind: "module",
- };
-}
-
-function channelNameForMethod(method: ChannelMethod): string {
- return `${HTTP_SESSION_CALLBACK_CHANNEL_NAME_PREFIX}/${method.toLowerCase()}`;
-}
-
export async function handleSessionCallbackRequest(
request: Request,
ctx: RouteContext,
diff --git a/packages/eve/src/execution/session-limit-cancellation.integration.test.ts b/packages/eve/src/execution/session-limit-cancellation.integration.test.ts
index 91a8e3828..dcdd7fcdf 100644
--- a/packages/eve/src/execution/session-limit-cancellation.integration.test.ts
+++ b/packages/eve/src/execution/session-limit-cancellation.integration.test.ts
@@ -77,7 +77,7 @@ function requestIdFromPromptTurn(events: readonly UnstampedMessageStreamEvent[])
describe("session-limit continuation decline integration", () => {
it("cancels the turn and keeps the session resumable when the user declines", async () => {
- const runtime = createTestRuntime({
+ const runtime = await createTestRuntime({
agent: { limits: { maxInputTokensPerSession: 1 }, name: "limit-decline-root" },
});
const continuationToken = "http:limit-decline-root";
@@ -143,7 +143,7 @@ describe("session-limit continuation decline integration", () => {
}, 60_000);
it("fails a zero-quota delegation fast and declines the root's own prompt", async () => {
- const runtime = createTestRuntime({
+ const runtime = await createTestRuntime({
agent: { limits: { maxInputTokensPerSession: 1 }, name: "limit-decline-child" },
});
const continuationToken = "http:limit-decline-child";
diff --git a/packages/eve/src/execution/session.test.ts b/packages/eve/src/execution/session.test.ts
index 292bc689f..7eb062c85 100644
--- a/packages/eve/src/execution/session.test.ts
+++ b/packages/eve/src/execution/session.test.ts
@@ -31,6 +31,7 @@ function createTestTurnAgent(overrides?: Partial<StaticRuntimeTurnAgent>): Runti
kind: "authored-tool",
logicalPath: "tools/add",
name: "add",
+ owner: { kind: "application" },
sourceId: "src-add",
},
],
@@ -168,6 +169,7 @@ describe("createSession", () => {
kind: "authored-tool",
logicalPath: "tools/noop",
name: "noop",
+ owner: { kind: "application" },
sourceId: "src-noop",
},
],
@@ -458,6 +460,7 @@ describe("refreshSessionFromTurnAgent", () => {
kind: "authored-tool",
logicalPath: "tools/echo",
name: "echo",
+ owner: { kind: "application" },
sourceId: "src-echo",
},
],
diff --git a/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts b/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts
index ef2610cdf..690f0a5a0 100644
--- a/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts
+++ b/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts
@@ -99,7 +99,7 @@ function buildSerializedContext(): Record<string, unknown> {
describe("settleCancelledTurnStep handle store", () => {
it("parks abandoned running handles as cancelled and keeps parked ones", async () => {
- const runtime = createTestRuntime({ agent: { name: "settle-cancel-handles" } });
+ const runtime = await createTestRuntime({ agent: { name: "settle-cancel-handles" } });
await runtime.run(async () => {
const result = await settleCancelledTurnStep({
diff --git a/packages/eve/src/execution/subagent-adapter.test.ts b/packages/eve/src/execution/subagent-adapter.test.ts
index bf3d54ebd..16615deaf 100644
--- a/packages/eve/src/execution/subagent-adapter.test.ts
+++ b/packages/eve/src/execution/subagent-adapter.test.ts
@@ -5,7 +5,7 @@ import { buildSessionHandle } from "#channel/session.js";
import { type SubagentAdapterState } from "#execution/subagent-adapter-state.js";
import { ContextContainer } from "#context/container.js";
import { ContinuationTokenKey, SessionIdKey } from "#context/keys.js";
-import type { InputRequest } from "#runtime/input/types.js";
+import type { InputRequest } from "#shared/input.js";
import { SUBAGENT_ADAPTER } from "#execution/subagent-adapter.js";
const SUBAGENT_INPUT_REQUESTED = SUBAGENT_ADAPTER["input.requested"];
diff --git a/packages/eve/src/execution/subagent-hitl-proxy.integration.test.ts b/packages/eve/src/execution/subagent-hitl-proxy.integration.test.ts
index 6a1fda576..fd4257c90 100644
--- a/packages/eve/src/execution/subagent-hitl-proxy.integration.test.ts
+++ b/packages/eve/src/execution/subagent-hitl-proxy.integration.test.ts
@@ -12,7 +12,7 @@ import { serializeContext } from "#context/serialize.js";
import { hasProxyInputRequests, upsertProxyInputRequests } from "#harness/proxy-input-requests.js";
import type { HarnessEmitFn, HarnessSession } from "#harness/types.js";
import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
-import type { InputRequest } from "#runtime/input/types.js";
+import type { InputRequest } from "#shared/input.js";
import { createRuntimeAdapterRegistry } from "#runtime/channels/registry.js";
import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
import { createEmptyHookRegistry } from "#runtime/hooks/registry.js";
diff --git a/packages/eve/src/execution/subagent-hitl-proxy.ts b/packages/eve/src/execution/subagent-hitl-proxy.ts
index 8fce34f07..db4135cf6 100644
--- a/packages/eve/src/execution/subagent-hitl-proxy.ts
+++ b/packages/eve/src/execution/subagent-hitl-proxy.ts
@@ -12,7 +12,7 @@ import type { ProxyInputRequest } from "#harness/proxy-input-requests.js";
import type { HarnessEmitFn, HarnessSession, SessionStateMap } from "#harness/types.js";
import { createInputRequestedEvent } from "#protocol/message.js";
import type { RunMode } from "#shared/run-mode.js";
-import type { InputResponse } from "#runtime/input/types.js";
+import type { InputResponse } from "#shared/input.js";
import { SESSION_LIMIT_STOP_OPTION_ID } from "#harness/session-limit-continuation.js";
// ---------------------------------------------------------------------------
diff --git a/packages/eve/src/execution/subagent-start-local.ts b/packages/eve/src/execution/subagent-start-local.ts
index 63cbdd15e..2032419d1 100644
--- a/packages/eve/src/execution/subagent-start-local.ts
+++ b/packages/eve/src/execution/subagent-start-local.ts
@@ -11,7 +11,7 @@ import {
rejectAgentEffect,
} from "#harness/handles/transitions.js";
import { createLogger, logError } from "#internal/logging.js";
-import type { RuntimeSubagentCallActionRequest } from "#runtime/actions/types.js";
+import type { RuntimeSubagentCallActionRequest } from "#shared/action-types.js";
import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
import { toErrorMessage } from "#shared/errors.js";
diff --git a/packages/eve/src/execution/subagent-start-remote.ts b/packages/eve/src/execution/subagent-start-remote.ts
index 63cfbc5af..ae82e4648 100644
--- a/packages/eve/src/execution/subagent-start-remote.ts
+++ b/packages/eve/src/execution/subagent-start-remote.ts
@@ -12,7 +12,7 @@ import {
rejectAgentEffect,
} from "#harness/handles/transitions.js";
import { createLogger, logError } from "#internal/logging.js";
-import type { RuntimeRemoteAgentCallActionRequest } from "#runtime/actions/types.js";
+import type { RuntimeRemoteAgentCallActionRequest } from "#shared/action-types.js";
import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
const log = createLogger("execution.subagent-start-remote");
diff --git a/packages/eve/src/execution/subagent-tool.test.ts b/packages/eve/src/execution/subagent-tool.test.ts
index b999f34a1..a5663c73e 100644
--- a/packages/eve/src/execution/subagent-tool.test.ts
+++ b/packages/eve/src/execution/subagent-tool.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
import { SUBAGENT_ADAPTER_KIND } from "#execution/subagent-adapter-state.js";
import type { HarnessSession } from "#harness/types.js";
-import type { RuntimeSubagentCallActionRequest } from "#runtime/actions/types.js";
+import type { RuntimeSubagentCallActionRequest } from "#shared/action-types.js";
import { buildSubagentRunInput } from "#execution/subagent-tool.js";
type BuildSubagentRunInput = Parameters<typeof buildSubagentRunInput>[0];
diff --git a/packages/eve/src/execution/subagent-tool.ts b/packages/eve/src/execution/subagent-tool.ts
index a4887a304..9dfe23a23 100644
--- a/packages/eve/src/execution/subagent-tool.ts
+++ b/packages/eve/src/execution/subagent-tool.ts
@@ -12,7 +12,7 @@ import type {
SessionTraceContext,
} from "#channel/types.js";
import type { HarnessSession } from "#harness/types.js";
-import type { RuntimeSubagentCallActionRequest } from "#runtime/actions/types.js";
+import type { RuntimeSubagentCallActionRequest } from "#shared/action-types.js";
import { mintSubagentContinuationToken } from "#execution/session.js";
import { resolveSubagentDepth } from "#harness/subagent-depth.js";
import { resolveRemainingSessionTokenLimits } from "#harness/subagent-token-budget.js";
diff --git a/packages/eve/src/execution/subagent-usage-span.test.ts b/packages/eve/src/execution/subagent-usage-span.test.ts
index 9c5f2e7ed..dd221e00f 100644
--- a/packages/eve/src/execution/subagent-usage-span.test.ts
+++ b/packages/eve/src/execution/subagent-usage-span.test.ts
@@ -1,7 +1,7 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { recordSubagentUsageSpans } from "#execution/subagent-usage-span.js";
-import type { RuntimeActionResult, RuntimeSubagentChildResult } from "#runtime/actions/types.js";
+import type { RuntimeActionResult, RuntimeSubagentChildResult } from "#shared/action-types.js";
const startSpanMock = vi.fn();
const endSpanMock = vi.fn();
diff --git a/packages/eve/src/execution/subagent-usage-span.ts b/packages/eve/src/execution/subagent-usage-span.ts
index 6cddd60fd..8f5280f47 100644
--- a/packages/eve/src/execution/subagent-usage-span.ts
+++ b/packages/eve/src/execution/subagent-usage-span.ts
@@ -1,7 +1,7 @@
import { trace } from "#compiled/@opentelemetry/api/index.js";
import { createLogger } from "#internal/logging.js";
-import type { RuntimeActionResult } from "#runtime/actions/types.js";
+import type { RuntimeActionResult } from "#shared/action-types.js";
const log = createLogger("execution.subagent-usage-span");
diff --git a/packages/eve/src/runtime/task-input-response-route.ts b/packages/eve/src/execution/task-input-response-route.ts
similarity index 75%
rename from packages/eve/src/runtime/task-input-response-route.ts
rename to packages/eve/src/execution/task-input-response-route.ts
index c150cd039..e461731a8 100644
--- a/packages/eve/src/runtime/task-input-response-route.ts
+++ b/packages/eve/src/execution/task-input-response-route.ts
@@ -1,29 +1,7 @@
import { readTaskInputTargetToken } from "#execution/task-input-capability.js";
import { resumeSessionInbox } from "#execution/wire/session-inbox-resume.js";
-import { EVE_TASK_INPUT_ROUTE_PATTERN } from "#protocol/routes.js";
-import type { ChannelMethod, RouteContext } from "#public/definitions/channel.js";
-import type { InputResponse } from "#runtime/input/types.js";
-import type { ResolvedChannelDefinition } from "#runtime/types.js";
-
-const NAME = "eve/v1/task-input/post";
-
-export function getTaskInputResponseChannelDefinitions(): readonly ResolvedChannelDefinition[] {
- return [
- {
- fetch: handleTaskInputResponseRequest,
- logicalPath: `framework://channels/${NAME}`,
- method: "POST" satisfies ChannelMethod,
- name: NAME,
- sourceId: "eve:framework:task-input-post",
- sourceKind: "module",
- urlPath: EVE_TASK_INPUT_ROUTE_PATTERN,
- },
- ];
-}
-
-export function getTaskInputResponseChannelNames(): ReadonlySet<string> {
- return new Set([NAME]);
-}
+import type { RouteContext } from "#public/definitions/channel.js";
+import type { InputResponse } from "#shared/input.js";
export async function handleTaskInputResponseRequest(
request: Request,
diff --git a/packages/eve/src/execution/task-model-retry.integration.test.ts b/packages/eve/src/execution/task-model-retry.integration.test.ts
index 5e55077ac..fa2109cb3 100644
--- a/packages/eve/src/execution/task-model-retry.integration.test.ts
+++ b/packages/eve/src/execution/task-model-retry.integration.test.ts
@@ -7,7 +7,7 @@ import { taskModelRetryFixtureWorkflow } from "#internal/testing/task-model-retr
describe("task model retry integration", () => {
it("retries a recoverable task error from the committed session snapshot", async () => {
- const runtime = createTestRuntime({ agent: { name: "task-model-retry-fixture" } });
+ const runtime = await createTestRuntime({ agent: { name: "task-model-retry-fixture" } });
await runtime.run(async () => {
const run = await start(taskModelRetryFixtureWorkflow, [{ failThroughAttempt: 1 }]);
@@ -32,7 +32,9 @@ describe("task model retry integration", () => {
});
it("notifies the parent once after Workflow exhausts persistent failures", async () => {
- const runtime = createTestRuntime({ agent: { name: "task-model-retry-exhaustion-fixture" } });
+ const runtime = await createTestRuntime({
+ agent: { name: "task-model-retry-exhaustion-fixture" },
+ });
await runtime.run(async () => {
const run = await start(taskModelRetryFixtureWorkflow, [
diff --git a/packages/eve/src/execution/tasks/child/update.ts b/packages/eve/src/execution/tasks/child/update.ts
index 7777acef3..702e96adb 100644
--- a/packages/eve/src/execution/tasks/child/update.ts
+++ b/packages/eve/src/execution/tasks/child/update.ts
@@ -7,7 +7,7 @@ import {
} from "#execution/subagent-adapter-state.js";
import { createTaskControlError } from "#execution/tasks/parent/control-shared.js";
import { resumeHook } from "#internal/workflow/runtime.js";
-import type { RuntimeActionResult, RuntimeToolCallActionRequest } from "#runtime/actions/types.js";
+import type { RuntimeActionResult, RuntimeToolCallActionRequest } from "#shared/action-types.js";
import { readTaskIdFromInboxToken } from "#tasks/task-id.js";
import type { TaskInboundUpdate } from "#tasks/types.js";
diff --git a/packages/eve/src/execution/tasks/parent/continuation-dispatch.ts b/packages/eve/src/execution/tasks/parent/continuation-dispatch.ts
index 8904577b8..a7bc56c96 100644
--- a/packages/eve/src/execution/tasks/parent/continuation-dispatch.ts
+++ b/packages/eve/src/execution/tasks/parent/continuation-dispatch.ts
@@ -16,7 +16,7 @@ import {
} from "#execution/tasks/parent/delegate.js";
import { describeTaskAgent } from "#execution/tasks/parent/agent-identity.js";
import { AGENT_BUSY } from "#harness/agent-handle-errors.js";
-import type { RuntimeSubagentDispatchFailure } from "#runtime/actions/types.js";
+import type { RuntimeSubagentDispatchFailure } from "#shared/action-types.js";
import type { JsonValue } from "#shared/json.js";
export type PersistedContinuationTask = Awaited<ReturnType<typeof settleDelegatedDispatch>>;
diff --git a/packages/eve/src/execution/tasks/parent/control-shared.ts b/packages/eve/src/execution/tasks/parent/control-shared.ts
index ad475e3e7..d9eca1042 100644
--- a/packages/eve/src/execution/tasks/parent/control-shared.ts
+++ b/packages/eve/src/execution/tasks/parent/control-shared.ts
@@ -2,7 +2,7 @@ import type { RuntimeSession } from "#execution/agent-handle-dispatch.js";
import { readLatestTaskView } from "#execution/tasks/parent/run-parent.js";
import { isTaskWorkflowTargetGone } from "#execution/tasks/workflow-target.js";
import { getAgentHandleStore, type AgentHandle } from "#harness/handles/store.js";
-import type { RuntimeActionResult, RuntimeToolCallActionRequest } from "#runtime/actions/types.js";
+import type { RuntimeActionResult, RuntimeToolCallActionRequest } from "#shared/action-types.js";
import { taskViewsToJson } from "#tasks/json.js";
import {
findSessionTaskEntry,
diff --git a/packages/eve/src/execution/tasks/parent/delegate.ts b/packages/eve/src/execution/tasks/parent/delegate.ts
index 1fd92a727..3ca30f179 100644
--- a/packages/eve/src/execution/tasks/parent/delegate.ts
+++ b/packages/eve/src/execution/tasks/parent/delegate.ts
@@ -15,7 +15,7 @@ import {
} from "#execution/tasks/parent/run-parent.js";
import { sessionCommandHookToken } from "#execution/session-command-token.js";
import { deriveAgentOperationId } from "#harness/handles/operation-id.js";
-import type { RuntimeSubagentChildResult } from "#runtime/actions/types.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 { recordSessionTask } from "#tasks/session-index.js";
diff --git a/packages/eve/src/execution/tasks/parent/dispatch-task-step.ts b/packages/eve/src/execution/tasks/parent/dispatch-task-step.ts
index 9fda6c9da..8666d8138 100644
--- a/packages/eve/src/execution/tasks/parent/dispatch-task-step.ts
+++ b/packages/eve/src/execution/tasks/parent/dispatch-task-step.ts
@@ -42,7 +42,7 @@ import {
settleTaskDispatchError,
type PersistedContinuationTask,
} from "#execution/tasks/parent/continuation-dispatch.js";
-import type { RuntimeActionResult } from "#runtime/actions/types.js";
+import type { RuntimeActionResult } from "#shared/action-types.js";
export async function dispatchTaskStep(
input: RuntimeActionDispatchInput,
diff --git a/packages/eve/src/execution/tasks/parent/dispatch.test.ts b/packages/eve/src/execution/tasks/parent/dispatch.test.ts
index 67098dbbb..435bcee10 100644
--- a/packages/eve/src/execution/tasks/parent/dispatch.test.ts
+++ b/packages/eve/src/execution/tasks/parent/dispatch.test.ts
@@ -9,7 +9,7 @@ import { executeTaskControlAction } from "#execution/tasks/parent/dispatch.js";
import { readLatestTaskView, sendTaskCommand } from "#execution/tasks/parent/run-parent.js";
import { requestWorkflowTurnCancellation } from "#execution/workflow-runtime.js";
import { AGENT_HANDLES_STATE_KEY } from "#harness/handles/store.js";
-import type { RuntimeToolCallActionRequest } from "#runtime/actions/types.js";
+import type { RuntimeToolCallActionRequest } from "#shared/action-types.js";
import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
import { SESSION_TASKS_STATE_KEY } from "#tasks/session-index.js";
diff --git a/packages/eve/src/execution/tasks/parent/dispatch.ts b/packages/eve/src/execution/tasks/parent/dispatch.ts
index 132131e8d..4f718519f 100644
--- a/packages/eve/src/execution/tasks/parent/dispatch.ts
+++ b/packages/eve/src/execution/tasks/parent/dispatch.ts
@@ -21,13 +21,13 @@ import type {
RuntimeActionRequest,
RuntimeActionResult,
RuntimeToolCallActionRequest,
-} from "#runtime/actions/types.js";
+} from "#shared/action-types.js";
import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
import {
TASK_CANCEL_TOOL_NAME,
TASK_CONTROL_TOOL_NAMES,
TASK_UPDATE_TOOL_NAME,
-} from "#runtime/framework-tools/tasks.js";
+} from "#shared/task-tool.js";
import type { SessionTaskIndexEntry } from "#tasks/session-index.js";
import {
isTerminalTaskStatus,
diff --git a/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.ts b/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.ts
index 3c96e3ba4..a0876fcc9 100644
--- a/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.ts
+++ b/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.ts
@@ -11,7 +11,7 @@ import {
} from "#harness/proxy-input-requests.js";
import { getAgentHandleStore } from "#harness/handles/store.js";
import { removeTaskAgentAddressFromState } from "#harness/handles/transitions.js";
-import { isInputRequest } from "#runtime/input/types.js";
+import { isInputRequest } from "#shared/input.js";
import { cacheTerminalTaskView, findSessionTaskEntry } from "#tasks/session-index.js";
import { createEveTaskInputRoutePath } from "#protocol/routes.js";
import { isTerminalTaskStatus, readSubagentTaskMetadata, type TaskView } from "#tasks/types.js";
diff --git a/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.ts b/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.ts
index f3518605c..2f907e8c1 100644
--- a/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.ts
+++ b/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.ts
@@ -45,15 +45,31 @@ describe("background subagent tool execution", () => {
});
it("runs concurrent local and remote defineTool calls as independent durable tasks", async () => {
- const runtime = createTestRuntime({ agent: { name: "background-subagent" } });
+ const runtime = await createTestRuntime({ agent: { name: "background-subagent" } });
await runtime.run(async () => {
const remoteNode = {
+ backing: {
+ kind: "resource",
+ sourcePath: "/virtual/eve-memory-app/agent/subagents/reviewer.ts",
+ },
+ binding: runtime.manifest.bindings["subagents/reviewer.ts"] ?? {
+ backing: {
+ kind: "programmatic",
+ moduleId: "subagents/reviewer.ts",
+ registryId: "memory:background-subagent",
+ revision: "memory:background-subagent",
+ },
+ logicalPath: "subagents/reviewer.ts",
+ owner: { kind: "application" },
+ },
description: "Remote reviewer",
entryPath: "/virtual/eve-memory-app/agent/subagents/reviewer.ts",
logicalPath: "subagents/reviewer.ts",
name: "reviewer",
nodeId: "remote/reviewer",
+ owner: { kind: "application" },
+ parentNodeId: ROOT_COMPILED_AGENT_NODE_ID,
path: "/eve/v1/session",
rootPath: "/virtual/eve-memory-app/agent",
sourceId: "subagents/reviewer.ts",
diff --git a/packages/eve/src/execution/tool-auth.integration.test.ts b/packages/eve/src/execution/tool-auth.integration.test.ts
index 8c9f05c89..66a229976 100644
--- a/packages/eve/src/execution/tool-auth.integration.test.ts
+++ b/packages/eve/src/execution/tool-auth.integration.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { buildApprovalResponseAuth, createToolExecuteWithAuth } from "#execution/tool-auth.js";
+import { buildApprovalResponseAuth } from "#execution/tool-auth.js";
import { evictScopedToken, resolveScopedToken } from "#runtime/connections/scoped-authorization.js";
import { loadContext } from "#context/container.js";
import { AuthKey, SessionIdKey } from "#context/keys.js";
@@ -16,7 +16,7 @@ import type {
AuthorizationDefinition,
ConnectionPrincipal,
TokenResult,
-} from "#runtime/connections/types.js";
+} from "#shared/connection-types.js";
import type { ResolvedToolDefinition } from "#runtime/types.js";
/**
@@ -65,18 +65,24 @@ function authoredTool(input: {
const logicalPath = `tools/${input.name}.ts`;
return {
description: `${input.name} auth tool.`,
- execute: createToolExecuteWithAuth({
- execute: input.execute as (toolInput: unknown, ctx: unknown) => unknown,
- scope: input.name,
- }),
+ execute: (toolInput, runtimeContext) =>
+ input.execute(toolInput, expectToolContext(runtimeContext)),
inputSchema: null,
logicalPath,
name: input.name,
+ owner: { kind: "application" },
sourceId: logicalPath,
sourceKind: "module",
};
}
+function expectToolContext(value: unknown): ToolContext {
+ if (typeof value !== "object" || value === null || !("getToken" in value)) {
+ throw new Error("Expected the authored tool context.");
+ }
+ return value as ToolContext;
+}
+
describe("approval response authorization", () => {
it("keeps distinct connector tokens separate within one response policy", async () => {
const github: AuthorizationDefinition = {
@@ -93,7 +99,7 @@ describe("approval response authorization", () => {
return { token: "linear-token" };
},
};
- const runtime = createTestRuntime({ tools: [] });
+ const runtime = await createTestRuntime({ tools: [] });
const tokens = await runtime.runAsSession(undefined, async () => {
const auth = buildApprovalResponseAuth({
@@ -123,7 +129,7 @@ describe("approval response authorization", () => {
return { token: "bound-responder-token" };
},
};
- const runtime = createTestRuntime({ tools: [] });
+ const runtime = await createTestRuntime({ tools: [] });
await runtime.runAsSession(undefined, async () => {
loadContext().set(AuthKey, {
@@ -172,7 +178,7 @@ describe("tool-hosted authorization", () => {
return { first: first.token, second: second.token };
},
});
- const runtime = createTestRuntime({ tools: [tool] });
+ const runtime = await createTestRuntime({ tools: [tool] });
const result = await runtime.runAsSession(undefined, async () => runtime.executeTool(tool, {}));
@@ -188,7 +194,7 @@ describe("tool-hosted authorization", () => {
return { callId: ctx.callId, toolName: ctx.toolName };
},
});
- const runtime = createTestRuntime({ tools: [tool] });
+ const runtime = await createTestRuntime({ tools: [tool] });
const result = await runtime.runAsSession(undefined, async () => runtime.executeTool(tool, {}));
@@ -213,7 +219,7 @@ describe("tool-hosted authorization", () => {
return { first: first.token, second: second.token };
},
});
- const runtime = createTestRuntime({ tools: [tool] });
+ const runtime = await createTestRuntime({ tools: [tool] });
const result = await runtime.runAsSession(undefined, async () => runtime.executeTool(tool, {}));
@@ -242,7 +248,7 @@ describe("tool-hosted authorization", () => {
return { github: github.token, linear: linear.token };
},
});
- const runtime = createTestRuntime({ tools: [tool] });
+ const runtime = await createTestRuntime({ tools: [tool] });
const result = await runtime.runAsSession(undefined, async () => runtime.executeTool(tool, {}));
@@ -269,7 +275,7 @@ describe("tool-hosted authorization", () => {
await ctx.getToken(linearAuth);
},
});
- const runtime = createTestRuntime({ tools: [tool] });
+ const runtime = await createTestRuntime({ tools: [tool] });
await expect(
runtime.runAsSession(undefined, async () => runtime.executeTool(tool, {})),
@@ -283,7 +289,7 @@ describe("tool-hosted authorization", () => {
return await (ctx.getToken as () => Promise<TokenResult>)();
},
});
- const runtime = createTestRuntime({ tools: [tool] });
+ const runtime = await createTestRuntime({ tools: [tool] });
await expect(
runtime.runAsSession(undefined, async () => runtime.executeTool(tool, {})),
@@ -310,7 +316,7 @@ describe("tool-hosted authorization", () => {
return await ctx.getToken(inlineAuth, { displayName: "Linear" });
},
});
- const runtime = createTestRuntime({ tools: [tool] });
+ const runtime = await createTestRuntime({ tools: [tool] });
const result = await runtime.runAsSession(
{ sessionId: "session_inline_auth_park" },
@@ -352,7 +358,7 @@ describe("tool-hosted authorization", () => {
return await ctx.getToken(inlineAuth);
},
});
- const runtime = createTestRuntime({ tools: [tool] });
+ const runtime = await createTestRuntime({ tools: [tool] });
const result = await runtime.runAsSession(
{ sessionId: "session_connect_callback" },
@@ -390,7 +396,7 @@ describe("tool-hosted authorization", () => {
return await ctx.getToken(auth);
},
});
- const runtime = createTestRuntime({ tools: [tool] });
+ const runtime = await createTestRuntime({ tools: [tool] });
const result = await runtime.runAsSession({ sessionId: "session_auth_park" }, async () => {
seedUserPrincipal();
@@ -429,7 +435,7 @@ describe("tool-hosted authorization", () => {
return await ctx.getToken(auth);
},
});
- const runtime = createTestRuntime({ tools: [tool] });
+ const runtime = await createTestRuntime({ tools: [tool] });
const result = await runtime.runAsSession({ sessionId: "session_display_name" }, async () => {
seedUserPrincipal();
@@ -465,7 +471,7 @@ describe("tool-hosted authorization", () => {
return await ctx.getToken(auth);
},
});
- const runtime = createTestRuntime({ tools: [tool] });
+ const runtime = await createTestRuntime({ tools: [tool] });
const result = await runtime.runAsSession(
{ sessionId: "session_display_name_strategy" },
@@ -500,7 +506,7 @@ describe("tool-hosted authorization", () => {
ctx.requireAuth(auth);
},
});
- const runtime = createTestRuntime({ tools: [tool] });
+ const runtime = await createTestRuntime({ tools: [tool] });
const result = await runtime.runAsSession({ sessionId: "session_require_auth" }, async () => {
seedUserPrincipal();
@@ -535,7 +541,7 @@ describe("tool-hosted authorization", () => {
return await ctx.getToken(auth);
},
});
- const runtime = createTestRuntime({ tools: [tool] });
+ const runtime = await createTestRuntime({ tools: [tool] });
const result = await runtime.runAsSession({ sessionId: "session_resume" }, async () => {
seedUserPrincipal();
@@ -581,7 +587,7 @@ describe("tool-hosted authorization", () => {
return await ctx.getToken(inlineAuth);
},
});
- const runtime = createTestRuntime({ tools: [tool] });
+ const runtime = await createTestRuntime({ tools: [tool] });
const result = await runtime.runAsSession({ sessionId: "session_inline_resume" }, async () => {
seedUserPrincipal();
@@ -630,7 +636,7 @@ describe("tool-hosted authorization", () => {
ctx.requireAuth(inlineAuth);
},
});
- const runtime = createTestRuntime({ tools: [tool] });
+ const runtime = await createTestRuntime({ tools: [tool] });
const result = await runtime.runAsSession({ sessionId: "session_inline_require" }, async () => {
seedUserPrincipal();
@@ -670,7 +676,7 @@ describe("tool-hosted authorization", () => {
ctx.requireAuth(auth);
},
});
- const runtime = createTestRuntime({ tools: [tool] });
+ const runtime = await createTestRuntime({ tools: [tool] });
const error = await runtime
.runAsSession({ sessionId: "session_loop_guard" }, async () => {
@@ -719,7 +725,7 @@ describe("tool-hosted authorization", () => {
ctx.requireAuth(inlineAuth);
},
});
- const runtime = createTestRuntime({ tools: [tool] });
+ const runtime = await createTestRuntime({ tools: [tool] });
const error = await runtime
.runAsSession({ sessionId: "session_inline_loop_guard" }, async () => {
@@ -757,7 +763,7 @@ describe("tool-hosted authorization", () => {
},
};
const scoped = { authorization: auth, connection: { url: "" }, scope: "list_groups" };
- const runtime = createTestRuntime({ tools: [] });
+ const runtime = await createTestRuntime({ tools: [] });
const tokens = await runtime.runAsSession({ sessionId: "session_evict" }, async () => {
seedUserPrincipal();
@@ -788,7 +794,7 @@ describe("tool-hosted authorization", () => {
},
};
const scoped = { authorization: auth, connection: { url: "" }, scope: "list_groups" };
- const runtime = createTestRuntime({ tools: [] });
+ const runtime = await createTestRuntime({ tools: [] });
await runtime.runAsSession({ sessionId: "session_evict_cascade" }, async () => {
seedUserPrincipal();
@@ -819,7 +825,7 @@ describe("tool-hosted authorization", () => {
return await ctx.getToken(auth);
},
});
- const runtime = createTestRuntime({ tools: [tool] });
+ const runtime = await createTestRuntime({ tools: [tool] });
// No CallbackBaseUrlKey set → getHookUrl returns undefined → no park
// signal. The interactive path must NOT leak the raw Required into the
@@ -851,7 +857,7 @@ describe("tool-hosted authorization", () => {
return await ctx.getToken(auth);
},
});
- const runtime = createTestRuntime({ tools: [tool] });
+ const runtime = await createTestRuntime({ tools: [tool] });
// Non-interactive strategies have no consent flow to park on, so the
// model should see the original failure.
diff --git a/packages/eve/src/execution/tool-auth.ts b/packages/eve/src/execution/tool-auth.ts
index 877e4184f..b4ecfde25 100644
--- a/packages/eve/src/execution/tool-auth.ts
+++ b/packages/eve/src/execution/tool-auth.ts
@@ -3,8 +3,7 @@
* providers inline with {@link ToolContext.getToken} and
* {@link ToolContext.requireAuth}.
*
- * Mirrors the connection authorization flow (see
- * `runtime/framework-tools/connection-search-dynamic.ts`) but scopes the
+ * Mirrors the connection authorization flow used by connection search but scopes the
* per-step token cache and framework-owned callback URL by the tool's
* path-derived name and provider key instead of a connection name. All the shared
* machinery — principal resolution, cache reads/writes, the park/resume
@@ -27,8 +26,8 @@ import {
type AuthorizationDefinition,
supportsInteractiveAuthorization,
type TokenResult,
-} from "#runtime/connections/types.js";
-import { normalizeAuthorizationSpec } from "#runtime/connections/validate-authorization.js";
+} from "#shared/connection-types.js";
+import { normalizeAuthorizationSpec } from "#shared/validate-authorization.js";
import {
completeScopedAuthorization,
evictScopedToken,
diff --git a/packages/eve/src/runtime/framework-tools/connection-search-dynamic.test.ts b/packages/eve/src/execution/tools/connection-search.test.ts
similarity index 72%
rename from packages/eve/src/runtime/framework-tools/connection-search-dynamic.test.ts
rename to packages/eve/src/execution/tools/connection-search.test.ts
index 2ce85b3c6..a13c95c6b 100644
--- a/packages/eve/src/runtime/framework-tools/connection-search-dynamic.test.ts
+++ b/packages/eve/src/execution/tools/connection-search.test.ts
@@ -10,9 +10,9 @@ import {
} from "#harness/authorization.js";
import { ConnectionAuthorizationRequiredError } from "#public/connections/errors.js";
import type { ToolContext } from "#public/definitions/tool.js";
-import type { ConnectionRegistry, ConnectionToolMetadata } from "#runtime/connections/types.js";
-import { extractDiscoveredTools } from "#runtime/framework-tools/connection-search-dynamic.js";
-import { getFrameworkDynamicToolResolvers } from "#runtime/framework-tools/index.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 type { ResolvedConnectionDefinition } from "#runtime/types.js";
import {
isBrandedToolEntry,
@@ -21,9 +21,6 @@ import {
} from "#shared/dynamic-tool-definition.js";
import { readDurableDynamicToolCallbacks } from "#shared/durable-dynamic-tool-callbacks.js";
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-type Msg = any;
-
function connection(name: string): ResolvedConnectionDefinition {
return {
connectionName: name,
@@ -58,7 +55,7 @@ async function executeConnectionSearch(
}
function getConnectionSearchResolver() {
- return getFrameworkDynamicToolResolvers()[0]!;
+ return connectionSearch;
}
function registry(input: {
@@ -110,46 +107,41 @@ describe("connection dynamic tools", () => {
const linear = connection("linear");
const connectionRegistry = registry({
connections: [linear],
- loadTools: { linear: async () => [] },
- });
- const messages: Msg[] = [
- {
- role: "tool",
- content: [
+ loadTools: {
+ linear: async () => [
{
- type: "tool-result",
- toolCallId: "call-1",
- toolName: "connection_search",
- output: [
- {
- connection: "linear",
- description: "List issues",
- inputSchema: { type: "object" },
- qualifiedName: "linear__list_issues",
- tool: "list_issues",
- },
- ],
+ description: "List issues",
+ inputSchema: { type: "object" },
+ name: "list_issues",
},
],
},
- ];
+ });
const ctx = new ContextContainer();
ctx.set(ConnectionRegistryKey, connectionRegistry);
const resolver = getConnectionSearchResolver();
const resolve = resolver.events["step.started"]!;
const tools = await contextStorage.run(ctx, async () => {
+ const initial = (await resolve(
+ {},
+ {
+ channel: {},
+ messages: [],
+ session: { auth: { current: null, initiator: null }, id: "test-session" },
+ },
+ )) as DynamicToolSet;
+ await initial["connection_search"]!.execute({ keywords: "list issues" }, {} as ToolContext);
return (await resolve(
{},
{
channel: {},
- messages,
+ messages: [],
session: { auth: { current: null, initiator: null }, id: "test-session" },
},
)) as DynamicToolSet;
});
- expect(resolver.eventNames).toEqual(["step.started"]);
expect(Object.keys(tools)).toEqual(["connection_search", "linear__list_issues"]);
expect(Object.values(tools).every(isBrandedToolEntry)).toBe(true);
});
@@ -446,150 +438,3 @@ describe("connection_search", () => {
expect(isAuthorizationSignal(result)).toBe(true);
});
});
-
-describe("extractDiscoveredTools", () => {
- it("extracts tools from raw array output", () => {
- const messages: Msg[] = [
- { role: "user", content: [{ type: "text", text: "search" }] },
- {
- role: "tool",
- content: [
- {
- type: "tool-result",
- toolCallId: "call-1",
- toolName: "connection_search",
- output: [
- {
- connection: "linear",
- tool: "list_issues",
- qualifiedName: "linear__list_issues",
- description: "List issues",
- inputSchema: { type: "object" },
- outputSchema: { type: "object" },
- },
- ],
- },
- ],
- },
- ];
-
- const result = extractDiscoveredTools(messages);
- expect(result).toHaveLength(1);
- expect(result[0]!.qualifiedName).toBe("linear__list_issues");
- expect(result[0]!.connection).toBe("linear");
- expect(result[0]!.tool).toBe("list_issues");
- expect(result[0]!.outputSchema).toEqual({ type: "object" });
- });
-
- it("extracts tools from ToolResultOutput json wrapper", () => {
- const messages: Msg[] = [
- {
- role: "tool",
- content: [
- {
- type: "tool-result",
- toolCallId: "call-1",
- toolName: "connection_search",
- output: {
- type: "json",
- value: [
- {
- connection: "linear",
- tool: "list_issues",
- qualifiedName: "linear__list_issues",
- description: "List issues",
- inputSchema: { type: "object" },
- },
- ],
- },
- },
- ],
- },
- ];
-
- const result = extractDiscoveredTools(messages);
- expect(result).toHaveLength(1);
- expect(result[0]!.qualifiedName).toBe("linear__list_issues");
- });
-
- it("returns empty for no tool results", () => {
- const messages: Msg[] = [{ role: "user", content: [{ type: "text", text: "hello" }] }];
- expect(extractDiscoveredTools(messages)).toHaveLength(0);
- });
-
- it("deduplicates by qualifiedName (latest wins)", () => {
- const messages: Msg[] = [
- {
- role: "tool",
- content: [
- {
- type: "tool-result",
- toolCallId: "call-1",
- toolName: "connection_search",
- output: [
- {
- connection: "linear",
- tool: "list_issues",
- qualifiedName: "linear__list_issues",
- description: "Old description",
- },
- ],
- },
- ],
- },
- {
- role: "tool",
- content: [
- {
- type: "tool-result",
- toolCallId: "call-2",
- toolName: "connection_search",
- output: [
- {
- connection: "linear",
- tool: "list_issues",
- qualifiedName: "linear__list_issues",
- description: "New description",
- },
- ],
- },
- ],
- },
- ];
-
- const result = extractDiscoveredTools(messages);
- expect(result).toHaveLength(1);
- expect(result[0]!.description).toBe("New description");
- });
-
- it("skips items without tool or qualifiedName", () => {
- const messages: Msg[] = [
- {
- role: "tool",
- content: [
- {
- type: "tool-result",
- toolCallId: "call-1",
- toolName: "connection_search",
- output: [
- {
- connection: "linear",
- description: "No tool or qualifiedName",
- },
- {
- connection: "linear",
- tool: "list_issues",
- qualifiedName: "linear__list_issues",
- description: "Valid",
- },
- ],
- },
- ],
- },
- ];
-
- const result = extractDiscoveredTools(messages);
- expect(result).toHaveLength(1);
- expect(result[0]!.description).toBe("Valid");
- });
-});
diff --git a/packages/eve/src/runtime/framework-tools/connection-search-dynamic.ts b/packages/eve/src/execution/tools/connection-search.ts
similarity index 77%
rename from packages/eve/src/runtime/framework-tools/connection-search-dynamic.ts
rename to packages/eve/src/execution/tools/connection-search.ts
index 20bdf4b73..61802ba6f 100644
--- a/packages/eve/src/runtime/framework-tools/connection-search-dynamic.ts
+++ b/packages/eve/src/execution/tools/connection-search.ts
@@ -14,7 +14,7 @@ import {
isConnectionAuthorizationFailedError,
isConnectionAuthorizationRequiredError,
} from "#public/connections/errors.js";
-import { defineDynamic, defineTool } from "#public/definitions/tool.js";
+import { defineTool } from "#public/definitions/tool.js";
import type { ToolContext } from "#public/definitions/tool.js";
import {
resolveApprovalPolicy,
@@ -32,15 +32,14 @@ import {
stampChallengeDisplayName,
} from "#runtime/connections/scoped-authorization.js";
import {
- type ConnectionRegistry,
type ConnectionToolMetadata,
type InteractiveAuthorizationDefinition,
supportsInteractiveAuthorization,
-} from "#runtime/connections/types.js";
+} from "#shared/connection-types.js";
+import type { ConnectionRegistry } from "#runtime/connections/registry-types.js";
import type { ResolvedConnectionDefinition } from "#runtime/types.js";
import { createLogger } from "#internal/logging.js";
import { toError } from "#shared/errors.js";
-import type { ModelMessage } from "ai";
import { ConnectionRegistryKey } from "#context/providers/connection-key.js";
@@ -363,44 +362,6 @@ async function executeConnectionSearch(
return summaries;
}
-/**
- * Extracts connection search results from conversation history.
- * Scans tool-result messages for `connection_search` results and
- * returns deduplicated tool metadata (latest result wins per qualifiedName).
- */
-export function extractDiscoveredTools(
- messages: readonly ModelMessage[],
-): ConnectionSearchResultItem[] {
- const byQualifiedName = new Map<string, ConnectionSearchResultItem>();
-
- for (const msg of messages) {
- if (msg.role !== "tool") continue;
- const parts = msg.content as Array<{
- type: string;
- toolName?: string;
- output?: unknown;
- }>;
- for (const part of parts) {
- if (part.type !== "tool-result" || part.toolName !== "connection_search") continue;
- const output = part.output;
- if (output === undefined || output === null) continue;
- const items = (
- typeof output === "object" && "type" in output && "value" in output
- ? (output as { value: unknown }).value
- : output
- ) as unknown;
- if (!Array.isArray(items)) continue;
- for (const item of items as ConnectionSearchResultItem[]) {
- if (item.tool && item.qualifiedName) {
- byQualifiedName.set(item.qualifiedName, item);
- }
- }
- }
- }
-
- return [...byQualifiedName.values()];
-}
-
function readDiscoveredToolClosure(closure: JsonObject): {
readonly connectionName: string;
readonly toolName: string;
@@ -511,93 +472,76 @@ async function authorizeDiscoveredConnectionToolApproval(
: await response(context);
}
-// The step-scoped definition re-derives its tools from conversation history.
-// After compaction removes old search results, those tools naturally disappear.
-const connectionSearchDynamicDefinition = defineDynamic({
- events: {
- "step.started": async (_event, ctx) => {
- const registry = loadContext().get(ConnectionRegistryKey);
- if (!registry || registry.getConnections().length === 0) return null;
-
- const connections = registry.getConnections();
- const connectionNames = connections.map((c) => c.connectionName);
- const fromMessages = extractDiscoveredTools(ctx.messages);
- const fromContext = loadContext().get(ConnectionSearchResultsKey) ?? [];
- const mergedMap = new Map<string, ConnectionSearchResultItem>();
- for (const r of fromContext) {
- if (r.qualifiedName) mergedMap.set(r.qualifiedName, r);
- }
- for (const r of fromMessages) {
- if (r.qualifiedName) mergedMap.set(r.qualifiedName, r);
- }
- const discovered = [...mergedMap.values()];
-
- const tools: Record<string, object> = {};
-
- const connectionSearchTool = defineTool({
- description:
- "Search for tools across your connections. " +
- "Discovered tools become directly callable by their qualified name " +
- "(e.g. `linear__list_issues`) in your next response. " +
- `Available connections: ${connectionNames.join(", ")}.`,
- inputSchema: CONNECTION_SEARCH_INPUT_SCHEMA,
- async execute(input: ConnectionSearchInput) {
- return executeConnectionSearch(input);
- },
- outputSchema: CONNECTION_SEARCH_OUTPUT_SCHEMA,
- });
- stampDurableDynamicToolCallbacks(connectionSearchTool, {
- execute: {
- callback: (_closure, input) => executeConnectionSearch(input as ConnectionSearchInput),
- closure: {},
- },
- });
- tools["connection_search"] = connectionSearchTool;
-
- for (const result of discovered) {
- const connectionName = result.connection;
- const toolName = result.tool!;
- const approval = registry.getConnectionApproval(connectionName);
-
- const closure = { connectionName, toolName };
- const discoveredTool = defineTool({
- description: result.description,
- inputSchema: (result.inputSchema ?? {
- type: "object",
- }) as JsonObject,
- approval,
- outputSchema: result.outputSchema as JsonObject | undefined,
- async execute(input: Record<string, unknown>, executeCtx) {
- return await executeDiscoveredConnectionTool(closure, input, executeCtx);
- },
- });
- stampDurableDynamicToolCallbacks(discoveredTool, {
- execute: { callback: executeDiscoveredConnectionTool, closure },
- ...(approval === undefined
- ? {}
- : {
- approvalRequest: {
- callback: requestDiscoveredConnectionToolApproval,
- closure,
- },
- }),
- ...(approval === undefined ||
- typeof approval === "function" ||
- approval.response === undefined
- ? {}
- : {
- approvalResponse: {
- callback: authorizeDiscoveredConnectionToolApproval,
- closure,
- },
- }),
- });
- tools[qualifiedConnectionToolName(connectionName, toolName)] = discoveredTool;
- }
-
- return tools;
+export async function resolveConnectionSearchDynamicTools() {
+ const registry = loadContext().get(ConnectionRegistryKey);
+ if (!registry || registry.getConnections().length === 0) return null;
+
+ const connections = registry.getConnections();
+ const connectionNames = connections.map((c) => c.connectionName);
+ const discovered = loadContext().get(ConnectionSearchResultsKey) ?? [];
+
+ const tools: Record<string, object> = {};
+
+ const connectionSearchTool = defineTool({
+ description:
+ "Search for tools across your connections. " +
+ "Discovered tools become directly callable by their qualified name " +
+ "(e.g. `linear__list_issues`) in your next response. " +
+ `Available connections: ${connectionNames.join(", ")}.`,
+ inputSchema: CONNECTION_SEARCH_INPUT_SCHEMA,
+ async execute(input: ConnectionSearchInput) {
+ return executeConnectionSearch(input);
},
- },
-});
+ outputSchema: CONNECTION_SEARCH_OUTPUT_SCHEMA,
+ });
+ stampDurableDynamicToolCallbacks(connectionSearchTool, {
+ execute: {
+ callback: (_closure, input) => executeConnectionSearch(input as ConnectionSearchInput),
+ closure: {},
+ },
+ });
+ tools["connection_search"] = connectionSearchTool;
+
+ for (const result of discovered) {
+ const connectionName = result.connection;
+ const toolName = result.tool!;
+ const approval = registry.getConnectionApproval(connectionName);
+
+ const closure = { connectionName, toolName };
+ const discoveredTool = defineTool({
+ description: result.description,
+ inputSchema: (result.inputSchema ?? {
+ type: "object",
+ }) as JsonObject,
+ approval,
+ outputSchema: result.outputSchema as JsonObject | undefined,
+ async execute(input: Record<string, unknown>, executeCtx) {
+ return await executeDiscoveredConnectionTool(closure, input, executeCtx);
+ },
+ });
+ stampDurableDynamicToolCallbacks(discoveredTool, {
+ execute: { callback: executeDiscoveredConnectionTool, closure },
+ ...(approval === undefined
+ ? {}
+ : {
+ approvalRequest: {
+ callback: requestDiscoveredConnectionToolApproval,
+ closure,
+ },
+ }),
+ ...(approval === undefined ||
+ typeof approval === "function" ||
+ approval.response === undefined
+ ? {}
+ : {
+ approvalResponse: {
+ callback: authorizeDiscoveredConnectionToolApproval,
+ closure,
+ },
+ }),
+ });
+ tools[qualifiedConnectionToolName(connectionName, toolName)] = discoveredTool;
+ }
-export default connectionSearchDynamicDefinition;
+ return tools;
+}
diff --git a/packages/eve/src/runtime/framework-tools/file-state.ts b/packages/eve/src/execution/tools/file-state.ts
similarity index 93%
rename from packages/eve/src/runtime/framework-tools/file-state.ts
rename to packages/eve/src/execution/tools/file-state.ts
index 5f0eac31b..c79086686 100644
--- a/packages/eve/src/runtime/framework-tools/file-state.ts
+++ b/packages/eve/src/execution/tools/file-state.ts
@@ -4,10 +4,7 @@ import { posix } from "node:path";
import { type AlsContext, loadContext } from "#context/container.js";
import { ContextKey } from "#context/key.js";
-// ---------------------------------------------------------------------------
-// Read-file stamp — tracks the last-known content of a file for stale-write
-// detection.
-// ---------------------------------------------------------------------------
+// Read-file stamps track the last-known content for stale-write detection.
/**
* Per-file fingerprint stored after a successful `read_file` call. Used by
diff --git a/packages/eve/src/runtime/framework-tools/skill.test.ts b/packages/eve/src/execution/tools/load-skill.test.ts
similarity index 75%
rename from packages/eve/src/runtime/framework-tools/skill.test.ts
rename to packages/eve/src/execution/tools/load-skill.test.ts
index fa728ab23..ea94eb384 100644
--- a/packages/eve/src/runtime/framework-tools/skill.test.ts
+++ b/packages/eve/src/execution/tools/load-skill.test.ts
@@ -4,37 +4,36 @@ import { ContextContainer, contextStorage } from "#context/container.js";
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/types.js";
-import {
- createSkillToolDefinition,
- SKILL_TOOL_DEFINITION,
-} from "#runtime/framework-tools/skill.js";
+import type { ConnectionRegistry } from "#runtime/connections/registry-types.js";
+import { loadSkill } from "#public/tools/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";
-function skillToolExecutor(skills: readonly ResolvedSkillDefinition[] = []) {
- const execute = createSkillToolDefinition(skills).execute;
+function skillToolExecutor(ctx: ContextContainer, skills: readonly ResolvedSkillDefinition[] = []) {
+ ctx.set(BundleKey, {
+ resolvedAgent: { skills },
+ } as never);
+ const execute = loadSkill.execute;
if (execute === undefined) throw new Error("load_skill tool is missing an execute function");
return execute;
}
-describe("SKILL_TOOL_DEFINITION", () => {
+describe("loadSkill", () => {
it("describes when skill loading should be used", () => {
- expect(SKILL_TOOL_DEFINITION.description).toContain(
- "request clearly matches a listed skill description",
- );
- expect(SKILL_TOOL_DEFINITION.description).toContain(
+ expect(loadSkill.description).toContain("request clearly matches a listed skill description");
+ expect(loadSkill.description).toContain(
"Loading adds the skill instructions to the current turn.",
);
- expect(SKILL_TOOL_DEFINITION.description).toContain("Available skills block");
- expect(SKILL_TOOL_DEFINITION.description).not.toContain("connection_search");
+ expect(loadSkill.description).toContain("Available skills block");
+ expect(loadSkill.description).not.toContain("connection_search");
});
});
describe("load_skill executor", () => {
- it("loads an authored markdown skill when no sandbox context is available", async () => {
+ it("loads an authored markdown skill from the active compiled bundle", async () => {
const ctx = new ContextContainer();
- const execute = skillToolExecutor([
+ const execute = skillToolExecutor(ctx, [
{
description: "Research a topic systematically",
logicalPath: "skills/research.md",
@@ -54,9 +53,7 @@ describe("load_skill executor", () => {
]);
await expect(
- contextStorage.run(ctx, () =>
- execute({ skill: "research" }, { messages: [], toolCallId: "call_1" }),
- ),
+ contextStorage.run(ctx, () => execute({ skill: "research" }, {} as never)),
).resolves.toBe("# Research\n\nFollow the evidence.\n");
});
@@ -74,7 +71,7 @@ describe("load_skill executor", () => {
};
const ctx = new ContextContainer();
ctx.set(SandboxKey, access);
- const execute = skillToolExecutor([
+ const execute = skillToolExecutor(ctx, [
{
assetsPath: "/authored/skills/incident-response/assets",
description: "Run the full incident response procedure",
@@ -93,9 +90,7 @@ describe("load_skill executor", () => {
]);
await expect(
- contextStorage.run(ctx, () =>
- execute({ skill: "incident-response" }, { messages: [], toolCallId: "call_2" }),
- ),
+ contextStorage.run(ctx, () => execute({ skill: "incident-response" }, {} as never)),
).resolves.toBe(
"# Incident response\n\nConsult `references/services/api/owners.md` when needed.\n",
);
@@ -119,7 +114,7 @@ describe("load_skill executor", () => {
ctx.set(DynamicSkillManifestKey, {
policy: [{ description: "Apply the dynamic policy", name: "policy" }],
});
- const execute = skillToolExecutor([
+ const execute = skillToolExecutor(ctx, [
{
description: "Apply the static policy",
logicalPath: "skills/policy.md",
@@ -131,9 +126,7 @@ describe("load_skill executor", () => {
]);
await expect(
- contextStorage.run(ctx, () =>
- execute({ skill: "policy" }, { messages: [], toolCallId: "call_dynamic" }),
- ),
+ contextStorage.run(ctx, () => execute({ skill: "policy" }, {} as never)),
).resolves.toBe("# Dynamic policy\n");
});
@@ -146,12 +139,10 @@ describe("load_skill executor", () => {
{ description: "Bark", name: "custom__bark" },
],
});
- const execute = skillToolExecutor();
+ const execute = skillToolExecutor(ctx);
await expect(
- contextStorage.run(ctx, () =>
- execute({ skill: "talk-like-a-dog" }, { messages: [], toolCallId: "call_1" }),
- ),
+ contextStorage.run(ctx, () => execute({ skill: "talk-like-a-dog" }, {} as never)),
).rejects.toThrow("Available skills: custom__bark, custom__talk-like-a-dog.");
});
@@ -168,12 +159,10 @@ describe("load_skill executor", () => {
const ctx = new ContextContainer();
ctx.set(SandboxKey, mockSandbox().access);
ctx.set(ConnectionRegistryKey, registry);
- const execute = skillToolExecutor();
+ const execute = skillToolExecutor(ctx);
await expect(
- contextStorage.run(ctx, () =>
- execute({ skill: "linear" }, { messages: [], toolCallId: "call_1" }),
- ),
+ contextStorage.run(ctx, () => execute({ skill: "linear" }, {} as never)),
).rejects.toThrow(
'"linear" is an installed connection, not a skill. Use connection_search with connection "linear" to find its tools.',
);
diff --git a/packages/eve/src/runtime/framework-tools/skill.ts b/packages/eve/src/execution/tools/load-skill.ts
similarity index 70%
rename from packages/eve/src/runtime/framework-tools/skill.ts
rename to packages/eve/src/execution/tools/load-skill.ts
index d75f8f099..0c4cf57ce 100644
--- a/packages/eve/src/runtime/framework-tools/skill.ts
+++ b/packages/eve/src/execution/tools/load-skill.ts
@@ -3,8 +3,8 @@ import { z } from "#compiled/zod/index.js";
import { loadContext } from "#context/container.js";
import { DynamicSkillManifestKey, SandboxKey } from "#context/keys.js";
import { ConnectionRegistryKey } from "#context/providers/connection-key.js";
+import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";
import { loadSkillFromSandbox } from "#runtime/skills/sandbox-access.js";
-import type { ResolvedSkillDefinition, ResolvedToolDefinition } from "#runtime/types.js";
/**
* Typed input accepted by {@link executeLoadSkillTool}.
@@ -18,12 +18,10 @@ type LoadSkillInput = z.infer<typeof SKILL_INPUT_SCHEMA>;
* Active dynamic skills take precedence and remain sandbox-backed because
* their full package content is currently materialized there at runtime.
*/
-async function executeLoadSkillTool(
- args: LoadSkillInput,
- authoredSkills: readonly ResolvedSkillDefinition[],
-): Promise<unknown> {
+async function executeLoadSkillTool(args: LoadSkillInput): Promise<unknown> {
const ctx = loadContext();
const { skill } = args;
+ const authoredSkills = ctx.require(BundleKey).resolvedAgent.skills;
const dynamicSkillNames = availableDynamicSkillNames(ctx);
const availableSkills = [
...new Set([...authoredSkills.map((entry) => entry.name), ...dynamicSkillNames]),
@@ -84,32 +82,6 @@ export const SKILL_INPUT_SCHEMA = z.strictObject({
});
export const SKILL_OUTPUT_SCHEMA = z.string();
-const SKILL_TOOL_METADATA = {
- description: [
- "Load the full instructions for one available skill by name or id.",
- "Use this tool when the request clearly matches a listed skill description or when the user explicitly asks for that skill.",
- "Loading adds the skill instructions to the current turn.",
- 'Choose the "skill" value from the Available skills block.',
- ].join(" "),
- inputSchema: SKILL_INPUT_SCHEMA,
- logicalPath: "eve:framework/load-skill",
- name: "load_skill",
- outputSchema: SKILL_OUTPUT_SCHEMA,
- sourceId: "eve:load-skill-tool",
- sourceKind: "module" as const,
-};
-
-/**
- * Creates a node-specific `load_skill` definition with authored skills bound
- * into its executor.
- */
-export function createSkillToolDefinition(
- authoredSkills: readonly ResolvedSkillDefinition[],
-): ResolvedToolDefinition {
- return {
- ...SKILL_TOOL_METADATA,
- execute: (input) => executeLoadSkillTool(input as LoadSkillInput, authoredSkills),
- };
+export async function executeLoadSkill(input: unknown): Promise<unknown> {
+ return await executeLoadSkillTool(input as LoadSkillInput);
}
-
-export const SKILL_TOOL_DEFINITION = createSkillToolDefinition([]);
diff --git a/packages/eve/src/runtime/framework-tools/sleep.ts b/packages/eve/src/execution/tools/sleep.ts
similarity index 100%
rename from packages/eve/src/runtime/framework-tools/sleep.ts
rename to packages/eve/src/execution/tools/sleep.ts
diff --git a/packages/eve/src/runtime/framework-tools/subagent/local.ts b/packages/eve/src/execution/tools/subagent/local.ts
similarity index 97%
rename from packages/eve/src/runtime/framework-tools/subagent/local.ts
rename to packages/eve/src/execution/tools/subagent/local.ts
index 607bb1613..1c799f528 100644
--- a/packages/eve/src/runtime/framework-tools/subagent/local.ts
+++ b/packages/eve/src/execution/tools/subagent/local.ts
@@ -25,9 +25,9 @@ import { defineTool, type TaskExec, type ToolContext } from "#public/definitions
import type {
RuntimeRemoteAgentCallActionRequest,
RuntimeSubagentCallActionRequest,
-} from "#runtime/actions/types.js";
-import { SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA } from "#runtime/framework-tools/tasks.js";
-import { PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA } from "#runtime/subagents/registry.js";
+} 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 { parseJsonObject } from "#shared/json.js";
import { createSubagentExecutorBinding } from "#tasks/types.js";
import { activeTurnId } from "#harness/active-turn-id.js";
@@ -68,6 +68,7 @@ interface SubagentDispatchResult {
readonly session: RuntimeSession;
}
+/** Transitional PR 1 classifier, replaced by declared dispatch effects in PR 2. */
const localSubagentExecutors = new WeakSet<object>();
const batchAgentClaims = new WeakMap<TaskExec["batch"], Map<string, string>>();
const log = createLogger("runtime.framework-tools.subagent");
diff --git a/packages/eve/src/runtime/framework-tools/subagent/remote.ts b/packages/eve/src/execution/tools/subagent/remote.ts
similarity index 67%
rename from packages/eve/src/runtime/framework-tools/subagent/remote.ts
rename to packages/eve/src/execution/tools/subagent/remote.ts
index dff8f7269..6c761e43b 100644
--- a/packages/eve/src/runtime/framework-tools/subagent/remote.ts
+++ b/packages/eve/src/execution/tools/subagent/remote.ts
@@ -1,7 +1,7 @@
import { defineTool } from "#public/definitions/tool.js";
-import { SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA } from "#runtime/framework-tools/tasks.js";
-import { PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA } from "#runtime/subagents/registry.js";
-import { executeSubagentTool } from "#runtime/framework-tools/subagent/local.js";
+import { SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA } from "#shared/task-tool.js";
+import { PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA } from "#shared/agent-tool.js";
+import { executeSubagentTool } from "#execution/tools/subagent/local.js";
export function defineRemoteSubagent(input: {
readonly description: string;
diff --git a/packages/eve/src/execution/tools/tasks.ts b/packages/eve/src/execution/tools/tasks.ts
new file mode 100644
index 000000000..1fc7e24d4
--- /dev/null
+++ b/packages/eve/src/execution/tools/tasks.ts
@@ -0,0 +1,61 @@
+import type { HarnessToolDefinition } from "#harness/execute-tool.js";
+import {
+ TASK_CANCEL_INPUT_SCHEMA,
+ TASK_CANCEL_TOOL_NAME,
+ TASK_UPDATE_INPUT_SCHEMA,
+ TASK_UPDATE_TOOL_NAME,
+ TASK_VIEWS_OUTPUT_SCHEMA,
+} from "#shared/task-tool.js";
+
+/**
+ * Framework task tools for `experimental.tasks`.
+ *
+ * With the flag on, subagent calls return a task receipt instead of
+ * blocking the parent turn; these tools coordinate that delegated work.
+ * `task_cancel` and `task_update` are execute-less runtime actions —
+ * they need durable session state and world access, so the runtime-action
+ * dispatch step executes them.
+ */
+
+const TASK_CANCEL_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.";
+
+const TASK_UPDATE_DESCRIPTION =
+ "Briefly tell the parent agent what this background task is currently doing. " +
+ "Report activity, not preliminary findings or results.";
+
+/**
+ * Builds the harness definitions injected when the root agent enables
+ * `experimental.tasks`. Follows the implicit `agent` tool pattern:
+ * inline definitions, no registry entry, session-shape hiding in
+ * advertised-tools, and re-validation at dispatch.
+ */
+export function createTaskToolHarnessDefinitions(): readonly HarnessToolDefinition[] {
+ return [
+ {
+ description: TASK_CANCEL_DESCRIPTION,
+ inputSchema: TASK_CANCEL_INPUT_SCHEMA,
+ name: TASK_CANCEL_TOOL_NAME,
+ outputSchema: TASK_VIEWS_OUTPUT_SCHEMA,
+ runtimeAction: { kind: "task-control" },
+ },
+ {
+ description: TASK_UPDATE_DESCRIPTION,
+ inputSchema: TASK_UPDATE_INPUT_SCHEMA,
+ name: TASK_UPDATE_TOOL_NAME,
+ runtimeAction: { kind: "task-control" },
+ },
+ ];
+}
+
+/**
+ * Whether one node's sessions receive the task tools.
+ *
+ * Mirrors `isImplicitAgentToolAvailable`: the compile step already
+ * rejects `experimental.tasks` on subagents, authored tools with the
+ * same name shadow the framework tool, and `disableTool(name)` removes
+ * individual tools. Root-node self-delegated children share this node's
+ * config, so advertised-tools uses caller/session shape to expose only
+ * `task_update` to delegated task children.
+ */
diff --git a/packages/eve/src/runtime/framework-tools/todo.test.ts b/packages/eve/src/execution/tools/todo.test.ts
similarity index 99%
rename from packages/eve/src/runtime/framework-tools/todo.test.ts
rename to packages/eve/src/execution/tools/todo.test.ts
index 79911739e..cf3907eb9 100644
--- a/packages/eve/src/runtime/framework-tools/todo.test.ts
+++ b/packages/eve/src/execution/tools/todo.test.ts
@@ -9,7 +9,7 @@ import {
type TodoItem,
type TodoState,
TodoStateKey,
-} from "#runtime/framework-tools/todo.js";
+} from "#execution/tools/todo.js";
function runInContext(
fn: () => unknown,
diff --git a/packages/eve/src/runtime/framework-tools/todo.ts b/packages/eve/src/execution/tools/todo.ts
similarity index 74%
rename from packages/eve/src/runtime/framework-tools/todo.ts
rename to packages/eve/src/execution/tools/todo.ts
index bae7bda86..69efa58cd 100644
--- a/packages/eve/src/runtime/framework-tools/todo.ts
+++ b/packages/eve/src/execution/tools/todo.ts
@@ -4,7 +4,6 @@ import { z } from "#compiled/zod/index.js";
import { loadContext } from "#context/container.js";
import { ContextKey } from "#context/key.js";
import { TODO_COMPACTION_PRESERVATION_LABEL } from "#harness/compaction-prompt.js";
-import type { ResolvedToolDefinition } from "#runtime/types.js";
// ---------------------------------------------------------------------------
// Durable context key
@@ -135,34 +134,3 @@ export const TODO_OUTPUT_SCHEMA = z.strictObject({
}),
todos: z.array(TODO_ITEM_SCHEMA),
});
-
-export const TODO_TOOL_DEFINITION: ResolvedToolDefinition = {
- description: [
- "Use this tool to create and manage a structured task list for the current session.",
- "This helps you track progress, organize complex tasks, and demonstrate thoroughness.",
- "",
- "When to use:",
- "- Complex multistep tasks requiring 3 or more distinct steps",
- "- When the user provides multiple tasks or a numbered list",
- "- After receiving new instructions, to capture requirements",
- "- After completing a task, to mark it complete and add follow-ups",
- "",
- "When NOT to use:",
- "- Single, straightforward tasks that need no tracking",
- "- Purely conversational or informational requests",
- "",
- "Usage:",
- "- Call with `todos` to replace the entire list (full replacement write)",
- "- Call without `todos` to read the current list",
- "- Both return the full current list with status counts",
- "- Mark tasks in_progress when you start, completed when done",
- "- Only have ONE task in_progress at a time",
- ].join("\n"),
- execute: async (input) => executeTodoTool((input ?? {}) as TodoToolInput),
- inputSchema: TODO_INPUT_SCHEMA,
- logicalPath: "eve:framework/todo",
- name: "todo",
- outputSchema: TODO_OUTPUT_SCHEMA,
- sourceId: "eve:todo-tool",
- sourceKind: "module",
-};
diff --git a/packages/eve/src/execution/turn-cancellation.integration.test.ts b/packages/eve/src/execution/turn-cancellation.integration.test.ts
index 57ffd793e..11c09cae3 100644
--- a/packages/eve/src/execution/turn-cancellation.integration.test.ts
+++ b/packages/eve/src/execution/turn-cancellation.integration.test.ts
@@ -77,6 +77,7 @@ function buildWaitForCancelTool(onStart: () => void, onAbort: () => void): Resol
inputSchema: toInputSchema({ additionalProperties: false, properties: {}, type: "object" }),
logicalPath: `tools/${WAIT_TOOL_NAME}.ts`,
name: WAIT_TOOL_NAME,
+ owner: { kind: "application" },
sourceId: `tools/${WAIT_TOOL_NAME}.ts`,
sourceKind: "module",
};
@@ -89,7 +90,7 @@ interface WaitToolFixture {
toolStarts(): number;
}
-function createWaitToolRuntime(agentName: string): WaitToolFixture {
+async function createWaitToolRuntime(agentName: string): Promise<WaitToolFixture> {
let aborts = 0;
let starts = 0;
let resolveStarted: (() => void) | undefined;
@@ -105,7 +106,7 @@ function createWaitToolRuntime(agentName: string): WaitToolFixture {
aborts += 1;
},
);
- const runtime = createTestRuntime({ agent: { name: agentName }, tools: [waitTool] });
+ const runtime = await createTestRuntime({ agent: { name: agentName }, tools: [waitTool] });
const manifestTool = runtime.manifest.tools.find((tool) => tool.name === WAIT_TOOL_NAME);
if (manifestTool === undefined) {
throw new Error(`Expected ${WAIT_TOOL_NAME} to be present in the test manifest.`);
@@ -266,7 +267,7 @@ async function expectCancelResponse(
describe("turn cancellation integration", () => {
it("buffers a default steering message before replacing the active turn", async () => {
- const fixture = createWaitToolRuntime("turn-steer-message");
+ const fixture = await createWaitToolRuntime("turn-steer-message");
const rawToken = "turn-steer-message";
const continuationToken = `http:${rawToken}`;
const workflowRuntime = createWorkflowRuntime({
@@ -330,7 +331,7 @@ describe("turn cancellation integration", () => {
}, 60_000);
it("cancels a turn mid-tool and accepts the next message normally", async () => {
- const fixture = createWaitToolRuntime("turn-cancel-tool");
+ const fixture = await createWaitToolRuntime("turn-cancel-tool");
const continuationToken = "http:turn-cancel-tool";
await fixture.runtime.run(async () => {
@@ -407,7 +408,7 @@ describe("turn cancellation integration", () => {
});
it("cancels a turn through the eve channel cancel route", async () => {
- const fixture = createWaitToolRuntime("turn-cancel-route");
+ const fixture = await createWaitToolRuntime("turn-cancel-route");
const continuationToken = "http:turn-cancel-route";
const cancelViaRoute = createCancelRouteCaller();
@@ -483,7 +484,7 @@ describe("turn cancellation integration", () => {
}, 60_000);
it("cancels a turn from a channel route helper addressed by continuation token", async () => {
- const fixture = createWaitToolRuntime("turn-cancel-helper");
+ const fixture = await createWaitToolRuntime("turn-cancel-helper");
const rawToken = "turn-cancel-helper";
const continuationToken = `http:${rawToken}`;
const workflowRuntime = createWorkflowRuntime({
@@ -573,7 +574,7 @@ describe("turn cancellation integration", () => {
}, 60_000);
it("cascades cancellation to an in-flight subagent and does not re-dispatch it", async () => {
- const fixture = createWaitToolRuntime("turn-cancel-subagent");
+ const fixture = await createWaitToolRuntime("turn-cancel-subagent");
const continuationToken = "http:turn-cancel-subagent";
await fixture.runtime.run(async () => {
@@ -639,7 +640,7 @@ describe("turn cancellation integration", () => {
}, 60_000);
it("cancels a turn parked on a child HITL request without corrupting the stream", async () => {
- const runtime = createTestRuntime({ agent: { name: "turn-cancel-hitl" } });
+ const runtime = await createTestRuntime({ agent: { name: "turn-cancel-hitl" } });
const continuationToken = "http:turn-cancel-hitl";
await runtime.run(async () => {
@@ -730,7 +731,7 @@ describe("turn cancellation integration", () => {
}, 60_000);
it("consumes a cancel with a stale turn guard as a no-op and keeps the turn running", async () => {
- const fixture = createWaitToolRuntime("turn-cancel-stale-guard");
+ const fixture = await createWaitToolRuntime("turn-cancel-stale-guard");
const continuationToken = "http:turn-cancel-stale-guard";
await fixture.runtime.run(async () => {
@@ -777,7 +778,7 @@ describe("turn cancellation integration", () => {
}, 60_000);
it("treats a cancel after the turn settled as a benign no-op", async () => {
- const runtime = createTestRuntime({ agent: { name: "turn-cancel-late" } });
+ const runtime = await createTestRuntime({ agent: { name: "turn-cancel-late" } });
const continuationToken = "http:turn-cancel-late";
await runtime.run(async () => {
@@ -827,7 +828,7 @@ describe("turn cancellation integration", () => {
});
it("completes settled turn runs so the world sweeps their hooks", async () => {
- const runtime = createTestRuntime({ agent: { name: "turn-cancel-sweep" } });
+ const runtime = await createTestRuntime({ agent: { name: "turn-cancel-sweep" } });
const continuationToken = "http:turn-cancel-sweep";
await runtime.run(async () => {
diff --git a/packages/eve/src/execution/turn-workflow.ts b/packages/eve/src/execution/turn-workflow.ts
index 68738b026..6d79a7065 100644
--- a/packages/eve/src/execution/turn-workflow.ts
+++ b/packages/eve/src/execution/turn-workflow.ts
@@ -33,7 +33,7 @@ import { turnStep } from "#execution/workflow-steps.js";
import { activeTurnId } from "#harness/active-turn-id.js";
import { getRuntimeActionResultKey } from "#runtime/actions/keys.js";
import { resolveRuntimeActionResultsForKeys } from "#runtime/actions/results.js";
-import type { RuntimeActionResult } from "#runtime/actions/types.js";
+import type { RuntimeActionResult } from "#shared/action-types.js";
const TASK_MODE_WAIT_ERROR_MESSAGE = "Task mode cannot wait for follow-up input (`next: null`).";
diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v1.ts b/packages/eve/src/execution/wire/session-inbox-wire.v1.ts
index e2b376c75..5f110be5d 100644
--- a/packages/eve/src/execution/wire/session-inbox-wire.v1.ts
+++ b/packages/eve/src/execution/wire/session-inbox-wire.v1.ts
@@ -8,7 +8,7 @@ import type {
} from "#channel/types.js";
import { coalesceDeliverPayloads } from "#execution/deliver-payloads.js";
import { SessionInboxWireError } from "#execution/wire/session-inbox-contract.js";
-import { inputRequestSchema, inputResponseSchema } from "#runtime/input/types.js";
+import { inputRequestSchema, inputResponseSchema } from "#shared/input.js";
import { formatValidationError } from "#runtime/validation.js";
import { jsonObjectSchema, jsonValueSchema } from "#shared/json-schemas.js";
import { tokenUsageSchema } from "#shared/token-usage.js";
diff --git a/packages/eve/src/execution/workflow-entry.integration.test.ts b/packages/eve/src/execution/workflow-entry.integration.test.ts
index db8cee118..18adc90a1 100644
--- a/packages/eve/src/execution/workflow-entry.integration.test.ts
+++ b/packages/eve/src/execution/workflow-entry.integration.test.ts
@@ -24,7 +24,7 @@ import type {
AuthorizationDefinition,
ConnectionPrincipal,
TokenResult,
-} from "#runtime/connections/types.js";
+} from "#shared/connection-types.js";
import type { ResolvedToolDefinition } from "#runtime/types.js";
import { toInputSchema } from "#shared/tool-schema.js";
@@ -70,7 +70,7 @@ function buildSerializedContext(overrides: {
interface WeatherAuthRuntime {
completeCalls(): number;
completedPrincipals(): readonly ConnectionPrincipal[];
- runtime: ReturnType<typeof createTestRuntime>;
+ runtime: Awaited<ReturnType<typeof createTestRuntime>>;
}
/**
@@ -79,7 +79,7 @@ interface WeatherAuthRuntime {
* `oauth-code` callback. Shared by the callback-resume and
* challenge-stays-open driver tests.
*/
-function createWeatherAuthRuntime(agentName: string): WeatherAuthRuntime {
+async function createWeatherAuthRuntime(agentName: string): Promise<WeatherAuthRuntime> {
let completeCalls = 0;
const completedPrincipals: ConnectionPrincipal[] = [];
const weatherAuth: AuthorizationDefinition<{ nonce: string }> = {
@@ -139,10 +139,11 @@ function createWeatherAuthRuntime(agentName: string): WeatherAuthRuntime {
}),
logicalPath: "tools/get_weather.ts",
name: "get_weather",
+ owner: { kind: "application" },
sourceId: "tools/get_weather.ts",
sourceKind: "module",
};
- const runtime = createTestRuntime({
+ const runtime = await createTestRuntime({
agent: { name: agentName },
tools: [getWeatherTool],
});
@@ -188,7 +189,9 @@ function expectSingleTurn(events: readonly MessageStreamEvent[], turnId: string)
describe("workflowEntry integration", () => {
it("resumes normal follow-ups after an interactive authorization callback", async () => {
- const { completeCalls, runtime } = createWeatherAuthRuntime("workflow-entry-auth-followup");
+ const { completeCalls, runtime } = await createWeatherAuthRuntime(
+ "workflow-entry-auth-followup",
+ );
const continuationToken = "http:workflow-entry-auth-followup";
await runtime.run(async () => {
@@ -304,7 +307,7 @@ describe("workflowEntry integration", () => {
});
it("runs ordinary deliveries while an authorization challenge stays open", async () => {
- const { completeCalls, completedPrincipals, runtime } = createWeatherAuthRuntime(
+ const { completeCalls, completedPrincipals, runtime } = await createWeatherAuthRuntime(
"workflow-entry-auth-open",
);
const continuationToken = "http:workflow-entry-auth-open";
@@ -440,7 +443,9 @@ describe("workflowEntry integration", () => {
});
it("defers ordinary deliveries while a task waits for authorization", async () => {
- const { completeCalls, runtime } = createWeatherAuthRuntime("workflow-entry-task-auth-open");
+ const { completeCalls, runtime } = await createWeatherAuthRuntime(
+ "workflow-entry-task-auth-open",
+ );
const continuationToken = "http:workflow-entry-task-auth-open";
await runtime.run(async () => {
@@ -505,7 +510,9 @@ describe("workflowEntry integration", () => {
});
it("ignores stale and duplicate callbacks after a challenge is replaced", async () => {
- const { completeCalls, runtime } = createWeatherAuthRuntime("workflow-entry-auth-replaced");
+ const { completeCalls, runtime } = await createWeatherAuthRuntime(
+ "workflow-entry-auth-replaced",
+ );
const continuationToken = "http:workflow-entry-auth-replaced";
await runtime.run(async () => {
@@ -592,7 +599,7 @@ describe("workflowEntry integration", () => {
});
it("completes the challenge after a no-op cancel consumed the parked wait", async () => {
- const { completeCalls, runtime } = createWeatherAuthRuntime("workflow-entry-auth-cancel");
+ const { completeCalls, runtime } = await createWeatherAuthRuntime("workflow-entry-auth-cancel");
const continuationToken = "http:workflow-entry-auth-cancel";
await runtime.run(async () => {
@@ -675,7 +682,7 @@ describe("workflowEntry integration", () => {
});
it("parks in conversation mode and resumes via runtime delivery", async () => {
- const runtime = createTestRuntime({ agent: { name: "workflow-entry-conversation" } });
+ const runtime = await createTestRuntime({ agent: { name: "workflow-entry-conversation" } });
const continuationToken = "http:workflow-entry-conversation";
await runtime.run(async () => {
@@ -744,7 +751,7 @@ describe("workflowEntry integration", () => {
});
it("publishes the session ID as the waiting address for an ID-only session", async () => {
- const runtime = createTestRuntime({ agent: { name: "workflow-entry-id-only" } });
+ const runtime = await createTestRuntime({ agent: { name: "workflow-entry-id-only" } });
await runtime.run(async () => {
const run = await start(workflowEntry, [
@@ -771,7 +778,7 @@ describe("workflowEntry integration", () => {
});
it("stamps every stream event with an id that survives a rewind", async () => {
- const runtime = createTestRuntime({ agent: { name: "workflow-entry-event-ids" } });
+ const runtime = await createTestRuntime({ agent: { name: "workflow-entry-event-ids" } });
const continuationToken = "http:workflow-entry-event-ids";
await runtime.run(async () => {
@@ -834,7 +841,7 @@ describe("workflowEntry integration", () => {
});
it("completes an expired conversation and lets its channel start a fresh session", async () => {
- const runtime = createTestRuntime({ agent: { name: "workflow-entry-timeout" } });
+ const runtime = await createTestRuntime({ agent: { name: "workflow-entry-timeout" } });
const continuationToken = "http:workflow-entry-timeout";
const workflowRuntime = createWorkflowRuntime({
compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
@@ -897,7 +904,9 @@ describe("workflowEntry integration", () => {
});
it("notifies each delegated conversation turn and remains available via agentId", async () => {
- const runtime = createTestRuntime({ agent: { name: "workflow-entry-delegated-conversation" } });
+ const runtime = await createTestRuntime({
+ agent: { name: "workflow-entry-delegated-conversation" },
+ });
const workflowRuntime = createWorkflowRuntime({
compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
});
@@ -976,7 +985,7 @@ describe("workflowEntry integration", () => {
});
it("exits a competing continuation owner before its first turn", async () => {
- const runtime = createTestRuntime({ agent: { name: "workflow-entry-hook-owner" } });
+ const runtime = await createTestRuntime({ agent: { name: "workflow-entry-hook-owner" } });
const continuationToken = "http:workflow-entry-hook-owner";
await runtime.run(async () => {
@@ -1031,7 +1040,7 @@ describe("workflowEntry integration", () => {
});
it("emits completed structured results for a conversation turn outputSchema", async () => {
- const runtime = createTestRuntime({ agent: { name: "workflow-entry-output-schema" } });
+ const runtime = await createTestRuntime({ agent: { name: "workflow-entry-output-schema" } });
const continuationToken = "http:workflow-entry-output-schema";
const outputSchema = {
properties: {
@@ -1090,7 +1099,7 @@ describe("workflowEntry integration", () => {
});
it("completes immediately in task mode", async () => {
- const runtime = createTestRuntime({ agent: { name: "workflow-entry-task" } });
+ const runtime = await createTestRuntime({ agent: { name: "workflow-entry-task" } });
await runtime.run(async () => {
const run = await start(workflowEntry, [
@@ -1119,7 +1128,7 @@ describe("workflowEntry integration", () => {
required: ["summary"],
type: "object",
} as const;
- const runtime = createTestRuntime({
+ const runtime = await createTestRuntime({
agent: { name: "workflow-entry-task-output-schema", outputSchema },
});
@@ -1143,7 +1152,7 @@ describe("workflowEntry integration", () => {
});
it("emits `$eve.*` session attributes onto the parent workflow run", async () => {
- const runtime = createTestRuntime({ agent: { name: "workflow-entry-tags" } });
+ const runtime = await createTestRuntime({ agent: { name: "workflow-entry-tags" } });
const continuationToken = "http:workflow-entry-tags";
await runtime.run(async () => {
@@ -1195,7 +1204,7 @@ describe("workflowEntry integration", () => {
});
it("emits parent lineage onto a subagent workflow run", async () => {
- const runtime = createTestRuntime({ agent: { name: "workflow-entry-subagent-tags" } });
+ const runtime = await createTestRuntime({ agent: { name: "workflow-entry-subagent-tags" } });
await runtime.run(async () => {
const serializedContext = buildSerializedContext({
diff --git a/packages/eve/src/execution/workflow-steps.ts b/packages/eve/src/execution/workflow-steps.ts
index 91a766ef4..24d098af2 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/s
import { createExecutionHistoryView } from "#execution/history-view.js";
import { resolveRuntimeCompiledArtifactsVersionedCacheKey } from "#runtime/cache-key.js";
import { createWorkflowRuntime } from "#execution/workflow-runtime.js";
-import { isTaskToolAvailable, TASK_UPDATE_TOOL_NAME } from "#runtime/framework-tools/tasks.js";
+import { TASK_UPDATE_TOOL_NAME } from "#shared/task-tool.js";
import { stageAttachmentsToSandbox } from "#harness/attachment-staging.js";
const TASK_DONE_WITH_PENDING_INPUT_ERROR_MESSAGE =
@@ -132,14 +132,13 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
const effectiveAgent = resolveEffectiveAgentRuntime(bundle, ctx);
const taskUpdatesEnabled =
isTaskOwnedSerializedContext(input.serializedContext) &&
- isTaskToolAvailable({
- disabledFrameworkTools: bundle.resolvedAgent.disabledFrameworkTools ?? [],
- hasAuthoredTool: effectiveAgent.turnAgent.tools.some(
- (tool) => tool.name === TASK_UPDATE_TOOL_NAME,
- ),
- tasksEnabled,
- toolName: TASK_UPDATE_TOOL_NAME,
- });
+ tasksEnabled &&
+ effectiveAgent.turnAgent.tools.some(
+ (tool) =>
+ tool.kind === "authored-tool" &&
+ tool.owner.kind === "framework" &&
+ tool.name === TASK_UPDATE_TOOL_NAME,
+ );
// Populate the callback base URL so getHookUrl() works during tool
// execution, preferring eve's active local origin over metadata fallback.
diff --git a/packages/eve/src/framework/host-inventory.ts b/packages/eve/src/framework/host-inventory.ts
new file mode 100644
index 000000000..62dc468df
--- /dev/null
+++ b/packages/eve/src/framework/host-inventory.ts
@@ -0,0 +1,56 @@
+import {
+ EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN,
+ EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH,
+ EVE_DEV_RUNTIME_ARTIFACTS_RESUME_ROUTE_PATH,
+ EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH,
+ EVE_DEV_RUNTIME_ARTIFACTS_SUSPEND_ROUTE_PATH,
+ EVE_PRODUCTION_CRON_ROUTE_PATTERN,
+} from "#protocol/routes.js";
+import { EVE_WORKFLOW_FLOW_ROUTE_PATH } from "#internal/workflow-bundle/eve-service-route-output.js";
+import {
+ DEVELOPMENT_WORKFLOW_STREAM_ROUTE,
+ DEVELOPMENT_WORKFLOW_WORLD_ROUTE,
+} from "#internal/workflow/development-world-protocol.js";
+
+export type HostHttpMethod = "ALL" | "GET" | "POST";
+
+export interface HostHttpRegistration {
+ readonly capability: "workflow" | "development" | "schedule";
+ readonly method: HostHttpMethod;
+ readonly path: string;
+ readonly reservationOnly?: boolean;
+}
+
+export const HOST_HTTP_INVENTORY: readonly HostHttpRegistration[] = Object.freeze([
+ { capability: "workflow", method: "ALL", path: EVE_WORKFLOW_FLOW_ROUTE_PATH },
+ { capability: "development", method: "GET", path: EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH },
+ {
+ capability: "development",
+ method: "GET",
+ path: EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH,
+ },
+ {
+ capability: "development",
+ method: "POST",
+ path: EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH,
+ },
+ {
+ capability: "development",
+ method: "POST",
+ path: EVE_DEV_RUNTIME_ARTIFACTS_SUSPEND_ROUTE_PATH,
+ },
+ {
+ capability: "development",
+ method: "POST",
+ path: EVE_DEV_RUNTIME_ARTIFACTS_RESUME_ROUTE_PATH,
+ },
+ { capability: "development", method: "ALL", path: DEVELOPMENT_WORKFLOW_WORLD_ROUTE },
+ { capability: "development", method: "ALL", path: DEVELOPMENT_WORKFLOW_STREAM_ROUTE },
+ { capability: "schedule", method: "POST", path: EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN },
+ {
+ capability: "schedule",
+ method: "ALL",
+ path: EVE_PRODUCTION_CRON_ROUTE_PATTERN,
+ reservationOnly: true,
+ },
+]);
diff --git a/packages/eve/src/framework/sources/modules/agent-tool.ts b/packages/eve/src/framework/sources/modules/agent-tool.ts
new file mode 100644
index 000000000..4a252ba93
--- /dev/null
+++ b/packages/eve/src/framework/sources/modules/agent-tool.ts
@@ -0,0 +1 @@
+export { agent as default } from "#public/tools/agent.js";
diff --git a/packages/eve/src/framework/sources/modules/agent.ts b/packages/eve/src/framework/sources/modules/agent.ts
new file mode 100644
index 000000000..ebb568e38
--- /dev/null
+++ b/packages/eve/src/framework/sources/modules/agent.ts
@@ -0,0 +1,4 @@
+import { defineAgent } from "#public/definitions/agent.js";
+import { DEFAULT_AGENT_MODEL_ID } from "#shared/default-agent-model.js";
+
+export default defineAgent({ model: DEFAULT_AGENT_MODEL_ID });
diff --git a/packages/eve/src/framework/sources/modules/ask-question.ts b/packages/eve/src/framework/sources/modules/ask-question.ts
new file mode 100644
index 000000000..f9a180e3f
--- /dev/null
+++ b/packages/eve/src/framework/sources/modules/ask-question.ts
@@ -0,0 +1 @@
+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.ts
new file mode 100644
index 000000000..6912cd201
--- /dev/null
+++ b/packages/eve/src/framework/sources/modules/bash.ts
@@ -0,0 +1 @@
+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.ts
new file mode 100644
index 000000000..030e2e387
--- /dev/null
+++ b/packages/eve/src/framework/sources/modules/connection-search.ts
@@ -0,0 +1 @@
+export { default } from "#tools/connection-search.js";
diff --git a/packages/eve/src/framework/sources/modules/eve-channel.ts b/packages/eve/src/framework/sources/modules/eve-channel.ts
new file mode 100644
index 000000000..682e7d6a0
--- /dev/null
+++ b/packages/eve/src/framework/sources/modules/eve-channel.ts
@@ -0,0 +1,6 @@
+import { localDev, placeholderAuth, vercelOidc } from "#public/channels/auth.js";
+import { eveChannel } from "#eve-channel/index.js";
+
+export default function createDefaultEveChannel() {
+ return eveChannel({ auth: [vercelOidc(), localDev(), placeholderAuth()] });
+}
diff --git a/packages/eve/src/framework/sources/modules/home-channel.ts b/packages/eve/src/framework/sources/modules/home-channel.ts
new file mode 100644
index 000000000..70d0f8d30
--- /dev/null
+++ b/packages/eve/src/framework/sources/modules/home-channel.ts
@@ -0,0 +1,10 @@
+import { defineChannel, GET, HEAD } from "#public/definitions/channel.js";
+import { buildHomePageResponse } from "#internal/nitro/routes/index.js";
+import { readHomeRouteMetadata } from "#internal/nitro/routes/channel-route-context.js";
+
+const respond = async (request: Request, args: Parameters<typeof readHomeRouteMetadata>[0]) =>
+ buildHomePageResponse(readHomeRouteMetadata(args) ?? { agentName: "eve" }, request);
+
+export default defineChannel({
+ routes: [GET("/", respond), HEAD("/", respond)],
+});
diff --git a/packages/eve/src/framework/sources/modules/load-skill.ts b/packages/eve/src/framework/sources/modules/load-skill.ts
new file mode 100644
index 000000000..1e4e9af93
--- /dev/null
+++ b/packages/eve/src/framework/sources/modules/load-skill.ts
@@ -0,0 +1 @@
+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.ts
new file mode 100644
index 000000000..2bd0f20f4
--- /dev/null
+++ b/packages/eve/src/framework/sources/modules/read-file.ts
@@ -0,0 +1 @@
+export { readFile as default } from "#tools/read-file.js";
diff --git a/packages/eve/src/framework/sources/modules/sandbox.ts b/packages/eve/src/framework/sources/modules/sandbox.ts
new file mode 100644
index 000000000..9a57a016e
--- /dev/null
+++ b/packages/eve/src/framework/sources/modules/sandbox.ts
@@ -0,0 +1,3 @@
+import { defineSandbox } from "#public/definitions/sandbox.js";
+
+export default defineSandbox({});
diff --git a/packages/eve/src/framework/sources/modules/task-cancel.ts b/packages/eve/src/framework/sources/modules/task-cancel.ts
new file mode 100644
index 000000000..a1843ae9e
--- /dev/null
+++ b/packages/eve/src/framework/sources/modules/task-cancel.ts
@@ -0,0 +1 @@
+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.ts
new file mode 100644
index 000000000..226d867f3
--- /dev/null
+++ b/packages/eve/src/framework/sources/modules/task-update.ts
@@ -0,0 +1 @@
+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.ts
new file mode 100644
index 000000000..21ed9197c
--- /dev/null
+++ b/packages/eve/src/framework/sources/modules/todo.ts
@@ -0,0 +1 @@
+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.ts
new file mode 100644
index 000000000..230db01ed
--- /dev/null
+++ b/packages/eve/src/framework/sources/modules/web-fetch.ts
@@ -0,0 +1 @@
+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.ts
new file mode 100644
index 000000000..13f54d8ae
--- /dev/null
+++ b/packages/eve/src/framework/sources/modules/web-search.ts
@@ -0,0 +1,3 @@
+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.ts
new file mode 100644
index 000000000..bee239578
--- /dev/null
+++ b/packages/eve/src/framework/sources/modules/write-file.ts
@@ -0,0 +1 @@
+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.ts
new file mode 100644
index 000000000..07a52fc08
--- /dev/null
+++ b/packages/eve/src/framework/sources/registry.ts
@@ -0,0 +1,101 @@
+import { resolveInstalledPackageInfo } from "#internal/application/package.js";
+import {
+ createAgentSourceRegistry,
+ defineProgrammaticAgentSource,
+ loadProgrammaticModuleNamespace,
+ type AgentSourceRegistry,
+ type AgentModuleBacking,
+ type ProgrammaticModuleNamespace,
+} from "#compiler/source-graph.js";
+
+const revision = `eve@${resolveInstalledPackageInfo().version}:compiled-manifest-v42`;
+
+const localDefaults = defineProgrammaticAgentSource({
+ id: "eve:defaults",
+ revision,
+ modules: [
+ { logicalPath: "agent.ts", loadNamespace: () => import("#framework/sources/modules/agent.js") },
+ {
+ logicalPath: "sandbox.ts",
+ semanticRevision: "eve:default-sandbox:v1",
+ loadNamespace: () => import("#framework/sources/modules/sandbox.js"),
+ },
+ {
+ logicalPath: "tools/bash.ts",
+ loadNamespace: () => import("#framework/sources/modules/bash.js"),
+ },
+ {
+ logicalPath: "tools/read_file.ts",
+ loadNamespace: () => import("#framework/sources/modules/read-file.js"),
+ },
+ {
+ logicalPath: "tools/write_file.ts",
+ loadNamespace: () => import("#framework/sources/modules/write-file.js"),
+ },
+ {
+ logicalPath: "tools/todo.ts",
+ loadNamespace: () => import("#framework/sources/modules/todo.js"),
+ },
+ {
+ logicalPath: "tools/web_fetch.ts",
+ loadNamespace: () => import("#framework/sources/modules/web-fetch.js"),
+ },
+ {
+ logicalPath: "tools/load_skill.ts",
+ loadNamespace: () => import("#framework/sources/modules/load-skill.js"),
+ },
+ {
+ logicalPath: "tools/connection_search.ts",
+ loadNamespace: () => import("#framework/sources/modules/connection-search.js"),
+ },
+ {
+ logicalPath: "tools/ask_question.ts",
+ loadNamespace: () => import("#framework/sources/modules/ask-question.js"),
+ },
+ {
+ logicalPath: "tools/web_search.ts",
+ loadNamespace: () => import("#framework/sources/modules/web-search.js"),
+ },
+ ],
+});
+
+const rootDefaults = defineProgrammaticAgentSource({
+ id: "eve:root-defaults",
+ revision,
+ modules: [
+ {
+ logicalPath: "tools/agent.ts",
+ loadNamespace: () => import("#framework/sources/modules/agent-tool.js"),
+ },
+ {
+ logicalPath: "tools/task_update.ts",
+ loadNamespace: () => import("#framework/sources/modules/task-update.js"),
+ },
+ {
+ logicalPath: "tools/task_cancel.ts",
+ loadNamespace: () => import("#framework/sources/modules/task-cancel.js"),
+ },
+ {
+ logicalPath: "channels/eve.ts",
+ loadNamespace: () => import("#framework/sources/modules/eve-channel.js"),
+ },
+ {
+ logicalPath: "channels/home.ts",
+ loadNamespace: () => import("#framework/sources/modules/home-channel.js"),
+ },
+ ],
+});
+
+export const frameworkAgentSourceRegistry: AgentSourceRegistry = createAgentSourceRegistry([
+ { applyTo: "all-local-nodes", source: localDefaults },
+ { applyTo: "root", source: rootDefaults },
+]);
+
+export async function loadFrameworkProgrammaticModule(
+ backing: Extract<AgentModuleBacking, { readonly kind: "programmatic" }>,
+): Promise<ProgrammaticModuleNamespace> {
+ return await loadProgrammaticModuleNamespace({
+ backing,
+ registries: [frameworkAgentSourceRegistry],
+ });
+}
diff --git a/packages/eve/src/harness/action-result-helpers.ts b/packages/eve/src/harness/action-result-helpers.ts
index f2be49fe5..e96a0c5ff 100644
--- a/packages/eve/src/harness/action-result-helpers.ts
+++ b/packages/eve/src/harness/action-result-helpers.ts
@@ -1,6 +1,6 @@
import type { ModelMessage, ToolSet, TypedToolError, TypedToolResult } from "ai";
-import type { RuntimeToolResultActionResult } from "#runtime/actions/types.js";
+import type { RuntimeToolResultActionResult } from "#shared/action-types.js";
import { toError } from "#shared/errors.js";
import { parseJsonValue, type JsonValue } from "#shared/json.js";
import {
diff --git a/packages/eve/src/harness/advertised-tools.ts b/packages/eve/src/harness/advertised-tools.ts
index 630d9ea0f..8b765d888 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 "#runtime/framework-tools/agent.js";
-import { TASK_TOOL_NAMES, TASK_UPDATE_TOOL_NAME } from "#runtime/framework-tools/tasks.js";
+import { AGENT_TOOL_NAME } from "#shared/agent-tool.js";
+import { TASK_TOOL_NAMES, TASK_UPDATE_TOOL_NAME } from "#shared/task-tool.js";
import { ROOT_RUNTIME_AGENT_NODE_ID } from "#runtime/graph.js";
import {
ensureWorkflowContinuationSecurity,
@@ -173,7 +173,7 @@ function shouldHideDelegationTool(
delegatedCaller: boolean | undefined,
): boolean {
if (definition.name === TASK_UPDATE_TOOL_NAME) return delegatedCaller !== true;
- if (isRootOnlyFrameworkTool(definition)) {
+ if (isRootOnlyTransitionalTool(definition)) {
return session.rootSessionId !== undefined || resolveSubagentDepth(session).currentDepth > 0;
}
@@ -186,7 +186,7 @@ function shouldHideDelegationTool(
* node's config, which self-delegated children share — session shape is
* the only signal that separates the root from its children.
*/
-function isRootOnlyFrameworkTool(definition: HarnessToolDefinition): boolean {
+function isRootOnlyTransitionalTool(definition: HarnessToolDefinition): boolean {
if (definition.rootOnly === true) return true;
if (
definition.name === AGENT_TOOL_NAME &&
diff --git a/packages/eve/src/harness/approval-delivery-coordinator.test.ts b/packages/eve/src/harness/approval-delivery-coordinator.test.ts
index 1a84c46ad..9e6a1e47f 100644
--- a/packages/eve/src/harness/approval-delivery-coordinator.test.ts
+++ b/packages/eve/src/harness/approval-delivery-coordinator.test.ts
@@ -5,7 +5,7 @@ import { settleDirectApprovalResponse } from "#harness/approval-candidates.js";
import { coordinateApprovalDelivery } from "#harness/approval-delivery-coordinator.js";
import { appendPendingInputBatch } from "#harness/pending-input-batches.js";
import type { HarnessSession } from "#harness/types.js";
-import type { InputRequest } from "#runtime/input/types.js";
+import type { InputRequest } from "#shared/input.js";
const request: InputRequest = {
action: { callId: "call-1", input: { marker: "durable" }, kind: "tool-call", toolName: "gate" },
diff --git a/packages/eve/src/harness/approval-delivery-coordinator.ts b/packages/eve/src/harness/approval-delivery-coordinator.ts
index 15fb6ba56..9c37be3ea 100644
--- a/packages/eve/src/harness/approval-delivery-coordinator.ts
+++ b/packages/eve/src/harness/approval-delivery-coordinator.ts
@@ -28,7 +28,7 @@ import {
import { isApprovalRequest } from "#harness/input-request-class.js";
import { getPendingInputBatches } from "#harness/pending-input-batches.js";
import type { HarnessSession, HarnessToolMap, StepInput } from "#harness/types.js";
-import type { InputRequest } from "#runtime/input/types.js";
+import type { InputRequest } from "#shared/input.js";
const UNAUTHENTICATED_APPROVAL_FEEDBACK = "Authentication is required to respond to this approval.";
const TEXT_APPROVAL_FEEDBACK =
diff --git a/packages/eve/src/harness/attachment-staging.integration.test.ts b/packages/eve/src/harness/attachment-staging.integration.test.ts
index 4c7759564..c1baafbd0 100644
--- a/packages/eve/src/harness/attachment-staging.integration.test.ts
+++ b/packages/eve/src/harness/attachment-staging.integration.test.ts
@@ -29,7 +29,7 @@ import {
describe("stageAttachmentsToSandbox (integration)", () => {
it("writes FilePart bytes into the active sandbox and rewrites data to an eve-sandbox: ref", async () => {
const sandbox = mockSandbox({ id: "sbx_integration" });
- const runtime = createTestRuntime();
+ const runtime = await createTestRuntime();
const csvBytes = Buffer.from("id,name\n1,alpha\n", "utf8");
const content: UserContent = [
@@ -75,7 +75,7 @@ describe("stageAttachmentsToSandbox (integration)", () => {
return await live.readTextFile({ path: filePath });
},
});
- const runtime = createTestRuntime({ tools: [readTool] });
+ const runtime = await createTestRuntime({ tools: [readTool] });
const payload = "id,name\n1,alpha\n";
const bytes = Buffer.from(payload, "utf8");
@@ -98,7 +98,7 @@ describe("stageAttachmentsToSandbox (integration)", () => {
it("passes text-only messages through without touching the sandbox", async () => {
const sandbox = mockSandbox({ id: "sbx_text" });
- const runtime = createTestRuntime();
+ const runtime = await createTestRuntime();
const result = await runtime.runAsSession({ sandbox }, async () =>
stageAttachmentsToSandbox("hello"),
@@ -110,7 +110,7 @@ describe("stageAttachmentsToSandbox (integration)", () => {
it("passes UserContent arrays with no FileParts through untouched", async () => {
const sandbox = mockSandbox({ id: "sbx_no_files" });
- const runtime = createTestRuntime();
+ const runtime = await createTestRuntime();
const content: UserContent = [{ type: "text", text: "just text" }];
const staged = await runtime.runAsSession({ sandbox }, async () =>
@@ -122,7 +122,7 @@ describe("stageAttachmentsToSandbox (integration)", () => {
});
it("returns the message unchanged when no SandboxKey is bound on the context", async () => {
- const runtime = createTestRuntime();
+ const runtime = await createTestRuntime();
const payload = Buffer.from("bytes", "utf8");
const content: UserContent = [
{ data: payload, filename: "orphan.txt", mediaType: "text/plain", type: "file" },
@@ -138,7 +138,7 @@ describe("stageAttachmentsToSandbox (integration)", () => {
it("dedupes repeated uploads of the same payload within one session", async () => {
const sandbox = mockSandbox({ id: "sbx_dedupe" });
- const runtime = createTestRuntime();
+ const runtime = await createTestRuntime();
const payload = Buffer.from("shared-payload", "utf8");
const firstStaged = await runtime.runAsSession({ sandbox }, async () => {
@@ -181,7 +181,7 @@ describe("stageAttachmentsToSandbox (integration)", () => {
};
const sandbox = mockSandbox({ id: "sbx_ref" });
- const runtime = createTestRuntime();
+ const runtime = await createTestRuntime();
const content: UserContent = [
{ type: "text", text: "what do you see?" },
{
@@ -230,7 +230,7 @@ describe("stageAttachmentsToSandbox (integration)", () => {
state: {},
};
const sandbox = mockSandbox({ id: "sbx_refine" });
- const runtime = createTestRuntime();
+ const runtime = await createTestRuntime();
const content: UserContent = [
{
data: new URL("https://example.com/image"),
@@ -259,7 +259,7 @@ describe("stageAttachmentsToSandbox (integration)", () => {
state: {},
};
const sandbox = mockSandbox({ id: "sbx_preserve" });
- const runtime = createTestRuntime();
+ const runtime = await createTestRuntime();
const content: UserContent = [
{
data: new URL("https://example.com/report.csv"),
@@ -281,7 +281,7 @@ describe("stageAttachmentsToSandbox (integration)", () => {
const adapter: ChannelAdapter<any> = { kind: "custom-channel", state: {} };
const fileUrl = new URL("https://example.com/a.bin");
const sandbox = mockSandbox({ id: "sbx_no_resolver" });
- const runtime = createTestRuntime();
+ const runtime = await createTestRuntime();
const content: UserContent = [
{ data: fileUrl, filename: "a.bin", mediaType: "application/octet-stream", type: "file" },
];
@@ -308,7 +308,7 @@ describe("stageAttachmentsToSandbox (integration)", () => {
state: {},
};
const sandbox = mockSandbox({ id: "sbx_threw" });
- const runtime = createTestRuntime();
+ const runtime = await createTestRuntime();
const content: UserContent = [
{
data: new URL("https://example.com/a.bin"),
@@ -339,7 +339,7 @@ describe("stageAttachmentsToSandbox (integration)", () => {
state: {},
};
const sandbox = mockSandbox({ id: "sbx_propagate" });
- const runtime = createTestRuntime();
+ const runtime = await createTestRuntime();
const content: UserContent = [
{
data: new URL("https://example.com/a.bin"),
@@ -358,7 +358,7 @@ describe("stageAttachmentsToSandbox (integration)", () => {
it("works alongside non-file parts in the same user message", async () => {
const sandbox = mockSandbox({ id: "sbx_mixed" });
- const runtime = createTestRuntime();
+ const runtime = await createTestRuntime();
const imageBytes = new Uint8Array([137, 80, 78, 71]);
const fileBytes = Buffer.from("text", "utf8");
@@ -392,7 +392,7 @@ describe("hydrateSandboxAttachments (integration)", () => {
it("hydrates small images inline as bytes — provider consumes them multimodally", async () => {
const sandbox = mockSandbox({ id: "sbx_hydrate_image" });
- const runtime = createTestRuntime();
+ const runtime = await createTestRuntime();
const stagedContent = (await runtime.runAsSession({ sandbox }, async () =>
stageAttachmentsToSandbox([
@@ -430,7 +430,7 @@ describe("hydrateSandboxAttachments (integration)", () => {
it("hydrates small PDFs inline as bytes — provider handles them natively", async () => {
const sandbox = mockSandbox({ id: "sbx_hydrate_pdf" });
- const runtime = createTestRuntime();
+ const runtime = await createTestRuntime();
const stagedContent = (await runtime.runAsSession({ sandbox }, async () =>
stageAttachmentsToSandbox([
@@ -455,7 +455,7 @@ describe("hydrateSandboxAttachments (integration)", () => {
it("substitutes non-inlinable FileParts with a text reference pointing at the sandbox path", async () => {
const sandbox = mockSandbox({ id: "sbx_hydrate_text_ref" });
- const runtime = createTestRuntime();
+ const runtime = await createTestRuntime();
const csvBytes = Buffer.from("id,name\n1,alpha\n", "utf8");
const stagedContent = (await runtime.runAsSession({ sandbox }, async () =>
@@ -491,7 +491,7 @@ describe("hydrateSandboxAttachments (integration)", () => {
it("treats oversized images (>3 MiB) as non-inlinable — renders a text reference instead of bytes", async () => {
const sandbox = mockSandbox({ id: "sbx_hydrate_big_image" });
- const runtime = createTestRuntime();
+ const runtime = await createTestRuntime();
// One byte over the 3 MiB cap so the ref size fails the inline
// check without allocating two massive buffers in the test.
const oversizedImage = Buffer.alloc(3 * 1024 * 1024 + 1, 0x89);
@@ -519,7 +519,7 @@ describe("hydrateSandboxAttachments (integration)", () => {
it("treats oversized PDFs (>20 MiB) as non-inlinable — renders a text reference instead of bytes", async () => {
const sandbox = mockSandbox({ id: "sbx_hydrate_big_pdf" });
- const runtime = createTestRuntime();
+ const runtime = await createTestRuntime();
const oversizedPdf = Buffer.alloc(20 * 1024 * 1024 + 1, 0x25);
const stagedContent = (await runtime.runAsSession({ sandbox }, async () =>
@@ -550,7 +550,7 @@ describe("hydrateSandboxAttachments (integration)", () => {
it("treats unknown binary media types as non-inlinable — renders a text reference", async () => {
const sandbox = mockSandbox({ id: "sbx_hydrate_binary" });
- const runtime = createTestRuntime();
+ const runtime = await createTestRuntime();
const binary = Buffer.from([0x00, 0x01, 0x02, 0x03]);
const stagedContent = (await runtime.runAsSession({ sandbox }, async () =>
@@ -581,7 +581,7 @@ describe("hydrateSandboxAttachments (integration)", () => {
it("returns the input array unchanged (no allocation) when no messages contain sandbox refs", async () => {
const sandbox = mockSandbox({ id: "sbx_noop" });
- const runtime = createTestRuntime();
+ const runtime = await createTestRuntime();
const messages = [{ content: "plain text", role: "user" as const }];
const hydrated = await runtime.runAsSession({ sandbox }, async () =>
@@ -593,7 +593,7 @@ describe("hydrateSandboxAttachments (integration)", () => {
it("is idempotent on inline Buffer FileParts", async () => {
const sandbox = mockSandbox({ id: "sbx_idempotent" });
- const runtime = createTestRuntime();
+ const runtime = await createTestRuntime();
const bytes = Buffer.from("hi", "utf8");
const messages = [
{
@@ -618,7 +618,7 @@ describe("hydrateSandboxAttachments (integration)", () => {
// Hydration must not fail the whole turn over it — it degrades to a
// text part so the run survives (#276).
const sandbox = mockSandbox({ id: "sbx_missing" });
- const runtime = createTestRuntime();
+ const runtime = await createTestRuntime();
// Ref pointing at a path that was never written. Use an
// inlinable media type so the byte-read path fires —
@@ -663,7 +663,7 @@ describe("hydrateSandboxAttachments (integration)", () => {
// resuming a durable session whose ephemeral sandbox is gone. The
// bytes are unreachable, but the turn must not fail.
const stagingSandbox = mockSandbox({ id: "sbx_resume_stage" });
- const runtime = createTestRuntime();
+ const runtime = await createTestRuntime();
const stagedContent = (await runtime.runAsSession({ sandbox: stagingSandbox }, async () =>
stageAttachmentsToSandbox([
@@ -697,7 +697,7 @@ describe("hydrateSandboxAttachments (integration)", () => {
// would still cost a full sandbox read per turn just to be
// thrown away.
const sandbox = mockSandbox({ id: "sbx_no_read" });
- const runtime = createTestRuntime();
+ const runtime = await createTestRuntime();
const csvBytes = Buffer.from("id,name\n1,alpha\n", "utf8");
const stagedContent = (await runtime.runAsSession({ sandbox }, async () =>
diff --git a/packages/eve/src/harness/authorization.test.ts b/packages/eve/src/harness/authorization.test.ts
index 16b9d19dd..d98bea374 100644
--- a/packages/eve/src/harness/authorization.test.ts
+++ b/packages/eve/src/harness/authorization.test.ts
@@ -11,7 +11,7 @@ import {
PendingAuthorizationResultKey,
setPendingAuthorization,
} from "#harness/authorization.js";
-import type { ConnectionPrincipal } from "#runtime/connections/types.js";
+import type { ConnectionPrincipal } from "#shared/connection-types.js";
afterEach(() => {
vi.unstubAllEnvs();
diff --git a/packages/eve/src/harness/authorization.ts b/packages/eve/src/harness/authorization.ts
index 6adeb53da..aaa3904d5 100644
--- a/packages/eve/src/harness/authorization.ts
+++ b/packages/eve/src/harness/authorization.ts
@@ -36,7 +36,7 @@ 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 { AuthorizationCallback, ConnectionPrincipal } from "#runtime/connections/types.js";
+import type { AuthorizationCallback, ConnectionPrincipal } from "#shared/connection-types.js";
import type { JsonValue } from "#public/types/json.js";
import { createEveConnectionCallbackRoutePath } from "#protocol/routes.js";
import { createUlid } from "#shared/ulid.js";
diff --git a/packages/eve/src/harness/emission.ts b/packages/eve/src/harness/emission.ts
index 8f5920b8b..c30333c40 100644
--- a/packages/eve/src/harness/emission.ts
+++ b/packages/eve/src/harness/emission.ts
@@ -48,10 +48,7 @@ import {
isInvalidToolCall,
resolveProviderToolCallRequest,
} from "#harness/tool-call-input-errors.js";
-import type {
- RuntimeActionRequest,
- RuntimeToolResultActionResult,
-} from "#runtime/actions/types.js";
+import type { RuntimeActionRequest, RuntimeToolResultActionResult } from "#shared/action-types.js";
import { createProviderStreamActionBatch } from "#harness/stream-actions.js";
import { normalizeModelStreamError } from "#harness/model-call-error.js";
import { createOrderedStreamEmitter } from "#harness/ordered-stream-emitter.js";
diff --git a/packages/eve/src/runtime/framework-tools/final-output.ts b/packages/eve/src/harness/final-output.ts
similarity index 92%
rename from packages/eve/src/runtime/framework-tools/final-output.ts
rename to packages/eve/src/harness/final-output.ts
index ec2aaa5bf..29d24112f 100644
--- a/packages/eve/src/runtime/framework-tools/final-output.ts
+++ b/packages/eve/src/harness/final-output.ts
@@ -4,7 +4,7 @@ import { toInputSchema } from "#shared/tool-schema.js";
import type { JsonObject } from "#shared/json.js";
/**
- * Stable model-visible name for the framework structured-output tool.
+ * Stable model-visible name for the kernel structured-output interception.
*/
export const FINAL_OUTPUT_TOOL_NAME = "final_output";
diff --git a/packages/eve/src/harness/handles/query.ts b/packages/eve/src/harness/handles/query.ts
index 63d9c9149..45f29b2bd 100644
--- a/packages/eve/src/harness/handles/query.ts
+++ b/packages/eve/src/harness/handles/query.ts
@@ -1,4 +1,4 @@
-import type { RuntimeActionResult, RuntimeSubagentChildResult } from "#runtime/actions/types.js";
+import type { RuntimeActionResult, RuntimeSubagentChildResult } from "#shared/action-types.js";
import { AGENT_HANDLES_STATE_KEY } from "#harness/handles/state-key.js";
import type { AgentHandle } from "#harness/handles/store.js";
import type { SessionStateMap } from "#harness/types.js";
diff --git a/packages/eve/src/harness/hitl/approval-input-requests.ts b/packages/eve/src/harness/hitl/approval-input-requests.ts
index 3449a0a02..c7fd76579 100644
--- a/packages/eve/src/harness/hitl/approval-input-requests.ts
+++ b/packages/eve/src/harness/hitl/approval-input-requests.ts
@@ -1,7 +1,7 @@
import type { ModelMessage } from "ai";
-import type { RuntimeToolResultActionResult } from "#runtime/actions/types.js";
-import type { InputRequest, InputResponse } from "#runtime/input/types.js";
+import type { RuntimeToolResultActionResult } from "#shared/action-types.js";
+import type { InputRequest, InputResponse } from "#shared/input.js";
import {
buildResolvedInputBatch,
resolveApprovalOutcome,
diff --git a/packages/eve/src/harness/hitl/approval-prompt.test.ts b/packages/eve/src/harness/hitl/approval-prompt.test.ts
index 8ed88fa0c..14e4cf818 100644
--- a/packages/eve/src/harness/hitl/approval-prompt.test.ts
+++ b/packages/eve/src/harness/hitl/approval-prompt.test.ts
@@ -4,7 +4,7 @@ import {
PENDING_APPROVALS_LABEL,
renderPendingApprovalsSnippet,
} from "#harness/hitl/approval-prompt.js";
-import type { InputRequest } from "#runtime/input/types.js";
+import type { InputRequest } from "#shared/input.js";
describe("renderPendingApprovalsSnippet", () => {
it("projects approval identity without exposing tool input", () => {
diff --git a/packages/eve/src/harness/hitl/approval-prompt.ts b/packages/eve/src/harness/hitl/approval-prompt.ts
index db1932b23..537d025f6 100644
--- a/packages/eve/src/harness/hitl/approval-prompt.ts
+++ b/packages/eve/src/harness/hitl/approval-prompt.ts
@@ -1,4 +1,4 @@
-import type { InputRequest } from "#runtime/input/types.js";
+import type { InputRequest } from "#shared/input.js";
import { isApprovalRequest } from "#harness/input-request-class.js";
/** Label prefixing the framework-injected pending-approval notice. */
diff --git a/packages/eve/src/harness/hitl/pending-input-resolution.ts b/packages/eve/src/harness/hitl/pending-input-resolution.ts
index d9d048d4f..4fa5d51ef 100644
--- a/packages/eve/src/harness/hitl/pending-input-resolution.ts
+++ b/packages/eve/src/harness/hitl/pending-input-resolution.ts
@@ -1,7 +1,7 @@
import type { ModelMessage } from "ai";
-import type { RuntimeToolResultActionResult } from "#runtime/actions/types.js";
-import type { InputResponse } from "#runtime/input/types.js";
+import type { RuntimeToolResultActionResult } from "#shared/action-types.js";
+import type { InputResponse } from "#shared/input.js";
import type { ResolvedInputBatch } from "#harness/input-request-resolution.js";
import type { PendingInputBatch, PendingInputBatchEvent } from "#harness/pending-input-batches.js";
import { queueDeferredStepInput } from "#harness/pending-input-batches.js";
diff --git a/packages/eve/src/harness/hitl/question-input-requests.ts b/packages/eve/src/harness/hitl/question-input-requests.ts
index 1672aec45..76b28cd39 100644
--- a/packages/eve/src/harness/hitl/question-input-requests.ts
+++ b/packages/eve/src/harness/hitl/question-input-requests.ts
@@ -1,6 +1,6 @@
import type { ModelMessage } from "ai";
-import type { InputRequest, InputResponse } from "#runtime/input/types.js";
+import type { InputRequest, InputResponse } from "#shared/input.js";
import { buildResolvedInputBatch } from "#harness/input-request-resolution.js";
import type { PendingInputBatch } from "#harness/pending-input-batches.js";
import {
diff --git a/packages/eve/src/harness/input-extraction.ts b/packages/eve/src/harness/input-extraction.ts
index bf70abcaa..09b4b2933 100644
--- a/packages/eve/src/harness/input-extraction.ts
+++ b/packages/eve/src/harness/input-extraction.ts
@@ -1,8 +1,8 @@
import type { ContentPart, ModelMessage, ToolSet, TypedToolCall } from "ai";
import { z } from "zod";
-import { ASK_QUESTION_TOOL_NAME } from "#runtime/framework-tools/ask-question.js";
-import type { InputRequest } from "#runtime/input/types.js";
+import { ASK_QUESTION_TOOL_NAME } from "#harness/request-input-tool.js";
+import type { InputRequest } from "#shared/input.js";
import { createRuntimeToolCallActionFromToolCall } from "#harness/tool-call-action.js";
// Persisted history parts lose AI SDK typing on the storage round trip. The
diff --git a/packages/eve/src/harness/input-request-class.test.ts b/packages/eve/src/harness/input-request-class.test.ts
index 2f168e212..69f11b784 100644
--- a/packages/eve/src/harness/input-request-class.test.ts
+++ b/packages/eve/src/harness/input-request-class.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
import { classifyInputRequest, isApprovalRequest } from "#harness/input-request-class.js";
import { createSessionLimitContinuationRequest } from "#harness/session-limit-continuation.js";
-import { ASK_QUESTION_TOOL_NAME } from "#runtime/framework-tools/ask-question.js";
+import { ASK_QUESTION_TOOL_NAME } from "#harness/request-input-tool.js";
describe("classifyInputRequest", () => {
const action = {
diff --git a/packages/eve/src/harness/input-request-class.ts b/packages/eve/src/harness/input-request-class.ts
index a127e187c..da86c8927 100644
--- a/packages/eve/src/harness/input-request-class.ts
+++ b/packages/eve/src/harness/input-request-class.ts
@@ -3,7 +3,7 @@
* the harness resolution path and protocol clients (e.g. the dev TUI's
* rendering decisions).
*/
-import type { InputRequest } from "#runtime/input/types.js";
+import type { InputRequest } from "#shared/input.js";
/** Returns true when the request gates an AI SDK tool call. */
export function isApprovalRequest(request: InputRequest): boolean {
diff --git a/packages/eve/src/harness/input-request-resolution.ts b/packages/eve/src/harness/input-request-resolution.ts
index 474caeb7e..64559380e 100644
--- a/packages/eve/src/harness/input-request-resolution.ts
+++ b/packages/eve/src/harness/input-request-resolution.ts
@@ -1,6 +1,6 @@
import { isApprovalRequest } from "#harness/input-request-class.js";
import type { PendingInputBatchEvent } from "#harness/pending-input-batches.js";
-import type { InputRequest, InputResponse } from "#runtime/input/types.js";
+import type { InputRequest, InputResponse } from "#shared/input.js";
const IGNORED_INPUT_REASON = "Ignored because the user continued without responding.";
export const TOOL_EXECUTION_DENIED_MESSAGE = "Tool execution was denied.";
diff --git a/packages/eve/src/harness/input-requests.test.ts b/packages/eve/src/harness/input-requests.test.ts
index 073eea5da..ac029c767 100644
--- a/packages/eve/src/harness/input-requests.test.ts
+++ b/packages/eve/src/harness/input-requests.test.ts
@@ -4,7 +4,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 type { InputRequest } from "#runtime/input/types.js";
+import type { InputRequest } from "#shared/input.js";
import type { HarnessToolDefinition } from "#harness/execute-tool.js";
import {
clearPendingSessionLimitPrompt,
diff --git a/packages/eve/src/harness/input-requests.ts b/packages/eve/src/harness/input-requests.ts
index 0c0309a3c..6edd4c10b 100644
--- a/packages/eve/src/harness/input-requests.ts
+++ b/packages/eve/src/harness/input-requests.ts
@@ -1,7 +1,7 @@
import type { ModelMessage } from "ai";
-import type { RuntimeToolCallActionRequest } from "#runtime/actions/types.js";
-import type { InputRequest, InputResponse } from "#runtime/input/types.js";
+import type { RuntimeToolCallActionRequest } from "#shared/action-types.js";
+import type { InputRequest, InputResponse } from "#shared/input.js";
import { resolveTextToResponses } from "#channel/resolve-text.js";
import {
getApprovedTools,
diff --git a/packages/eve/src/harness/instrumentation/native-events.ts b/packages/eve/src/harness/instrumentation/native-events.ts
index 0987c371f..3a5df1c9d 100644
--- a/packages/eve/src/harness/instrumentation/native-events.ts
+++ b/packages/eve/src/harness/instrumentation/native-events.ts
@@ -28,7 +28,7 @@ import {
import type { ResolvedInputBatch } from "#harness/input-requests.js";
import { RuntimeActionSettlementTimesKey } from "#harness/runtime-action-settlement-state.js";
import type { HandleEventFn } from "#harness/types.js";
-import type { RuntimeActionRequest, RuntimeActionResult } from "#runtime/actions/types.js";
+import type { RuntimeActionRequest, RuntimeActionResult } from "#shared/action-types.js";
import type { ChannelAudience } from "#shared/channel-audience.js";
export interface CreateInstrumentationHandleEventInput {
diff --git a/packages/eve/src/harness/messages.ts b/packages/eve/src/harness/messages.ts
index 1618611fa..acf4ab453 100644
--- a/packages/eve/src/harness/messages.ts
+++ b/packages/eve/src/harness/messages.ts
@@ -6,7 +6,7 @@ import type {
SessionAuthContext,
TurnCaller,
} from "#channel/types.js";
-import type { InputResponse } from "#runtime/input/types.js";
+import type { InputResponse } from "#shared/input.js";
import type { StepInput } from "#harness/types.js";
/**
diff --git a/packages/eve/src/harness/pending-input-batches.test.ts b/packages/eve/src/harness/pending-input-batches.test.ts
index baf761cc6..9bcd653eb 100644
--- a/packages/eve/src/harness/pending-input-batches.test.ts
+++ b/packages/eve/src/harness/pending-input-batches.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import type { InputRequest } from "#runtime/input/types.js";
+import type { InputRequest } from "#shared/input.js";
import { resolvePendingInput } from "#harness/input-requests.js";
import { appendPendingInputBatch, getPendingInputBatches } from "#harness/pending-input-batches.js";
import type { HarnessSession } from "#harness/types.js";
diff --git a/packages/eve/src/harness/pending-input-batches.ts b/packages/eve/src/harness/pending-input-batches.ts
index c252d7125..ee7680d11 100644
--- a/packages/eve/src/harness/pending-input-batches.ts
+++ b/packages/eve/src/harness/pending-input-batches.ts
@@ -1,6 +1,6 @@
import type { ModelMessage } from "ai";
-import type { InputRequest } from "#runtime/input/types.js";
+import type { InputRequest } from "#shared/input.js";
import type { HarnessSession, SessionStateMap, StepInput } from "#harness/types.js";
import { coalesceTurnInputs } from "#harness/messages.js";
diff --git a/packages/eve/src/runtime/framework-tools/web-search.ts b/packages/eve/src/harness/provider-tool-schemas.ts
similarity index 91%
rename from packages/eve/src/runtime/framework-tools/web-search.ts
rename to packages/eve/src/harness/provider-tool-schemas.ts
index 738dec014..5df7848a5 100644
--- a/packages/eve/src/runtime/framework-tools/web-search.ts
+++ b/packages/eve/src/harness/provider-tool-schemas.ts
@@ -1,6 +1,7 @@
-import type { ResolvedToolDefinition } from "#runtime/types.js";
import type { JsonObject } from "#shared/json.js";
+export const WEB_SEARCH_TOOL_NAME = "web_search";
+
/**
* Output schema for OpenAI's provider-managed `webSearch` tool.
*/
@@ -305,20 +306,3 @@ export const WEB_SEARCH_PARALLEL_OUTPUT_SCHEMA: JsonObject = {
},
],
};
-
-/**
- * Framework-provided web search tool definition.
- *
- * Omits `execute` — the execution layer skips executor creation for tools
- * without it, and the harness injects the real provider-managed tool at
- * step time.
- */
-export const WEB_SEARCH_TOOL_DEFINITION: ResolvedToolDefinition = {
- description:
- "Search the web for real-time information. Use this to find up-to-date information about current events, recent developments, or topics that may have changed since the knowledge cutoff.",
- inputSchema: null,
- logicalPath: "eve:framework/web-search",
- name: "web_search",
- sourceId: "eve:web-search-tool",
- sourceKind: "module",
-};
diff --git a/packages/eve/src/harness/provider-tools.test.ts b/packages/eve/src/harness/provider-tools.test.ts
index 6d3de9498..1329bc0b4 100644
--- a/packages/eve/src/harness/provider-tools.test.ts
+++ b/packages/eve/src/harness/provider-tools.test.ts
@@ -7,7 +7,7 @@ import {
WEB_SEARCH_GOOGLE_OUTPUT_SCHEMA,
WEB_SEARCH_OPENAI_OUTPUT_SCHEMA,
WEB_SEARCH_PARALLEL_OUTPUT_SCHEMA,
-} from "#runtime/framework-tools/web-search.js";
+} from "#harness/provider-tool-schemas.js";
import {
resolveFrameworkToolFromUpstreamType,
resolveWebSearchBackend,
diff --git a/packages/eve/src/harness/provider-tools.ts b/packages/eve/src/harness/provider-tools.ts
index 036c68d68..ee132affd 100644
--- a/packages/eve/src/harness/provider-tools.ts
+++ b/packages/eve/src/harness/provider-tools.ts
@@ -7,8 +7,8 @@ import {
WEB_SEARCH_GOOGLE_OUTPUT_SCHEMA,
WEB_SEARCH_OPENAI_OUTPUT_SCHEMA,
WEB_SEARCH_PARALLEL_OUTPUT_SCHEMA,
- WEB_SEARCH_TOOL_DEFINITION,
-} from "#runtime/framework-tools/web-search.js";
+ WEB_SEARCH_TOOL_NAME,
+} from "#harness/provider-tool-schemas.js";
import type { JsonObject } from "#shared/json.js";
import type { WebSearchProvider } from "#shared/web-search.js";
@@ -34,7 +34,7 @@ const UPSTREAM_TOOL_TYPE_TO_FRAMEWORK_NAME: Readonly<Record<string, string>> = {
// Anthropic's stable web search tool. The Bedrock and Vertex
// Anthropic backends reject this type because they only host the
// older Claude Messages surface.
- web_search_20250305: WEB_SEARCH_TOOL_DEFINITION.name,
+ web_search_20250305: WEB_SEARCH_TOOL_NAME,
};
/**
diff --git a/packages/eve/src/harness/proxy-input-requests.test.ts b/packages/eve/src/harness/proxy-input-requests.test.ts
index b58331241..d73226e9b 100644
--- a/packages/eve/src/harness/proxy-input-requests.test.ts
+++ b/packages/eve/src/harness/proxy-input-requests.test.ts
@@ -8,7 +8,7 @@ import {
upsertProxyInputRequests,
} from "#harness/proxy-input-requests.js";
import type { SubagentInputRequestHookPayload } from "#channel/types.js";
-import type { InputRequest, InputRequestKind } from "#runtime/input/types.js";
+import type { InputRequest, InputRequestKind } from "#shared/input.js";
import type { HarnessSession } from "#harness/types.js";
function createSession(state?: Record<string, unknown>): HarnessSession {
diff --git a/packages/eve/src/harness/proxy-input-requests.ts b/packages/eve/src/harness/proxy-input-requests.ts
index d24046b03..8315125b6 100644
--- a/packages/eve/src/harness/proxy-input-requests.ts
+++ b/packages/eve/src/harness/proxy-input-requests.ts
@@ -1,6 +1,6 @@
import type { SubagentInputRequestHookPayload } from "#channel/types.js";
import type { HarnessSession, SessionStateMap } from "#harness/types.js";
-import type { InputRequestKind } from "#runtime/input/types.js";
+import type { InputRequestKind } from "#shared/input.js";
import { isLoopbackHostname } from "#shared/network-address.js";
const PROXY_INPUT_REQUESTS_KEY = "eve.runtime.proxyInputRequests";
diff --git a/packages/eve/src/harness/request-input-tool.ts b/packages/eve/src/harness/request-input-tool.ts
new file mode 100644
index 000000000..f6e5f68e6
--- /dev/null
+++ b/packages/eve/src/harness/request-input-tool.ts
@@ -0,0 +1,4 @@
+/**
+ * Stable model-visible name for the framework question tool.
+ */
+export const ASK_QUESTION_TOOL_NAME = "ask_question";
diff --git a/packages/eve/src/harness/runtime-actions.ts b/packages/eve/src/harness/runtime-actions.ts
index 32f7c90be..7757f8833 100644
--- a/packages/eve/src/harness/runtime-actions.ts
+++ b/packages/eve/src/harness/runtime-actions.ts
@@ -3,7 +3,7 @@ import type { ModelMessage, ToolSet, TypedToolCall } from "ai";
import { createActionResultEvent, type UnstampedMessageStreamEvent } from "#protocol/message.js";
import { getRuntimeActionRequestKey } from "#runtime/actions/keys.js";
import { resolveRuntimeActionResultsForKeys } from "#runtime/actions/results.js";
-import type { RuntimeActionRequest, RuntimeActionResult } from "#runtime/actions/types.js";
+import type { RuntimeActionRequest, RuntimeActionResult } from "#shared/action-types.js";
import { parseJsonObject, type JsonObject } from "#shared/json.js";
import type { AgentTurnOutcome } from "#shared/agent-turn-outcome.js";
import { findRunningAgentHandle, isResultBoundToRunningHandle } from "#harness/handles/query.js";
diff --git a/packages/eve/src/harness/session-limit-continuation.ts b/packages/eve/src/harness/session-limit-continuation.ts
index c4a79b084..7198919bb 100644
--- a/packages/eve/src/harness/session-limit-continuation.ts
+++ b/packages/eve/src/harness/session-limit-continuation.ts
@@ -7,7 +7,7 @@
* identical session state always produces an identical prompt — no model call
* is involved.
*/
-import type { InputRequest, InputResponse } from "#runtime/input/types.js";
+import type { InputRequest, InputResponse } from "#shared/input.js";
import type { SessionTokenLimitViolation } from "#harness/turn-tag-state.js";
/** Synthetic action tool name carried by session-limit continuation requests. */
diff --git a/packages/eve/src/harness/stale-input-responses.ts b/packages/eve/src/harness/stale-input-responses.ts
index 3d9e8b44d..6fdab5cd6 100644
--- a/packages/eve/src/harness/stale-input-responses.ts
+++ b/packages/eve/src/harness/stale-input-responses.ts
@@ -5,7 +5,7 @@ import { isApprovalRequest } from "#harness/input-request-class.js";
import { appendUserContent, normalizeUserContent } from "#harness/messages.js";
import { isSessionLimitContinuationRequestId } from "#harness/session-limit-continuation.js";
import type { StepInput } from "#harness/types.js";
-import type { InputRequest, InputResponse } from "#runtime/input/types.js";
+import type { InputRequest, InputResponse } from "#shared/input.js";
type StaleResponseConversion =
| {
diff --git a/packages/eve/src/harness/step-hooks.ts b/packages/eve/src/harness/step-hooks.ts
index b01ee87e9..69a3502d6 100644
--- a/packages/eve/src/harness/step-hooks.ts
+++ b/packages/eve/src/harness/step-hooks.ts
@@ -32,7 +32,7 @@ import {
} from "#harness/prompt-cache.js";
import { createRuntimeActionRequestFromToolCall } from "#harness/runtime-actions.js";
import { isInvalidToolCall } from "#harness/tool-call-input-errors.js";
-import type { RuntimeToolResultActionResult } from "#runtime/actions/types.js";
+import type { RuntimeToolResultActionResult } from "#shared/action-types.js";
import {
type HarnessEmitFn,
type HarnessSession,
diff --git a/packages/eve/src/harness/stream-actions.ts b/packages/eve/src/harness/stream-actions.ts
index 4a9473b51..1cb76e984 100644
--- a/packages/eve/src/harness/stream-actions.ts
+++ b/packages/eve/src/harness/stream-actions.ts
@@ -1,5 +1,5 @@
import { createActionsRequestedEvent } from "#protocol/message.js";
-import type { RuntimeToolCallActionRequest } from "#runtime/actions/types.js";
+import type { RuntimeToolCallActionRequest } from "#shared/action-types.js";
import type { HarnessEmitFn } from "#harness/types.js";
interface ActionEventCoordinates {
diff --git a/packages/eve/src/harness/subagent-depth.ts b/packages/eve/src/harness/subagent-depth.ts
index 0641190f1..70e6da792 100644
--- a/packages/eve/src/harness/subagent-depth.ts
+++ b/packages/eve/src/harness/subagent-depth.ts
@@ -4,7 +4,7 @@ import type {
RuntimeActionRequest,
RuntimeRemoteAgentCallActionRequest,
RuntimeSubagentCallActionRequest,
-} from "#runtime/actions/types.js";
+} from "#shared/action-types.js";
export type DelegatedRuntimeActionRequest =
| RuntimeRemoteAgentCallActionRequest
diff --git a/packages/eve/src/harness/tool-call-action.ts b/packages/eve/src/harness/tool-call-action.ts
index 75dd41023..a591480c4 100644
--- a/packages/eve/src/harness/tool-call-action.ts
+++ b/packages/eve/src/harness/tool-call-action.ts
@@ -1,4 +1,4 @@
-import type { RuntimeToolCallActionRequest } from "#runtime/actions/types.js";
+import type { RuntimeToolCallActionRequest } from "#shared/action-types.js";
import { resolveToolCallInputObject } from "#harness/runtime-actions.js";
/** Creates a runtime tool-call action shape from an AI SDK tool call. */
diff --git a/packages/eve/src/harness/tool-call-input-errors.ts b/packages/eve/src/harness/tool-call-input-errors.ts
index 40a93345b..f6aa99c28 100644
--- a/packages/eve/src/harness/tool-call-input-errors.ts
+++ b/packages/eve/src/harness/tool-call-input-errors.ts
@@ -1,6 +1,6 @@
import type { ToolSet, TypedToolCall, TypedToolError } from "ai";
-import type { RuntimeToolCallActionRequest } from "#runtime/actions/types.js";
+import type { RuntimeToolCallActionRequest } from "#shared/action-types.js";
import { resolveToolCallInputObject } from "#harness/runtime-actions.js";
/**
diff --git a/packages/eve/src/harness/tool-input-validation.integration.test.ts b/packages/eve/src/harness/tool-input-validation.integration.test.ts
index b6ec9d5ae..2284dad36 100644
--- a/packages/eve/src/harness/tool-input-validation.integration.test.ts
+++ b/packages/eve/src/harness/tool-input-validation.integration.test.ts
@@ -5,10 +5,7 @@ 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,
- ASK_QUESTION_TOOL_DEFINITION,
-} from "#runtime/framework-tools/ask-question.js";
+import { ASK_QUESTION_INPUT_SCHEMA, askQuestion } from "#public/tools/ask-question.js";
import { serializeInputSchema } from "#shared/tool-schema.js";
const usage = {
@@ -90,7 +87,7 @@ describe("framework tool input validation (real AI SDK)", () => {
[
"ask_question",
{
- description: ASK_QUESTION_TOOL_DEFINITION.description,
+ description: askQuestion.description,
inputSchema: ASK_QUESTION_INPUT_SCHEMA,
name: "ask_question",
},
@@ -108,7 +105,7 @@ describe("framework tool input validation (real AI SDK)", () => {
system: "You are a test assistant.",
tools: [
{
- description: ASK_QUESTION_TOOL_DEFINITION.description,
+ description: askQuestion.description,
inputSchema: serializeInputSchema(ASK_QUESTION_INPUT_SCHEMA),
name: "ask_question",
},
diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.ts
index f502c9f11..b3081551c 100644
--- a/packages/eve/src/harness/tool-loop.ts
+++ b/packages/eve/src/harness/tool-loop.ts
@@ -71,14 +71,14 @@ import {
type UnstampedMessageStreamEvent,
} from "#protocol/message.js";
import type { RuntimeTraceContext } from "#protocol/message.js";
-import { ASK_QUESTION_TOOL_NAME } from "#runtime/framework-tools/ask-question.js";
+import { ASK_QUESTION_TOOL_NAME } from "#harness/request-input-tool.js";
import { resolveAgentsAnnouncement } from "#harness/handles/prompt.js";
import { getAgentHandleStore } from "#harness/handles/store.js";
import {
getWorkflowRuntimeActionInterrupts,
isWorkflowRuntimeActionInterrupt,
} from "#harness/workflow-runtime-action-state.js";
-import type { InputRequest } from "#runtime/input/types.js";
+import type { InputRequest } from "#shared/input.js";
import {
hydrateSandboxAttachments,
stageAttachmentsToSandbox,
@@ -157,7 +157,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 "#runtime/framework-tools/tasks.js";
+import { TASK_UPDATE_TOOL_NAME } from "#shared/task-tool.js";
import { readTaskIdFromInboxToken } from "#tasks/task-inbox-token.js";
import {
consumeDeferredStepInput,
@@ -253,10 +253,7 @@ import {
type WorkflowSandboxInterrupt,
unwrapWorkflowSandboxResult,
} from "#shared/workflow-sandbox.js";
-import {
- buildFinalOutputTool,
- FINAL_OUTPUT_TOOL_NAME,
-} from "#runtime/framework-tools/final-output.js";
+import { buildFinalOutputTool, FINAL_OUTPUT_TOOL_NAME } from "#harness/final-output.js";
import type { RuntimeModelReference } from "#runtime/agent/bootstrap.js";
import type { RunMode } from "#shared/run-mode.js";
import { createHistoryViewPreparer } from "#shared/history-view.js";
diff --git a/packages/eve/src/harness/tools.test.ts b/packages/eve/src/harness/tools.test.ts
index 2804d1da6..237ea3088 100644
--- a/packages/eve/src/harness/tools.test.ts
+++ b/packages/eve/src/harness/tools.test.ts
@@ -13,7 +13,7 @@ import {
WEB_SEARCH_GOOGLE_OUTPUT_SCHEMA,
WEB_SEARCH_OPENAI_OUTPUT_SCHEMA,
WEB_SEARCH_PARALLEL_OUTPUT_SCHEMA,
-} from "#runtime/framework-tools/web-search.js";
+} from "#harness/provider-tool-schemas.js";
import type { JsonObject } from "#shared/json.js";
import { isAsyncIterable } from "#shared/async-iterable.js";
import type { HarnessToolDefinition } from "#harness/execute-tool.js";
diff --git a/packages/eve/src/harness/tools.ts b/packages/eve/src/harness/tools.ts
index 5b371cfda..dbc14af04 100644
--- a/packages/eve/src/harness/tools.ts
+++ b/packages/eve/src/harness/tools.ts
@@ -3,8 +3,8 @@ import { type ToolApprovalConfiguration, type ToolApprovalStatus, type ToolSet,
import type { SessionCapabilities } from "#channel/types.js";
import type { RuntimeModelReference } from "#runtime/agent/bootstrap.js";
import type { WebSearchProvider } from "#shared/web-search.js";
-import { ASK_QUESTION_TOOL_NAME } from "#runtime/framework-tools/ask-question.js";
-import { WEB_SEARCH_TOOL_DEFINITION } from "#runtime/framework-tools/web-search.js";
+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";
@@ -300,14 +300,14 @@ export async function buildToolSetWithProviderTools(input: {
// Inject the real provider tool for web_search when the definition has
// no local execute (i.e. the framework definition uses the provider sentinel).
- if (!disabled?.has(WEB_SEARCH_TOOL_DEFINITION.name)) {
- const webSearchTool = input.tools.get(WEB_SEARCH_TOOL_DEFINITION.name);
+ if (!disabled?.has(WEB_SEARCH_TOOL_NAME)) {
+ const webSearchTool = input.tools.get(WEB_SEARCH_TOOL_NAME);
if (webSearchTool !== undefined && webSearchTool.execute === undefined) {
const backend = resolveWebSearchBackend(input.modelReference, input.webSearchProvider);
if (backend === null) {
- delete tools[WEB_SEARCH_TOOL_DEFINITION.name];
+ delete tools[WEB_SEARCH_TOOL_NAME];
} else {
- tools[WEB_SEARCH_TOOL_DEFINITION.name] = await resolveWebSearchProviderTool(backend);
+ tools[WEB_SEARCH_TOOL_NAME] = await resolveWebSearchProviderTool(backend);
}
}
}
diff --git a/packages/eve/src/harness/types.ts b/packages/eve/src/harness/types.ts
index 437ae624a..519e57669 100644
--- a/packages/eve/src/harness/types.ts
+++ b/packages/eve/src/harness/types.ts
@@ -4,9 +4,9 @@ import type { SessionAuthContext, SessionCapabilities } from "#channel/types.js"
import type { AlsContext } from "#context/container.js";
import type { UnstampedMessageStreamEvent, RuntimeIdentity } from "#protocol/message.js";
import type { RunMode } from "#shared/run-mode.js";
-import type { RuntimeActionResult } from "#runtime/actions/types.js";
+import type { RuntimeActionResult } from "#shared/action-types.js";
import type { RuntimeModelReference } from "#runtime/agent/bootstrap.js";
-import type { InputResponse } from "#runtime/input/types.js";
+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";
diff --git a/packages/eve/src/harness/workflow-runtime-action-state.ts b/packages/eve/src/harness/workflow-runtime-action-state.ts
index 36246045a..e6d4a3466 100644
--- a/packages/eve/src/harness/workflow-runtime-action-state.ts
+++ b/packages/eve/src/harness/workflow-runtime-action-state.ts
@@ -1,6 +1,6 @@
import type { HarnessRuntimeActionDefinition } from "#harness/execute-tool.js";
import { getRuntimeActionRequestKey } from "#runtime/actions/keys.js";
-import type { RuntimeActionRequest } from "#runtime/actions/types.js";
+import type { RuntimeActionRequest } from "#shared/action-types.js";
import type { JsonObject } from "#shared/json.js";
import type { WorkflowSandboxInterrupt } from "#shared/workflow-sandbox.js";
diff --git a/packages/eve/src/harness/workflow-subagent-limit.test.ts b/packages/eve/src/harness/workflow-subagent-limit.test.ts
index 7f3095aa7..346d4a076 100644
--- a/packages/eve/src/harness/workflow-subagent-limit.test.ts
+++ b/packages/eve/src/harness/workflow-subagent-limit.test.ts
@@ -6,7 +6,7 @@ import {
DEFAULT_WORKFLOW_MAX_SUBAGENTS,
planWorkflowSubagentDispatch,
} from "#harness/workflow-subagent-limit.js";
-import type { RuntimeActionRequest } from "#runtime/actions/types.js";
+import type { RuntimeActionRequest } from "#shared/action-types.js";
import type { WorkflowSandboxInterrupt } from "#shared/workflow-sandbox.js";
type LedgerEntry = WorkflowSandboxInterrupt["continuation"]["ledger"][number];
diff --git a/packages/eve/src/harness/workflow-subagent-limit.ts b/packages/eve/src/harness/workflow-subagent-limit.ts
index 405cb8fbd..574a665eb 100644
--- a/packages/eve/src/harness/workflow-subagent-limit.ts
+++ b/packages/eve/src/harness/workflow-subagent-limit.ts
@@ -1,4 +1,4 @@
-import type { RuntimeActionRequest } from "#runtime/actions/types.js";
+import type { RuntimeActionRequest } from "#shared/action-types.js";
import type { WorkflowSandboxInterrupt } from "#shared/workflow-sandbox.js";
/**
diff --git a/packages/eve/src/instrumentation/provider.ts b/packages/eve/src/instrumentation/provider.ts
new file mode 100644
index 000000000..3638ffd22
--- /dev/null
+++ b/packages/eve/src/instrumentation/provider.ts
@@ -0,0 +1,207 @@
+/**
+ * The provider contract authored under `agent/instrumentation/`.
+ *
+ * Reachable only with `experimental.instrumentationProviders` on. With the flag
+ * off nothing discovers that directory, so these types compile but never run.
+ */
+
+// Type-only, so nothing couples the provider definition to the harness at
+// runtime. The event shapes are eve's own vocabulary; deriving the handler map
+// from the union below is what keeps the public contract from drifting away
+// from the bus that feeds it.
+import type {
+ InstrumentationCapture,
+ InstrumentationEvent,
+} from "#harness/instrumentation/lifecycle.js";
+import type { JsonValue } from "#public/types/json.js";
+
+export type { JsonValue } from "#public/types/json.js";
+
+export type {
+ InstrumentationActionCompletedEvent,
+ InstrumentationActionFailedEvent,
+ InstrumentationActionKind,
+ InstrumentationActionOutcome,
+ InstrumentationActionOutput,
+ InstrumentationActionStartedEvent,
+ InstrumentationAttemptScope,
+ InstrumentationCapture,
+ InstrumentationChannelDeliveryInput,
+ InstrumentationChannelDeliveryOutcome,
+ InstrumentationChannelDeliveryRef,
+ InstrumentationChannelDeliveryStartedEvent,
+ InstrumentationChannelDeliveryTerminalEvent,
+ InstrumentationContentPart,
+ InstrumentationEvent,
+ InstrumentationInputKind,
+ InstrumentationInputOption,
+ InstrumentationInputOutcome,
+ InstrumentationInputRequest,
+ InstrumentationInputRequestedEvent,
+ InstrumentationInputResolvedEvent,
+ InstrumentationInputResponse,
+ InstrumentationModelCallCompletedEvent,
+ InstrumentationModelCallFailedEvent,
+ InstrumentationModelCallStartedEvent,
+ InstrumentationModelRef,
+ InstrumentationOperationRef,
+ InstrumentationParentLineage,
+ InstrumentationSessionFailedEvent,
+ InstrumentationSessionSettledEvent,
+ InstrumentationSessionStartedEvent,
+ InstrumentationSessionTransitionEvent,
+ InstrumentationStepAttemptMetadataEvent,
+ InstrumentationStepAttemptCompletedEvent,
+ InstrumentationStepAttemptFailedEvent,
+ InstrumentationStepAttemptStartedEvent,
+ InstrumentationStepAttemptTerminalEvent,
+ InstrumentationToolCallCompletedEvent,
+ InstrumentationToolCallFailedEvent,
+ InstrumentationToolCallStartedEvent,
+ InstrumentationToolOutput,
+ InstrumentationTraceContext,
+ InstrumentationTurnFailedEvent,
+ InstrumentationTurnSettledEvent,
+ InstrumentationTurnStartedEvent,
+ InstrumentationTurnTerminalEvent,
+ InstrumentationUsage,
+} from "#harness/instrumentation/lifecycle.js";
+
+/**
+ * Marks a value as having come from `defineInstrumentation` or a built-in
+ * factory.
+ *
+ * It does not say which layout the value belongs to: a provider and a legacy
+ * config both carry `events` and `setup`, so no value-level check separates
+ * them. The layout decides — `agent/instrumentation.ts` is read as a config and
+ * `agent/instrumentation/*.ts` as providers, and the two are mutually exclusive
+ * builds. The brand's job is only to catch a default export that never went
+ * through eve at all.
+ */
+export const PROVIDER = Symbol.for("eve.instrumentation.provider");
+
+/** Marks a slot the author turned off rather than configured. */
+export const DISABLED = Symbol.for("eve.instrumentation.disabled");
+
+/** Where the agent is running when `setup` fires. */
+export type InstrumentationEnvironment = "development" | "preview" | "production";
+
+/** The local eval run this server was started to serve. */
+export interface EvaluationRef {
+ readonly runId: string;
+}
+
+/**
+ * Passed to {@link InstrumentationProvider.setup} once at server startup,
+ * before any event is published.
+ */
+export interface ProviderSetupContext {
+ /** The agent name declared by `defineAgent`. */
+ readonly agentName: string;
+ /** Always supplied at runtime; optional for legacy setup-context compatibility. */
+ readonly environment?: InstrumentationEnvironment;
+ /** Present only when this server was started for a local `eve eval` run. */
+ readonly evaluation?: EvaluationRef;
+ /** The eve version running the agent. */
+ /** Always supplied at runtime; optional for legacy setup-context compatibility. */
+ readonly frameworkVersion?: string;
+}
+
+export interface ProviderState {
+ get(): JsonValue | undefined;
+ /** Stages a JSON value; `undefined` releases this operation's slot. */
+ set(value: JsonValue | undefined): void;
+}
+
+export interface ProviderContext {
+ readonly state: ProviderState;
+}
+
+/**
+ * One event handler.
+ *
+ * A handler can carry durable JSON state from a start to its terminal through
+ * `ctx.state`. eve scopes and releases that state by provider and operation.
+ */
+export type Handler<TEvent> = (event: TEvent, ctx: ProviderContext) => void | PromiseLike<void>;
+
+type EventForType<TEvent, TType> = TEvent extends { readonly type: infer TEventType }
+ ? TType extends TEventType
+ ? TEvent & { readonly type: TType }
+ : never
+ : never;
+
+/**
+ * The events a provider may handle, one optional handler per event type.
+ *
+ * Derived from the event union rather than written out, so a new event reaches
+ * providers the moment the bus can publish it.
+ */
+export type ProviderEvents = {
+ readonly [TType in InstrumentationEvent["type"]]?: Handler<
+ EventForType<InstrumentationEvent, TType>
+ >;
+};
+
+/**
+ * What an author writes for one file under `agent/instrumentation/`.
+ *
+ * Setup runs in slot order, but event handlers across authored providers run
+ * concurrently and are failure-isolated. Do not coordinate providers through
+ * completion order.
+ */
+export interface ProviderDefinition {
+ /**
+ * How much of each event this provider is handed. Defaults to `"metadata"`:
+ * structure, identity, usage, and timing, but not what was said.
+ *
+ * `"content"` adds the prompt, the response, tool arguments, and tool
+ * results. Asking is what makes eve build the projection at all, so a
+ * directory in which nobody asks never serializes a prompt.
+ */
+ readonly capture?: InstrumentationCapture;
+ readonly events?: ProviderEvents;
+ /** Runs once at server startup, before any event is published. */
+ readonly setup?: (context: ProviderSetupContext) => void | PromiseLike<void>;
+ /** Drains anything buffered. eve calls this before a session goes idle. */
+ readonly flush?: () => void | PromiseLike<void>;
+ /** Releases resources when the process is going away. */
+ readonly shutdown?: () => void | PromiseLike<void>;
+}
+
+/** A {@link ProviderDefinition} that has been through `defineInstrumentation`. */
+export type InstrumentationProvider = ProviderDefinition & {
+ readonly [PROVIDER]: true;
+};
+
+/** A slot the author turned off. eve registers nothing for it. */
+export interface InstrumentationDisabled {
+ readonly [DISABLED]: true;
+}
+
+/**
+ * Turns off the slot the file it is exported from names.
+ *
+ * Export it as the default of `agent/instrumentation/local.ts` to stop eve
+ * spooling local traces, for instance. Omitting the file entirely leaves eve's
+ * default in place, which is why turning one off takes a value.
+ */
+export function disableInstrumentation(): InstrumentationDisabled {
+ return { [DISABLED]: true };
+}
+
+export function isInstrumentationProvider(value: unknown): value is InstrumentationProvider {
+ return (
+ typeof value === "object" &&
+ value !== null &&
+ (value as Partial<InstrumentationProvider>)[PROVIDER] === true
+ );
+}
+
+export function isInstrumentationDisabled(value: unknown): value is InstrumentationDisabled {
+ return (
+ typeof value === "object" &&
+ value !== null &&
+ (value as Partial<InstrumentationDisabled>)[DISABLED] === true
+ );
+}
diff --git a/packages/eve/src/internal/application/compiled-artifacts.ts b/packages/eve/src/internal/application/compiled-artifacts.ts
index fe60097b7..131bd18dc 100644
--- a/packages/eve/src/internal/application/compiled-artifacts.ts
+++ b/packages/eve/src/internal/application/compiled-artifacts.ts
@@ -28,6 +28,14 @@ export type GeneratedInstrumentationLayout =
| { readonly kind: "file" }
| { readonly kind: "directory"; readonly slots: readonly string[] };
+type InstrumentationPluginLayout =
+ | InstrumentationLayout
+ | {
+ readonly kind: "module-map";
+ readonly moduleMapPath: string;
+ readonly sourceId: string;
+ };
+
/**
* Paths to the generated compiled-artifacts files shared by Nitro and the
* vendored workflow bundles for one application.
@@ -70,11 +78,14 @@ export async function writeCompiledArtifactsFiles(input: {
const bootstrapPath = join(input.outDir, "compiled-artifacts-bootstrap.mjs");
const instrumentationPluginPath = join(input.outDir, "compiled-artifacts-instrumentation.mjs");
const workflowWorldPluginPath = join(input.outDir, "compiled-artifacts-workflow-world.mjs");
- const layout = resolveInstrumentationLayout({
- agentRoot: input.compileResult.manifest.agentRoot,
- providersEnabled:
- input.compileResult.manifest.config.experimental?.instrumentationProviders ?? false,
- });
+ const providersEnabled =
+ input.compileResult.manifest.config.experimental?.instrumentationProviders ?? false;
+ const providerLayout = providersEnabled
+ ? resolveInstrumentationLayout({
+ agentRoot: input.compileResult.manifest.agentRoot,
+ providersEnabled: true,
+ })
+ : undefined;
await mkdir(input.outDir, { recursive: true });
await writeFile(
@@ -100,17 +111,32 @@ export async function writeCompiledArtifactsFiles(input: {
workflowWorldPluginPath,
};
- if (layout !== undefined) {
+ if (input.compileResult.manifest.instrumentation !== undefined) {
+ const sourceId = input.compileResult.manifest.instrumentation.sourceId;
await writeFile(
instrumentationPluginPath,
createInstrumentationPluginSource({
agentName: input.compileResult.manifest.config.name,
- layout,
+ layout: { kind: "module-map", moduleMapPath: bootstrapPath, sourceId },
}),
);
generatedArtifacts.instrumentationPluginPath = instrumentationPluginPath;
- generatedArtifacts.instrumentationLayout = generatedInstrumentationLayout(layout);
- generatedArtifacts.instrumentationSourcePaths = instrumentationSourcePathsOf(layout);
+ generatedArtifacts.instrumentationLayout = { kind: "file" };
+ const binding = input.compileResult.manifest.bindings[sourceId];
+ if (binding?.backing.kind === "filesystem") {
+ generatedArtifacts.instrumentationSourcePaths = [binding.backing.sourcePath];
+ }
+ } else if (providerLayout !== undefined) {
+ await writeFile(
+ instrumentationPluginPath,
+ createInstrumentationPluginSource({
+ agentName: input.compileResult.manifest.config.name,
+ layout: providerLayout,
+ }),
+ );
+ generatedArtifacts.instrumentationPluginPath = instrumentationPluginPath;
+ generatedArtifacts.instrumentationLayout = generatedInstrumentationLayout(providerLayout);
+ generatedArtifacts.instrumentationSourcePaths = instrumentationSourcePathsOf(providerLayout);
}
return generatedArtifacts;
@@ -156,7 +182,25 @@ export async function writeDevelopmentCompiledArtifactsFiles(input: {
workflowWorldPluginPath,
};
- if (materializedIndex.instrumentation !== undefined) {
+ if (input.compileResult.manifest.instrumentation !== undefined) {
+ const compileRoot = join(input.runtimeAppRoot, ".eve", "compile");
+ const moduleMapPath = join(input.outDir, "compiled-artifacts-instrumentation-source.mjs");
+ await copyFile(join(compileRoot, materializedIndex.moduleMap), moduleMapPath);
+ await writeFile(
+ instrumentationPluginPath,
+ createInstrumentationPluginSource({
+ agentName: input.compileResult.manifest.config.name,
+ layout: {
+ kind: "module-map",
+ moduleMapPath,
+ sourceId: input.compileResult.manifest.instrumentation.sourceId,
+ },
+ }),
+ );
+ generatedArtifacts.instrumentationPluginPath = instrumentationPluginPath;
+ generatedArtifacts.instrumentationLayout = { kind: "file" };
+ generatedArtifacts.instrumentationSourcePaths = [moduleMapPath];
+ } else if (materializedIndex.instrumentation !== undefined) {
const layout = await copyMaterializedInstrumentation({
instrumentation: materializedIndex.instrumentation,
outDir: input.outDir,
@@ -229,10 +273,8 @@ function createDevelopmentCompiledArtifactsBootstrapSource(agentName: string): s
].join("\n");
}
-function stripCompiledModuleMapExports(source: string): string {
- return source
- .replace(/^export const moduleMap = /m, "const moduleMap = ")
- .replace(/\nexport default moduleMap;\n?$/, "\n");
+function stripCompiledModuleMapDefaultExport(source: string): string {
+ return source.replace(/\nexport default moduleMap;\n?$/, "\n");
}
export async function createCompiledArtifactsBootstrapSource(input: {
@@ -242,11 +284,14 @@ export async function createCompiledArtifactsBootstrapSource(input: {
moduleMapPath: string;
}): Promise<string> {
const agentName = input.compileResult.manifest.config.name;
- const moduleMapSource = stripCompiledModuleMapExports(
+ const moduleMapSource = stripCompiledModuleMapDefaultExport(
createCompiledModuleMapSource({
importSpecifierStyle: "absolute",
manifest: input.compileResult.manifest,
moduleMapPath: input.moduleMapPath,
+ programmaticLoaderImportSpecifier: resolvePackageSourceFilePath(
+ "src/internal/programmatic-source-loader.ts",
+ ),
}),
).trim();
@@ -428,10 +473,29 @@ export function createDevelopmentWorkflowWorldPluginSource(input: {
*/
function createInstrumentationPluginSource(input: {
agentName: string;
- layout: InstrumentationLayout;
+ layout: InstrumentationPluginLayout;
}): string {
const agentName = JSON.stringify(input.agentName);
+ if (input.layout.kind === "module-map") {
+ const registerConfigPath = resolvePackageSourceFilePath(
+ "src/harness/instrumentation/config.ts",
+ );
+ return [
+ "// Generated by eve. Do not edit by hand.",
+ `import { moduleMap } from ${stringifyEsmImportSpecifier(input.layout.moduleMapPath)};`,
+ `import { registerInstrumentationConfig } from ${stringifyEsmImportSpecifier(registerConfigPath)};`,
+ "",
+ `const instrumentationModule = moduleMap.nodes["__root__"].modules[${JSON.stringify(input.layout.sourceId)}];`,
+ "if (instrumentationModule.default != null) {",
+ ` await registerInstrumentationConfig(instrumentationModule.default, { agentName: ${agentName} });`,
+ "}",
+ "",
+ "export default function installInstrumentationPlugin() {}",
+ "",
+ ].join("\n");
+ }
+
if (input.layout.kind === "file") {
const registerConfigPath = resolvePackageSourceFilePath(
"src/harness/instrumentation/config.ts",
diff --git a/packages/eve/src/internal/authored-definition/connection.test.ts b/packages/eve/src/internal/authored-definition/connection.test.ts
index 064ec40a8..afeeeca49 100644
--- a/packages/eve/src/internal/authored-definition/connection.test.ts
+++ b/packages/eve/src/internal/authored-definition/connection.test.ts
@@ -1,10 +1,7 @@
import { describe, expect, it } from "vitest";
import { normalizeMcpClientConnectionDefinition } from "#internal/authored-definition/connection.js";
-import type {
- ConnectionAuthDefinition,
- ConnectionAuthProvider,
-} from "#runtime/connections/types.js";
+import type { ConnectionAuthDefinition, ConnectionAuthProvider } from "#shared/connection-types.js";
const MSG = "Expected the connection export to match the public eve shape.";
diff --git a/packages/eve/src/internal/authored-definition/connection.ts b/packages/eve/src/internal/authored-definition/connection.ts
index 7d63ce7f2..5e903e2d4 100644
--- a/packages/eve/src/internal/authored-definition/connection.ts
+++ b/packages/eve/src/internal/authored-definition/connection.ts
@@ -9,8 +9,8 @@ import type {
ConnectionAuthDefinition,
HeadersDefinition,
ToolFilterDefinition,
-} from "#runtime/connections/types.js";
-import { normalizeAuthorizationSpec } from "#runtime/connections/validate-authorization.js";
+} from "#shared/connection-types.js";
+import { normalizeAuthorizationSpec } from "#shared/validate-authorization.js";
import { expectObjectRecord, expectOnlyKnownKeys } from "#internal/authored-module.js";
import { parseJsonValue } from "#shared/json.js";
diff --git a/packages/eve/src/internal/authored-definition/schema-backed.ts b/packages/eve/src/internal/authored-definition/schema-backed.ts
index 5b311ca2f..cd09e2df9 100644
--- a/packages/eve/src/internal/authored-definition/schema-backed.ts
+++ b/packages/eve/src/internal/authored-definition/schema-backed.ts
@@ -29,7 +29,12 @@ import {
* Identity is path-derived — the compiler stamps the filename slug onto
* the compiled entry. This shape never carries an authored `name`.
*/
-type NormalizedAuthoredTool = Readonly<Omit<InternalToolDefinitionWithExecuteFn, "name">>;
+type NormalizedAuthoredTool = Readonly<
+ Omit<InternalToolDefinitionWithExecuteFn, "name"> & {
+ readonly hasApproval: boolean;
+ readonly hasModelOutputProjection: boolean;
+ }
+>;
type MutableNormalizedAuthoredTool = {
-readonly [K in keyof NormalizedAuthoredTool]: NormalizedAuthoredTool[K];
};
@@ -113,6 +118,8 @@ export function normalizeToolDefinition(value: unknown, message: string): Normal
const definition: MutableNormalizedAuthoredTool = {
description: expectString(record.description, message),
execute: expectFunction(record.execute, message),
+ hasApproval: record.approval !== undefined,
+ hasModelOutputProjection: record.toModelOutput !== undefined,
inputSchema,
};
if (record.execution !== undefined) {
diff --git a/packages/eve/src/internal/authored-module-loader.scenario.test.ts b/packages/eve/src/internal/authored-module-loader.scenario.test.ts
index 1a26d80d0..2ab04383e 100644
--- a/packages/eve/src/internal/authored-module-loader.scenario.test.ts
+++ b/packages/eve/src/internal/authored-module-loader.scenario.test.ts
@@ -1057,7 +1057,11 @@ describe("loadAuthoredModuleNamespace", () => {
const manifest = await compileAgentManifest(discovered.manifest);
expect(manifest.config.build?.externalDependencies).toEqual(["external-only"]);
- expect(manifest.tools).toHaveLength(1);
+ expect(
+ manifest.tools.filter(
+ (tool) => manifest.bindings[tool.sourceId]?.owner.kind === "application",
+ ),
+ ).toHaveLength(1);
} finally {
await rm(workspaceRoot, { force: true, recursive: true });
}
@@ -1163,7 +1167,11 @@ describe("loadAuthoredModuleNamespace", () => {
expect(manifest.config.build?.externalDependencies).toEqual(["external-only"]);
expect(subagent?.agent.config.build?.externalDependencies).toEqual(["external-only"]);
- expect(subagent?.agent.tools).toHaveLength(1);
+ expect(
+ subagent?.agent.tools.filter(
+ (tool) => subagent.agent.bindings[tool.sourceId]?.owner.kind === "application",
+ ),
+ ).toHaveLength(1);
} finally {
await rm(workspaceRoot, { force: true, recursive: true });
}
diff --git a/packages/eve/src/internal/authored-module-map-loader.ts b/packages/eve/src/internal/authored-module-map-loader.ts
index 7e32c88ce..896626b9c 100644
--- a/packages/eve/src/internal/authored-module-map-loader.ts
+++ b/packages/eve/src/internal/authored-module-map-loader.ts
@@ -6,53 +6,35 @@ import type {
CompiledAgentNodeManifest,
CompiledAgentResources,
} from "#compiler/manifest.js";
-import type { ModuleSourceRef } from "#shared/source-ref.js";
import { ROOT_COMPILED_AGENT_NODE_ID } from "#compiler/manifest.js";
import {
- collectModuleRefsForManifest,
+ collectModuleBindingsForManifest,
compiledModuleMapSchema,
+ resolveCompiledModuleExtensionScopeNamespace,
type CompiledModuleMap,
} from "#compiler/module-map.js";
+import { loadFrameworkProgrammaticModule } from "#framework/sources/registry.js";
+import { loadAuthoredModuleNamespace } from "#internal/authored-module-loader.js";
+import { readMaterializedAuthoredModuleIndex } from "#internal/materialized-authored-modules.js";
import type { RuntimeDiskCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
import { loadCompiledManifest } from "#runtime/loaders/manifest.js";
import { formatValidationError } from "#runtime/validation.js";
-import { loadAuthoredModuleNamespace } from "#internal/authored-module-loader.js";
-import { readMaterializedAuthoredModuleIndex } from "#internal/materialized-authored-modules.js";
-/**
- * Ambient namespace read by `defineExtension` when it is evaluated from a module
- * the bundler could not scope — specifically a mount's extension package, which
- * resolves cross-package and so loads unbundled in the dev/eval loader. Set only
- * around the synchronous evaluation of one mount module (see below), so it never
- * leaks into consumer code.
- */
const EXT_CONFIG_SCOPE = Symbol.for("eve.ext-config-scope");
-/**
- * Loads a disk-backed module map by hydrating authored modules directly from
- * source. This is for dev/build flows that need tsconfig alias support and
- * source reloads without relying on Node's module cache for module-map.mjs.
- */
+/** Hydrates the compiled module map from the exact physical bindings in the manifest. */
export async function loadCompiledModuleMapFromAuthoredSource(input: {
readonly compiledArtifactsSource: RuntimeDiskCompiledArtifactsSource;
}): Promise<CompiledModuleMap> {
const manifest = await loadCompiledManifest({
compiledArtifactsSource: input.compiledArtifactsSource,
});
-
return await hydrateCompiledModuleMapFromManifest(
manifest,
input.compiledArtifactsSource.appRoot,
);
}
-interface ExtensionScopeIndex {
- /** Mount namespace (from `ext:<ns>:` source ids) to package namespace. */
- readonly byMountNamespace: ReadonlyMap<string, string>;
- /** Mount module source id to package namespace. */
- readonly byMountSourceId: ReadonlyMap<string, string>;
-}
-
async function hydrateCompiledModuleMapFromManifest(
manifest: CompiledAgentManifest,
runtimeAppRoot: string,
@@ -66,76 +48,47 @@ async function hydrateCompiledModuleMapFromManifest(
}
const nodes: CompiledModuleMap["nodes"] = {};
- const nodeManifests: Array<{
- additionalModuleRef?: ModuleSourceRef;
- agentRoot: string;
- externalDependencies: readonly string[];
- manifest: CompiledAgentNodeManifest | CompiledAgentResources;
- nodeId: string;
+ const nodeManifests: ReadonlyArray<{
+ readonly manifest: CompiledAgentNodeManifest | CompiledAgentResources;
+ readonly nodeId: string;
}> = [
- {
- agentRoot: manifest.agentRoot,
- externalDependencies: manifest.config.build?.externalDependencies ?? [],
- manifest,
- nodeId: ROOT_COMPILED_AGENT_NODE_ID,
- },
+ { manifest, nodeId: ROOT_COMPILED_AGENT_NODE_ID },
...[...manifest.subagents]
.sort((left, right) => left.nodeId.localeCompare(right.nodeId))
- .map((subagent) => ({
- additionalModuleRef: subagent.configResolver,
- agentRoot: subagent.agent.agentRoot,
- externalDependencies:
- subagent.configResolver === undefined
- ? (subagent.agent.config.build?.externalDependencies ?? [])
- : (subagent.configResolver.build?.externalDependencies ?? []),
- manifest: subagent.agent,
- nodeId: subagent.nodeId,
- })),
+ .map((subagent) => ({ manifest: subagent.agent, nodeId: subagent.nodeId })),
];
- const nodeManifestById = new Map(nodeManifests.map((entry) => [entry.nodeId, entry.manifest]));
- const parentNodeIdByChild = new Map(
- manifest.subagentEdges.map((edge) => [edge.childNodeId, edge.parentNodeId]),
- );
- const extensionNamespacesByNodeId = new Map<string, ReadonlyMap<string, string>>();
- const extensionNamespacesForNode = (nodeId: string): ReadonlyMap<string, string> => {
- const cached = extensionNamespacesByNodeId.get(nodeId);
- if (cached !== undefined) return cached;
-
- const parentNodeId = parentNodeIdByChild.get(nodeId);
- const namespaces = new Map(
- parentNodeId === undefined ? [] : extensionNamespacesForNode(parentNodeId),
- );
- for (const mount of nodeManifestById.get(nodeId)?.extensionMounts ?? []) {
- namespaces.set(mount.namespace, mount.packageNamespace);
- }
- extensionNamespacesByNodeId.set(nodeId, namespaces);
- return namespaces;
- };
-
- for (const nodeManifest of nodeManifests) {
- const scopeIndex: ExtensionScopeIndex = {
- byMountNamespace: extensionNamespacesForNode(nodeManifest.nodeId),
- byMountSourceId: new Map(
- nodeManifest.manifest.extensionMounts.map((mount) => [
- mount.mountSourceId,
- mount.packageNamespace,
- ]),
- ),
- };
- nodes[nodeManifest.nodeId] = {
- modules: await hydrateCompiledNodeScope({
- agentRoot: nodeManifest.agentRoot,
- additionalModuleRef: nodeManifest.additionalModuleRef,
- externalDependencies: nodeManifest.externalDependencies,
- manifest: nodeManifest.manifest,
- scopeIndex,
- }),
+ for (const node of nodeManifests) {
+ nodes[node.nodeId] = {
+ modules: await hydrateCompiledNodeScope(node.manifest),
};
}
+ return { nodes };
+}
- return {
- nodes,
- };
+async function hydrateCompiledNodeScope(
+ manifest: CompiledAgentNodeManifest | CompiledAgentResources,
+): Promise<CompiledModuleMap["nodes"][string]["modules"]> {
+ const mountScopes = new Map(
+ manifest.extensionMounts.map((mount) => [mount.mountSourceId, mount.packageNamespace]),
+ );
+ const container = globalThis as Record<symbol, unknown>;
+ const modules: CompiledModuleMap["nodes"][string]["modules"] = {};
+ for (const { binding, sourceId } of collectModuleBindingsForManifest(manifest)) {
+ const mountConfigScope = mountScopes.get(sourceId);
+ if (mountConfigScope !== undefined) container[EXT_CONFIG_SCOPE] = mountConfigScope;
+ try {
+ modules[sourceId] =
+ binding.backing.kind === "programmatic"
+ ? await loadFrameworkProgrammaticModule(binding.backing)
+ : await loadAuthoredModuleNamespace(binding.backing.sourcePath, {
+ externalDependencies: binding.backing.externalDependencies,
+ extensionScopeNamespace: resolveCompiledModuleExtensionScopeNamespace(binding),
+ });
+ } finally {
+ if (mountConfigScope !== undefined) container[EXT_CONFIG_SCOPE] = undefined;
+ }
+ }
+ return modules;
}
async function loadMaterializedCompiledModuleMap(input: {
@@ -149,66 +102,10 @@ async function loadMaterializedCompiledModuleMap(input: {
const parsed = compiledModuleMapSchema.safeParse(
moduleNamespace.moduleMap ?? moduleNamespace.default,
);
-
if (!parsed.success) {
throw new Error(
`Expected materialized authored module map "${moduleMapPath}" to export a valid compiled eve module map. ${formatValidationError(parsed.error)}`,
);
}
-
return parsed.data;
}
-
-/**
- * Resolves the package namespace an extension-owned source id belongs to.
- * Composed sources are keyed `ext:<mountNamespace>:<originalSourceId>`.
- */
-function extensionNamespaceForSourceId(
- sourceId: string,
- index: ExtensionScopeIndex,
-): string | undefined {
- const match = sourceId.match(/^ext:([^:]+):/);
- return match === null ? undefined : index.byMountNamespace.get(match[1]!);
-}
-
-async function hydrateCompiledNodeScope(input: {
- additionalModuleRef?: ModuleSourceRef;
- agentRoot: string;
- externalDependencies: readonly string[];
- manifest: CompiledAgentNodeManifest | CompiledAgentResources;
- scopeIndex: ExtensionScopeIndex;
-}): Promise<CompiledModuleMap["nodes"][string]["modules"]> {
- const refs = [
- ...collectModuleRefsForManifest(input.manifest),
- ...(input.additionalModuleRef === undefined ? [] : [input.additionalModuleRef]),
- ].sort((left, right) => left.sourceId.localeCompare(right.sourceId));
- const container = globalThis as Record<symbol, unknown>;
- const modules: CompiledModuleMap["nodes"][string]["modules"] = {};
-
- for (const ref of refs) {
- const modulePath = join(input.agentRoot, ref.logicalPath);
- const extensionScopeNamespace = extensionNamespaceForSourceId(ref.sourceId, input.scopeIndex);
-
- // A mount module (e.g. `agent/extensions/crm.ts`) imports the extension
- // package cross-package, so its config handle loads unbundled and the
- // bundler cannot scope it. Set the ambient config scope around this one
- // synchronous load so the mount's `defineExtension` binds under the package
- // namespace — matching what the extension's own bundled tools read.
- const mountConfigScope = input.scopeIndex.byMountSourceId.get(ref.sourceId);
- if (mountConfigScope !== undefined) {
- container[EXT_CONFIG_SCOPE] = mountConfigScope;
- }
- try {
- modules[ref.sourceId] = await loadAuthoredModuleNamespace(modulePath, {
- externalDependencies: input.externalDependencies,
- extensionScopeNamespace,
- });
- } finally {
- if (mountConfigScope !== undefined) {
- container[EXT_CONFIG_SCOPE] = undefined;
- }
- }
- }
-
- return modules;
-}
diff --git a/packages/eve/src/internal/compiled-manifest-fingerprint.test.ts b/packages/eve/src/internal/compiled-manifest-fingerprint.test.ts
index ece211693..da5c983ea 100644
--- a/packages/eve/src/internal/compiled-manifest-fingerprint.test.ts
+++ b/packages/eve/src/internal/compiled-manifest-fingerprint.test.ts
@@ -1,30 +1,31 @@
import { join } from "node:path";
import { describe, expect, it } from "vitest";
-import { createCompiledAgentManifest } from "#compiler/manifest.js";
+import { compileFromMemory } from "#compiler/compile-from-memory.js";
import { serializeCompiledManifestForFingerprint } from "#internal/compiled-manifest-fingerprint.js";
-function manifestWithRoot(runtimeAppRoot: string, agentRoot = join(runtimeAppRoot, "agent")) {
- return createCompiledAgentManifest({
- agentRoot,
- appRoot: runtimeAppRoot,
- config: {
- model: { id: "openai/gpt-5-mini", routing: { kind: "gateway", target: "openai" } },
+async function manifestWithRoot(runtimeAppRoot: string, agentRoot = join(runtimeAppRoot, "agent")) {
+ return (
+ await compileFromMemory({
+ agentRoot,
+ appRoot: runtimeAppRoot,
+ model: "openai/gpt-5.4",
name: "fingerprint-test",
- },
- });
+ revision: "fingerprint-test:v1",
+ })
+ ).manifest;
}
describe("serializeCompiledManifestForFingerprint", () => {
- it("serializes identical content under different snapshot roots identically", () => {
+ it("serializes identical content under different snapshot roots identically", async () => {
const firstRoot = "/tmp/snapshots/generation-a/source/app";
const secondRoot = "/tmp/snapshots/generation-b/source/app";
const first = serializeCompiledManifestForFingerprint({
- manifest: manifestWithRoot(firstRoot),
+ manifest: await manifestWithRoot(firstRoot),
runtimeAppRoot: firstRoot,
});
const second = serializeCompiledManifestForFingerprint({
- manifest: manifestWithRoot(secondRoot),
+ manifest: await manifestWithRoot(secondRoot),
runtimeAppRoot: secondRoot,
});
@@ -33,10 +34,10 @@ describe("serializeCompiledManifestForFingerprint", () => {
expect(first).not.toContain("generation-a");
});
- it("keeps absolute paths outside the runtime root verbatim", () => {
+ it("keeps absolute paths outside the runtime root verbatim", async () => {
const runtimeAppRoot = "/tmp/snapshots/generation-a/source/app";
const serialized = serializeCompiledManifestForFingerprint({
- manifest: manifestWithRoot(runtimeAppRoot, "/somewhere/else/agent"),
+ manifest: await manifestWithRoot(runtimeAppRoot, "/somewhere/else/agent"),
runtimeAppRoot,
});
diff --git a/packages/eve/src/internal/invocation/agent-invocation.ts b/packages/eve/src/internal/invocation/agent-invocation.ts
index ef201852a..bc320dcda 100644
--- a/packages/eve/src/internal/invocation/agent-invocation.ts
+++ b/packages/eve/src/internal/invocation/agent-invocation.ts
@@ -1,5 +1,5 @@
import type { ConnectionAuthorizationChallenge } from "#public/connections/errors.js";
-import type { InputRequest } from "#runtime/input/types.js";
+import type { InputRequest } from "#shared/input.js";
import type { JsonValue } from "#shared/json.js";
export interface AgentInvocationAuthorizationRequest {
diff --git a/packages/eve/src/internal/invocation/workflow-execution.ts b/packages/eve/src/internal/invocation/workflow-execution.ts
index 02fe1b94d..ed194ae22 100644
--- a/packages/eve/src/internal/invocation/workflow-execution.ts
+++ b/packages/eve/src/internal/invocation/workflow-execution.ts
@@ -23,7 +23,7 @@ import {
import type { RouteSessionCreator } from "#internal/nitro/routes/channel-route-context.js";
import { getRun, getWorld } from "#internal/workflow/runtime.js";
import type { HandleMessageStreamEvent } from "#protocol/message.js";
-import type { InputRequest, InputResponse } from "#runtime/input/types.js";
+import type { InputRequest, InputResponse } from "#shared/input.js";
import type { JsonObject, JsonValue } from "#shared/json.js";
import { parseJsonValue } from "#shared/json.js";
diff --git a/packages/eve/src/internal/materialized-authored-modules.ts b/packages/eve/src/internal/materialized-authored-modules.ts
index 8d3cb53ff..e228b6e1f 100644
--- a/packages/eve/src/internal/materialized-authored-modules.ts
+++ b/packages/eve/src/internal/materialized-authored-modules.ts
@@ -47,21 +47,16 @@ export async function prepareMaterializedAuthoredModules(input: {
readonly moduleMapPath: string;
}): Promise<PreparedMaterializedAuthoredModules> {
const moduleMapCode = await bundleAuthoredModuleMapForGeneration(input);
- const layout = resolveInstrumentationLayout({
- agentRoot: input.manifest.agentRoot,
- providersEnabled: input.manifest.config.experimental?.instrumentationProviders ?? false,
- });
+ const providersEnabled = input.manifest.config.experimental?.instrumentationProviders ?? false;
+ const layout = providersEnabled
+ ? resolveInstrumentationLayout({ agentRoot: input.manifest.agentRoot, providersEnabled: true })
+ : undefined;
const externalDependencies = input.manifest.config.build?.externalDependencies ?? [];
const bundleInstrumentationModule = async (sourcePath: string): Promise<string> =>
await bundleAuthoredModuleForGeneration(sourcePath, { externalDependencies });
let instrumentation: PreparedMaterializedInstrumentation | undefined;
- if (layout?.kind === "file") {
- instrumentation = {
- kind: "file",
- moduleCode: await bundleInstrumentationModule(layout.modulePath),
- };
- } else if (layout?.kind === "directory") {
+ if (layout?.kind === "directory") {
const moduleCodeBySlot: Record<string, string> = {};
for (const [slot, sourcePath] of Object.entries(layout.modulePathsBySlot)) {
moduleCodeBySlot[slot] = await bundleInstrumentationModule(sourcePath);
diff --git a/packages/eve/src/internal/nitro/dev-generation-artifacts.scenario.test.ts b/packages/eve/src/internal/nitro/dev-generation-artifacts.scenario.test.ts
index 352b3c456..e0a8bd570 100644
--- a/packages/eve/src/internal/nitro/dev-generation-artifacts.scenario.test.ts
+++ b/packages/eve/src/internal/nitro/dev-generation-artifacts.scenario.test.ts
@@ -75,7 +75,9 @@ describe("development generation artifacts", () => {
),
});
const subagent = compileResult.manifest.subagents[0];
- const subagentToolSourceId = subagent?.agent.tools[0]?.sourceId;
+ const subagentToolSourceId = subagent?.agent.tools.find(
+ (tool) => tool.name === "read_shared",
+ )?.sourceId;
expect(subagentToolSourceId).toBeDefined();
const subagentTool = moduleMap.nodes[subagent!.nodeId]?.modules[subagentToolSourceId!] as {
default: { execute(): string };
@@ -164,8 +166,11 @@ describe("development generation artifacts", () => {
});
const compileResult = await compileAgent({ startPath: app.appRoot });
+ const snapshot = await stageDevelopmentGeneration(compileResult);
const moduleMap = await loadCompiledModuleMapFromAuthoredSource({
- compiledArtifactsSource: createAuthoredSourceRuntimeCompiledArtifactsSource(app.appRoot),
+ compiledArtifactsSource: createAuthoredSourceRuntimeCompiledArtifactsSource(
+ snapshot.runtimeAppRoot,
+ ),
});
const subagent = compileResult.manifest.subagents[0];
if (subagent?.configResolver === undefined) throw new Error("expected a dynamic subagent");
@@ -385,7 +390,9 @@ describe("development generation artifacts", () => {
snapshot.runtimeAppRoot,
),
});
- const toolSourceId = compileResult.manifest.tools[0]?.sourceId;
+ const toolSourceId = compileResult.manifest.tools.find(
+ (tool) => tool.name === "read_dynamic",
+ )?.sourceId;
expect(toolSourceId).toBeDefined();
const tool = moduleMap.nodes[ROOT_COMPILED_AGENT_NODE_ID]?.modules[toolSourceId!] as {
default: { execute(): Promise<string> };
@@ -454,7 +461,9 @@ describe("development generation artifacts", () => {
snapshot.runtimeAppRoot,
),
});
- const toolSourceId = compileResult.manifest.tools[0]?.sourceId;
+ const toolSourceId = compileResult.manifest.tools.find(
+ (tool) => tool.name === "read_value",
+ )?.sourceId;
expect(toolSourceId).toBeDefined();
const tool = moduleMap.nodes[ROOT_COMPILED_AGENT_NODE_ID]?.modules[toolSourceId!] as {
default: { execute(): string };
@@ -491,17 +500,15 @@ describe("development generation artifacts", () => {
join(first.runtimeAppRoot, ".eve", "compile", "authored-modules.json"),
"utf8",
),
- ) as { readonly instrumentation?: MaterializedInstrumentation };
- if (firstIndex.instrumentation?.kind !== "file") {
- throw new Error("expected materialized file instrumentation");
- }
- const materializedInstrumentation = await readFile(
- join(first.runtimeAppRoot, ".eve", "compile", firstIndex.instrumentation.modulePath),
+ ) as { readonly instrumentation?: MaterializedInstrumentation; readonly moduleMap: string };
+ expect(firstIndex.instrumentation).toBeUndefined();
+ const materializedModuleMap = await readFile(
+ join(first.runtimeAppRoot, ".eve", "compile", firstIndex.moduleMap),
"utf8",
);
expect(first.fingerprint).toBe(identical.fingerprint);
- expect(materializedInstrumentation).not.toContain("/.eve/dev-runtime/snapshots/");
+ expect(materializedModuleMap).not.toContain(first.runtimeAppRoot.replaceAll("\\", "/"));
await writeFile(
join(app.appRoot, "agent", "instructions.md"),
@@ -526,9 +533,9 @@ describe("development generation artifacts", () => {
const changed = await stageDevelopmentGeneration(changedCompile);
expect(changed.fingerprint).not.toBe(first.fingerprint);
- await expect(
- readFile(join(changed.runtimeAppRoot, ".eve", "compile", "authored-modules.json"), "utf8"),
- ).resolves.toContain('"instrumentation"');
+ expect(changedCompile.manifest.instrumentation).toMatchObject({
+ logicalPath: "instrumentation.mjs",
+ });
await writeFile(
join(app.appRoot, "agent", "skills", "guide.md"),
diff --git a/packages/eve/src/internal/nitro/dev-runtime-artifacts.integration.test.ts b/packages/eve/src/internal/nitro/dev-runtime-artifacts.integration.test.ts
index 6b38bea02..fa6e62492 100644
--- a/packages/eve/src/internal/nitro/dev-runtime-artifacts.integration.test.ts
+++ b/packages/eve/src/internal/nitro/dev-runtime-artifacts.integration.test.ts
@@ -9,13 +9,13 @@ import {
utimes,
writeFile,
} from "node:fs/promises";
-import { join } from "node:path";
+import { join, resolve } from "node:path";
import { describe, expect, it } from "vitest";
import type { CompileAgentResult } from "#compiler/compile-agent.js";
-import { createCompiledAgentManifest, ROOT_COMPILED_AGENT_NODE_ID } from "#compiler/manifest.js";
-import { createCompiledModuleMapSource } from "#compiler/module-map.js";
+import { compileAgent } from "#compiler/compile-agent.js";
+import { ROOT_COMPILED_AGENT_NODE_ID } from "#compiler/manifest.js";
import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";
import { createDiskRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";
@@ -55,13 +55,14 @@ async function createNextStyleImportSnapshotFixture(): Promise<{ readonly appRoo
const appRoot = await createScratchDirectory("eve-dev-runtime-next-imports-");
const agentRoot = join(appRoot, "agent");
const compileDirectoryPath = join(appRoot, ".eve", "compile");
- const manifestPath = join(compileDirectoryPath, "compiled-agent-manifest.json");
const moduleMapPath = join(compileDirectoryPath, "module-map.mjs");
await mkdir(agentRoot, { recursive: true });
+ await mkdir(join(appRoot, "node_modules"), { recursive: true });
await mkdir(join(appRoot, "src", "features", "editor", "eve"), { recursive: true });
await mkdir(compileDirectoryPath, { recursive: true });
await writeFile(join(appRoot, "package.json"), '{"name":"next-agent","type":"module"}\n');
+ await symlink(resolve(import.meta.dirname, "../../.."), join(appRoot, "node_modules", "eve"));
await writeFile(
join(appRoot, "tsconfig.json"),
`${JSON.stringify(
@@ -83,6 +84,7 @@ async function createNextStyleImportSnapshotFixture(): Promise<{ readonly appRoo
'import { createEveModelRouter } from "./model-router";',
'import { authSessionAuth } from "@/features/editor/eve/auth-session";',
"",
+ 'export default { model: "openai/gpt-5.4-mini" };',
"export const routed = createEveModelRouter(authSessionAuth);",
"",
].join("\n"),
@@ -100,49 +102,13 @@ async function createNextStyleImportSnapshotFixture(): Promise<{ readonly appRoo
join(appRoot, "src", "features", "editor", "eve", "auth-session.ts"),
'export const authSessionAuth = "session-auth";\n',
);
+ await writeFile(join(agentRoot, "instructions.md"), "Use the routed model.\n");
- const manifest = createCompiledAgentManifest({
- agentRoot,
- appRoot,
- config: {
- model: {
- id: "openai/gpt-5.4-mini",
- routing: {
- kind: "gateway",
- target: "openai/gpt-5.4-mini",
- },
- },
- name: "Next Imports Agent",
- source: {
- logicalPath: "agent.ts",
- sourceId: "agent.ts",
- sourceKind: "module",
- },
- },
- instructions: [
- {
- content: "Use the routed model.",
- logicalPath: "instructions.md",
- name: "instructions",
- role: "system",
- sourceId: "instructions.md",
- sourceKind: "markdown",
- },
- ],
- });
-
- await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
- await writeFile(
- moduleMapPath,
- createCompiledModuleMapSource({
- manifest,
- moduleMapPath,
- }),
- );
+ const compileResult = await compileAgent({ startPath: appRoot });
await publishDevelopmentGeneration({
- manifest,
- paths: { compileDirectoryPath, moduleMapPath },
+ ...compileResult,
+ paths: { ...compileResult.paths, compileDirectoryPath, moduleMapPath },
project: { appRoot },
} as CompileAgentResult);
@@ -291,7 +257,8 @@ describe("development runtime artifact snapshots", () => {
);
expect(existsSync(join(snapshot.runtimeAppRoot, "agent"))).toBe(false);
expect(existsSync(join(snapshot.runtimeAppRoot, ".devtools"))).toBe(false);
- expect(existsSync(join(snapshot.runtimeAppRoot, "node_modules"))).toBe(false);
+ expect(existsSync(join(snapshot.runtimeAppRoot, "node_modules", "eve"))).toBe(true);
+ expect(existsSync(join(snapshot.runtimeAppRoot, "node_modules", "heavy-package"))).toBe(false);
expect(existsSync(join(snapshot.runtimeAppRoot, ".env"))).toBe(false);
expect(existsSync(join(snapshot.runtimeAppRoot, ".env.local"))).toBe(false);
expect(existsSync(join(snapshot.runtimeAppRoot, ".env.example"))).toBe(false);
diff --git a/packages/eve/src/internal/nitro/dev-runtime-artifacts.ts b/packages/eve/src/internal/nitro/dev-runtime-artifacts.ts
index d458923c0..138428f24 100644
--- a/packages/eve/src/internal/nitro/dev-runtime-artifacts.ts
+++ b/packages/eve/src/internal/nitro/dev-runtime-artifacts.ts
@@ -18,6 +18,7 @@ import {
recordRetiredDevelopmentRuntimeArtifactsSnapshot,
} from "#internal/nitro/dev-runtime-artifacts-retention.js";
import { renameWithTransientBusyRetry } from "#shared/rename-with-retry.js";
+import { resolvePackageRoot } from "#internal/application/package.js";
const DEV_RUNTIME_ARTIFACTS_DIRECTORY = "dev-runtime";
const DEV_RUNTIME_ARTIFACTS_GENERATION_METADATA = "generation.json";
@@ -95,6 +96,7 @@ export async function stageDevelopmentRuntimeArtifactsSnapshot(
try {
await copyDevelopmentSourceSnapshot(sourceSnapshotPlan);
+ await mountFrameworkPackage(sourceSnapshotPlan.runtimeAppRoot);
await mountExtensionExternalDependencies({
manifest: compileResult.manifest,
runtimeAppRoot: sourceSnapshotPlan.runtimeAppRoot,
@@ -144,6 +146,13 @@ export async function stageDevelopmentRuntimeArtifactsSnapshot(
};
}
+async function mountFrameworkPackage(runtimeAppRoot: string): Promise<void> {
+ const mountPath = join(runtimeAppRoot, "node_modules", "eve");
+ await mkdir(dirname(mountPath), { recursive: true });
+ await rm(mountPath, { force: true, recursive: true });
+ await symlink(resolvePackageRoot(), mountPath, "junction");
+}
+
async function mountExtensionExternalDependencies(input: {
readonly manifest?: CompiledAgentManifest;
readonly runtimeAppRoot: string;
diff --git a/packages/eve/src/internal/nitro/host/application-route-registry.test.ts b/packages/eve/src/internal/nitro/host/application-route-registry.test.ts
index 256317151..a7ce93226 100644
--- a/packages/eve/src/internal/nitro/host/application-route-registry.test.ts
+++ b/packages/eve/src/internal/nitro/host/application-route-registry.test.ts
@@ -1,132 +1,66 @@
import { describe, expect, it } from "vitest";
+import { compileFromMemory } from "#compiler/compile-from-memory.js";
+import { createApplicationRouteRegistry } from "#internal/nitro/host/application-route-registry.js";
import {
- createApplicationRouteRegistryFromInput,
- mergeApplicationChannelRouteRegistrations,
-} from "#internal/nitro/host/application-route-registry.js";
+ EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN,
+ EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH,
+ EVE_HEALTH_ROUTE_PATH,
+ EVE_INFO_ROUTE_PATH,
+} from "#protocol/routes.js";
+import { EVE_WORKFLOW_FLOW_ROUTE_PATH } from "#internal/workflow-bundle/eve-service-route-output.js";
-describe("mergeApplicationChannelRouteRegistrations", () => {
- it("applies authored overrides, disabled defaults, and framework-first route dedupe", () => {
- const registrations = mergeApplicationChannelRouteRegistrations({
- frameworkChannelNames: new Set(["callback", "eve", "shared"]),
- frameworkChannels: [
- { method: "POST", name: "eve", urlPath: "/framework/session" },
- { method: "POST", name: "callback", urlPath: "/callback" },
- { method: "GET", name: "shared", urlPath: "/duplicate" },
- ],
- manifestChannels: [
- { kind: "disabled", name: "callback" },
- { kind: "channel", method: "POST", name: "eve", urlPath: "/authored/session" },
- { kind: "channel", method: "GET", name: "custom", urlPath: "/duplicate" },
- ],
- });
+describe("createApplicationRouteRegistry", () => {
+ it("projects the compiler-owned channel route plan", async () => {
+ const { manifest } = await compileFromMemory({ model: "openai/gpt-5.4" });
+ const registry = createApplicationRouteRegistry({ compileResult: { manifest } });
- expect(registrations).toEqual([
- { cors: undefined, method: "GET", route: "/duplicate" },
- { cors: undefined, method: "POST", route: "/authored/session" },
- ]);
+ expect(registry.channelRegistrations).toEqual(
+ manifest.channelRoutes.effective.map((route) => ({
+ cors: route.cors,
+ method: route.method,
+ route: route.urlPath,
+ })),
+ );
+ expect(registry.channelRoutes).toContainEqual({
+ cors: undefined,
+ kind: "channel",
+ method: "GET",
+ path: EVE_HEALTH_ROUTE_PATH,
+ });
+ expect(registry.channelRoutes).toContainEqual({
+ cors: undefined,
+ kind: "channel",
+ method: "HEAD",
+ path: EVE_HEALTH_ROUTE_PATH,
+ });
+ expect(registry.channelRoutes).toContainEqual(
+ expect.objectContaining({ kind: "channel", method: "GET", path: EVE_INFO_ROUTE_PATH }),
+ );
+ expect(registry.routes.at(-1)).toEqual({
+ kind: "workflow",
+ method: "ALL",
+ path: EVE_WORKFLOW_FLOW_ROUTE_PATH,
+ });
});
- it("rejects disable files that do not name a framework channel", () => {
- expect(() =>
- mergeApplicationChannelRouteRegistrations({
- frameworkChannelNames: new Set(["eve"]),
- frameworkChannels: [],
- manifestChannels: [{ kind: "disabled", name: "unknown" }],
- }),
- ).toThrow(
- 'agent/channels/unknown.ts exports disableRoute() but "unknown" is not a framework channel',
+ it("adds only host-owned development routes in development", async () => {
+ const { manifest } = await compileFromMemory({ model: "openai/gpt-5.4" });
+ const registry = createApplicationRouteRegistry(
+ { compileResult: { manifest } },
+ { development: true },
);
- });
-});
-describe("createApplicationRouteRegistryFromInput", () => {
- it("centralizes package, channel, development, and workflow precedence", () => {
- const cors = { origin: ["https://example.com"] } as const;
- const registry = createApplicationRouteRegistryFromInput({
- development: true,
- frameworkChannelNames: new Set(),
- frameworkChannels: [],
- manifestChannels: [
- { cors, kind: "channel", method: "POST", name: "hooks", urlPath: "/hooks" },
- { cors, kind: "channel", method: "GET", name: "hooks", urlPath: "/hooks" },
- { cors, kind: "channel", method: "POST", name: "copy", urlPath: "/hooks" },
- {
- cors,
- kind: "channel",
- method: "WEBSOCKET",
- name: "socket",
- urlPath: "/socket/:room",
- },
- {
- kind: "channel",
- method: "GET",
- name: "reserved-health",
- urlPath: "/eve/v1/health",
- },
- {
- kind: "channel",
- method: "GET",
- name: "dev-shadow",
- urlPath: "/eve/v1/dev/runtime-artifacts",
- },
- ],
+ expect(registry.routes).toContainEqual({
+ kind: "development-artifacts",
+ method: "GET",
+ path: EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH,
});
-
- expect(registry.channelRegistrations).toEqual([
- { cors, method: "POST", route: "/hooks" },
- { cors, method: "GET", route: "/hooks" },
- { cors, method: "WEBSOCKET", route: "/socket/:room" },
- {
- cors: undefined,
- method: "GET",
- route: "/eve/v1/dev/runtime-artifacts",
- },
- ]);
- expect(registry.routes).toEqual([
- { kind: "home", method: "GET", path: "/" },
- { kind: "health", method: "GET", path: "/eve/v1/health" },
- { kind: "health", method: "HEAD", path: "/eve/v1/health" },
- { cors, kind: "channel", method: "POST", path: "/hooks" },
- { cors, kind: "channel-preflight", method: "OPTIONS", path: "/hooks" },
- { cors, kind: "channel", method: "GET", path: "/hooks" },
- {
- cors,
- kind: "channel",
- method: "WEBSOCKET",
- path: "/socket/:room",
- },
- {
- cors: undefined,
- kind: "channel",
- method: "GET",
- path: "/eve/v1/dev/runtime-artifacts",
- },
- {
- kind: "development-schedule",
- method: "POST",
- path: "/eve/v1/dev/schedules/:scheduleId",
- },
- {
- kind: "workflow",
- method: "ALL",
- path: "/.well-known/workflow/v1/flow",
- },
- ]);
- });
-
- it("omits development routes outside development", () => {
- const registry = createApplicationRouteRegistryFromInput({
- frameworkChannelNames: new Set(),
- frameworkChannels: [],
- manifestChannels: [],
+ expect(registry.routes).toContainEqual({
+ kind: "development-schedule",
+ method: "POST",
+ path: EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN,
});
-
- expect(registry.routes.map((route) => route.kind)).toEqual([
- "home",
- "health",
- "health",
- "workflow",
- ]);
+ expect(registry.routes.filter((route) => route.kind === "workflow")).toHaveLength(1);
});
});
diff --git a/packages/eve/src/internal/nitro/host/application-route-registry.ts b/packages/eve/src/internal/nitro/host/application-route-registry.ts
index 8e0a23089..bc219a5e0 100644
--- a/packages/eve/src/internal/nitro/host/application-route-registry.ts
+++ b/packages/eve/src/internal/nitro/host/application-route-registry.ts
@@ -4,16 +4,9 @@ import type { ChannelRouteMethod } from "#public/definitions/channel.js";
import {
EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN,
EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH,
- EVE_HEALTH_ROUTE_PATH,
} from "#protocol/routes.js";
-import {
- getAllFrameworkChannelNames,
- getFrameworkChannelDefinitions,
-} from "#runtime/framework-channels/index.js";
import { EVE_WORKFLOW_FLOW_ROUTE_PATH } from "#internal/workflow-bundle/eve-service-route-output.js";
-export type ApplicationRouteMethod = ChannelRouteMethod | "ALL" | "HEAD" | "OPTIONS";
-
export interface ApplicationChannelRouteRegistration {
readonly method: ChannelRouteMethod;
readonly route: string;
@@ -47,16 +40,6 @@ export type ApplicationRouteRegistration =
readonly method: "POST";
readonly path: string;
}
- | {
- readonly kind: "health";
- readonly method: "GET" | "HEAD";
- readonly path: string;
- }
- | {
- readonly kind: "home";
- readonly method: "GET";
- readonly path: string;
- }
| {
readonly kind: "workflow";
readonly method: "ALL";
@@ -64,210 +47,65 @@ export type ApplicationRouteRegistration =
};
export interface ApplicationRouteRegistry {
- /** Active channel bindings after framework override and route deduplication. */
readonly channelRegistrations: readonly ApplicationChannelRouteRegistration[];
- /** Channel and preflight routes accepted by the application-wide registry. */
readonly channelRoutes: readonly (ApplicationChannelPreflightRoute | ApplicationChannelRoute)[];
- /** Globally deduplicated method/path bindings in Nitro registration order. */
readonly routes: readonly ApplicationRouteRegistration[];
}
interface ApplicationRouteRegistryHost {
readonly compileResult: {
- readonly manifest: Pick<CompiledAgentManifest, "channels">;
+ readonly manifest: Pick<CompiledAgentManifest, "channelRoutes">;
};
}
-type ApplicationChannelManifestEntry =
- | {
- readonly kind: "channel";
- readonly name: string;
- readonly method: ChannelRouteMethod;
- readonly urlPath: string;
- readonly cors?: NormalizedChannelCorsOptions;
- }
- | {
- readonly kind: "disabled";
- readonly name: string;
- };
-
-interface ApplicationFrameworkChannelDefinition {
- readonly name: string;
- readonly method: ChannelRouteMethod;
- readonly urlPath: string;
- readonly cors?: NormalizedChannelCorsOptions;
-}
-
-interface MergeApplicationChannelRoutesInput {
- readonly frameworkChannelNames: ReadonlySet<string>;
- readonly frameworkChannels: readonly ApplicationFrameworkChannelDefinition[];
- readonly manifestChannels: readonly ApplicationChannelManifestEntry[];
-}
-
-interface CreateApplicationRouteRegistryInput extends MergeApplicationChannelRoutesInput {
- readonly development?: boolean;
-}
-
-const PACKAGE_ROUTES: readonly ApplicationRouteRegistration[] = [
- { kind: "home", method: "GET", path: "/" },
- { kind: "health", method: "GET", path: EVE_HEALTH_ROUTE_PATH },
- { kind: "health", method: "HEAD", path: EVE_HEALTH_ROUTE_PATH },
-];
-
-function createMethodPathKey(input: {
- readonly method: ApplicationRouteMethod;
- readonly path: string;
-}): string {
- return `${input.method} ${input.path}`;
-}
-
-/** Applies authored-name overrides before deduplicating framework-first route bindings. */
-export function mergeApplicationChannelRouteRegistrations(
- input: MergeApplicationChannelRoutesInput,
-): readonly ApplicationChannelRouteRegistration[] {
- const authoredNames = new Set<string>();
- const authoredRoutes: ApplicationChannelRouteRegistration[] = [];
- const disabledNames = new Set<string>();
-
- for (const entry of input.manifestChannels) {
- if (entry.kind === "disabled") {
- if (!input.frameworkChannelNames.has(entry.name)) {
- throw new Error(
- `agent/channels/${entry.name}.ts exports disableRoute() but "${entry.name}" is not a framework channel. ` +
- `Rename the file to one of: ${[...input.frameworkChannelNames].sort().join(", ")}.`,
- );
- }
- disabledNames.add(entry.name);
- continue;
- }
-
- authoredNames.add(entry.name);
- authoredRoutes.push({
- cors: entry.cors,
- method: entry.method,
- route: entry.urlPath,
- });
- }
-
- const activeFrameworkRoutes = input.frameworkChannels
- .filter((channel) => !authoredNames.has(channel.name) && !disabledNames.has(channel.name))
- .map((channel): ApplicationChannelRouteRegistration => ({
- cors: channel.cors,
- method: channel.method,
- route: channel.urlPath,
- }));
-
- const seen = new Set<string>();
- const merged: ApplicationChannelRouteRegistration[] = [];
- for (const registration of [...activeFrameworkRoutes, ...authoredRoutes]) {
- const key = createMethodPathKey({
- method: registration.method,
- path: registration.route,
- });
- if (!seen.has(key)) {
- seen.add(key);
- merged.push(registration);
- }
- }
-
- return merged;
-}
-
-/** Compiles route identity, precedence, and deduplication without importing Nitro. */
-export function createApplicationRouteRegistryFromInput(
- input: CreateApplicationRouteRegistryInput,
+/** Projects the compiler-owned route plan into Nitro registration records. */
+export function createApplicationRouteRegistry(
+ preparedHost: ApplicationRouteRegistryHost,
+ options: { readonly development?: boolean } = {},
): ApplicationRouteRegistry {
- const routes: ApplicationRouteRegistration[] = [];
- const channelRoutes: Array<ApplicationChannelPreflightRoute | ApplicationChannelRoute> = [];
- const channelRegistrations: ApplicationChannelRouteRegistration[] = [];
- const methodPaths = new Set<string>();
-
- const addRoute = (route: ApplicationRouteRegistration): boolean => {
- const key = createMethodPathKey(route);
- if (methodPaths.has(key)) {
- return false;
- }
- methodPaths.add(key);
- routes.push(route);
- return true;
- };
-
- for (const route of PACKAGE_ROUTES) {
- addRoute(route);
- }
-
- const preflightPaths = new Set<string>();
- for (const channel of mergeApplicationChannelRouteRegistrations(input)) {
- const channelRoute: ApplicationChannelRoute = {
- cors: channel.cors,
+ const plan = preparedHost.compileResult.manifest.channelRoutes;
+ const channelRegistrations = plan.effective.map((route) => ({
+ cors: route.cors,
+ method: route.method,
+ route: route.urlPath,
+ }));
+ const channelRoutes: Array<ApplicationChannelPreflightRoute | ApplicationChannelRoute> = [
+ ...plan.effective.map((route): ApplicationChannelRoute => ({
+ cors: route.cors,
kind: "channel",
- method: channel.method,
- path: channel.route,
- };
- if (!addRoute(channelRoute)) {
- continue;
- }
- channelRegistrations.push(channel);
- channelRoutes.push(channelRoute);
-
- if (
- channel.method !== "WEBSOCKET" &&
- channel.cors !== undefined &&
- !preflightPaths.has(channel.route)
- ) {
- preflightPaths.add(channel.route);
- const preflightRoute: ApplicationChannelPreflightRoute = {
- cors: channel.cors,
- kind: "channel-preflight",
- method: "OPTIONS",
- path: channel.route,
- };
- if (addRoute(preflightRoute)) {
- channelRoutes.push(preflightRoute);
- }
- }
- }
-
- if (input.development === true) {
- addRoute({
- kind: "development-artifacts",
- method: "GET",
- path: EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH,
- });
- addRoute({
- kind: "development-schedule",
- method: "POST",
- path: EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN,
- });
+ method: route.method,
+ path: route.urlPath,
+ })),
+ ...plan.preflight.map((route): ApplicationChannelPreflightRoute => ({
+ cors: route.cors,
+ kind: "channel-preflight",
+ method: "OPTIONS",
+ path: route.urlPath,
+ })),
+ ];
+ const routes: ApplicationRouteRegistration[] = [...channelRoutes];
+
+ if (options.development === true) {
+ routes.push(
+ {
+ kind: "development-artifacts",
+ method: "GET",
+ path: EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH,
+ },
+ {
+ kind: "development-schedule",
+ method: "POST",
+ path: EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN,
+ },
+ );
}
- addRoute({
- kind: "workflow",
- method: "ALL",
- path: EVE_WORKFLOW_FLOW_ROUTE_PATH,
- });
-
+ routes.push({ kind: "workflow", method: "ALL", path: EVE_WORKFLOW_FLOW_ROUTE_PATH });
return { channelRegistrations, channelRoutes, routes };
}
-export function createApplicationRouteRegistry(
- preparedHost: ApplicationRouteRegistryHost,
- options: { readonly development?: boolean } = {},
-): ApplicationRouteRegistry {
- return createApplicationRouteRegistryFromInput({
- development: options.development,
- frameworkChannelNames: getAllFrameworkChannelNames(),
- frameworkChannels: getFrameworkChannelDefinitions(),
- manifestChannels: preparedHost.compileResult.manifest.channels,
- });
-}
-
export function computeApplicationChannelRouteRegistrations(
preparedHost: ApplicationRouteRegistryHost,
): readonly ApplicationChannelRouteRegistration[] {
- return mergeApplicationChannelRouteRegistrations({
- frameworkChannelNames: getAllFrameworkChannelNames(),
- frameworkChannels: getFrameworkChannelDefinitions(),
- manifestChannels: preparedHost.compileResult.manifest.channels,
- });
+ return createApplicationRouteRegistry(preparedHost).channelRegistrations;
}
diff --git a/packages/eve/src/internal/nitro/host/build-application.scenario.test.ts b/packages/eve/src/internal/nitro/host/build-application.scenario.test.ts
index 4445f30ea..bf60c3c28 100644
--- a/packages/eve/src/internal/nitro/host/build-application.scenario.test.ts
+++ b/packages/eve/src/internal/nitro/host/build-application.scenario.test.ts
@@ -4,7 +4,7 @@ import { join } from "node:path";
import type { Nitro } from "nitro/types";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { createCompiledAgentManifest } from "#compiler/manifest.js";
+import { compileFromMemory } from "#compiler/compile-from-memory.js";
import {
APPLICATION_BUILD_PROFILE_SCHEMA_VERSION,
type ApplicationBuildProfile,
@@ -120,15 +120,13 @@ vi.mock("./vercel-build-prewarm.js", () => ({
const createScratchDirectory = useTemporaryDirectories();
const DEPLOYABLE_BUILD_OPTIONS = { skipVercelSandboxPrewarm: false } as const;
-function createPreparedHost(appRoot: string): PreparedApplicationHost {
+async function createPreparedHost(appRoot: string): Promise<PreparedApplicationHost> {
const agentRoot = join(appRoot, "agent");
- const manifest = createCompiledAgentManifest({
+ const { manifest } = await compileFromMemory({
agentRoot,
appRoot,
- config: {
- model: { id: "openai/gpt-5.4", routing: { kind: "gateway", target: "openai" } },
- name: "scenario-test-agent",
- },
+ model: "openai/gpt-5.4",
+ name: "scenario-test-agent",
});
return {
appRoot,
@@ -181,7 +179,7 @@ async function prepareHostBuildWorkspace(
workspace: ApplicationBuildWorkspace,
): Promise<PreparedApplicationHost> {
await mkdir(join(workspace.compiler.artifactsDir, "compile"), { recursive: true });
- return createPreparedHost(workspace.appRoot);
+ return await createPreparedHost(workspace.appRoot);
}
describe("buildApplication", () => {
diff --git a/packages/eve/src/internal/nitro/host/build-extension.ts b/packages/eve/src/internal/nitro/host/build-extension.ts
index 3147b3508..5e4f5fa2f 100644
--- a/packages/eve/src/internal/nitro/host/build-extension.ts
+++ b/packages/eve/src/internal/nitro/host/build-extension.ts
@@ -90,7 +90,9 @@ export async function buildExtensionPackage(
requires: await deriveExtensionCapabilityRequirements({
declarationModule,
manifest,
+ packageName: config.packageName,
runtimeDependencies: config.runtimeDependencies,
+ shortName: config.shortName,
sourceRoot: config.sourceRoot,
}),
});
diff --git a/packages/eve/src/internal/nitro/host/build-vercel-agent-summary.test.ts b/packages/eve/src/internal/nitro/host/build-vercel-agent-summary.test.ts
index 7196e9da1..62bdbfbb3 100644
--- a/packages/eve/src/internal/nitro/host/build-vercel-agent-summary.test.ts
+++ b/packages/eve/src/internal/nitro/host/build-vercel-agent-summary.test.ts
@@ -1,17 +1,9 @@
import { describe, expect, it } from "vitest";
-import {
- type CompiledChannelDefinition,
- type CompiledConnectionDefinition,
- type CompiledScheduleDefinition,
- type CompiledSkillDefinition,
- type CompiledSubagentEdge,
- type CompiledSubagentNode,
- type CompiledToolDefinition,
- createCompiledAgentManifest,
- createCompiledAgentNodeManifest,
- ROOT_COMPILED_AGENT_NODE_ID,
-} from "#compiler/manifest.js";
+import { compileFromMemory } from "#compiler/compile-from-memory.js";
+import { defineChannel, POST } from "#public/definitions/channel.js";
+import { defineInstructions } from "#public/definitions/instructions.js";
+import { defineSchedule } from "#public/definitions/schedule.js";
import { buildVercelAgentSummary } from "#internal/nitro/host/build-vercel-agent-summary.js";
import {
normalizeChannelKindForDisplay,
@@ -19,169 +11,37 @@ import {
VERCEL_EVE_AGENT_SUMMARY_VERSION,
} from "#internal/vercel-agent-summary.js";
-const APP_ROOT = "/app";
-const AGENT_ROOT = "/app/agent";
const GENERATOR_VERSION = "0.0.0-test";
-function makeTool(name: string): CompiledToolDefinition {
- return {
- description: `${name} description`,
- inputSchema: null,
- logicalPath: `tools/${name}.ts`,
- name,
- sourceId: `tools/${name}.ts`,
- sourceKind: "module",
- };
-}
-
-function makeConnection(
- name: string,
- options: {
- vercelConnect?: { connector: string };
- protocol?: CompiledConnectionDefinition["protocol"];
- url?: string;
- } = {},
-): CompiledConnectionDefinition {
- const protocol = options.protocol ?? "mcp";
- const base: CompiledConnectionDefinition = {
- connectionName: name,
- description: `${name} description`,
- logicalPath: `connections/${name}.ts`,
- protocol,
- sourceId: `connections/${name}.ts`,
- sourceKind: "module",
- url: options.url ?? `https://mcp.example.com/${name}`,
- };
- if (options.vercelConnect !== undefined) {
- return { ...base, vercelConnect: options.vercelConnect };
- }
- return base;
-}
-
-function makeSchedule(name: string, cron: string): CompiledScheduleDefinition {
- return {
- cron,
- hasRun: false,
- logicalPath: `schedules/${name}.md`,
- markdown: `# ${name}`,
- name,
- sourceId: `schedules/${name}.md`,
- sourceKind: "markdown",
- };
-}
-
-function makeChannel(input: { name: string; adapterKind?: string }): CompiledChannelDefinition {
- return {
- adapterKind: input.adapterKind,
- kind: "channel",
- logicalPath: `channels/${input.name}.ts`,
- method: "POST",
- name: input.name,
- sourceId: `channels/${input.name}.ts`,
- sourceKind: "module",
- urlPath: `/${input.name}`,
- };
-}
-
-function makeFlatSkill(name: string): CompiledSkillDefinition {
- return {
- description: `${name} description`,
- logicalPath: `skills/${name}.md`,
- markdown: `# ${name}`,
- name,
- sourceId: `skills/${name}.md`,
- sourceKind: "markdown",
- };
-}
-
-function makePackagedSkill(name: string): CompiledSkillDefinition {
- return {
- description: `${name} description`,
- logicalPath: `skills/${name}`,
- markdown: `# ${name}`,
- name,
- rootPath: `skills/${name}`,
- skillFilePath: `skills/${name}/SKILL.md`,
- skillId: name,
- sourceId: `skills/${name}/SKILL.md`,
- sourceKind: "skill-package",
- };
-}
-
-function makeSubagent(name: string): CompiledSubagentNode {
- return {
- agent: createCompiledAgentNodeManifest({
- agentRoot: `${AGENT_ROOT}/subagents/${name}`,
- appRoot: APP_ROOT,
- config: {
- model: { id: "openai/gpt-5.4", routing: { kind: "gateway", target: "openai" } },
- name,
- },
- }),
- description: `${name} subagent description`,
- entryPath: `subagents/${name}/agent.ts`,
- exportName: undefined,
- logicalPath: `subagents/${name}`,
- name,
- nodeId: name,
- rootPath: `subagents/${name}`,
- sourceId: `subagents/${name}/agent.ts`,
- sourceKind: "module",
- };
-}
-
describe("buildVercelAgentSummary", () => {
- it("produces the public summary shape from a compiled manifest", () => {
- const subagent = makeSubagent("research");
- const subagentEdge: CompiledSubagentEdge = {
- childNodeId: "research",
- parentNodeId: ROOT_COMPILED_AGENT_NODE_ID,
- };
- const manifest = createCompiledAgentManifest({
- agentRoot: AGENT_ROOT,
- appRoot: APP_ROOT,
- channels: [
- makeChannel({ name: "slack", adapterKind: "slack" }),
- makeChannel({ name: "weather-bot", adapterKind: "weather-slack" }),
- makeChannel({ name: "messages", adapterKind: "http" }),
- makeChannel({ name: "stripe", adapterKind: "stripe-webhook" }),
- makeChannel({ name: "mystery" }),
- { kind: "disabled", logicalPath: "channels/disabled.ts", name: "disabled" },
- ],
- config: {
- description: "An agent for tests.",
- model: { id: "openai/gpt-5.4", routing: { kind: "gateway", target: "openai" } },
- name: "test-agent",
- },
- connections: [
- makeConnection("linear", {
- vercelConnect: { connector: "oauth/mcp-linear-app" },
- }),
- makeConnection("github"),
- makeConnection("notion-api", {
- protocol: "openapi",
- url: "https://api.notion.com",
- }),
- ],
- diagnosticsSummary: { errors: 0, warnings: 2 },
- schedules: [
- makeSchedule("morning-digest", "0 9 * * *"),
- makeSchedule("weekly-report", "0 9 * * MON"),
- ],
- skills: [makeFlatSkill("get-weather"), makePackagedSkill("research")],
- subagentEdges: [subagentEdge],
- subagents: [subagent],
- instructions: [
+ it("projects the effective compiled graph into the public summary", async () => {
+ const { manifest } = await compileFromMemory({
+ model: "openai/gpt-5.4",
+ modules: [
{
- content: "You are a helpful test agent. Always cite tools you use.",
- logicalPath: "instructions.md",
- name: "instructions",
- role: "system",
- sourceId: "instructions.md",
- sourceKind: "markdown",
+ loadNamespace: async () => ({
+ default: defineInstructions({ content: "Resolved instructions.", role: "user" }),
+ }),
+ logicalPath: "instructions/summary.ts",
+ },
+ {
+ loadNamespace: async () => ({
+ default: defineChannel({
+ routes: [POST("/custom", async () => new Response("ok"))],
+ }),
+ }),
+ logicalPath: "channels/custom.ts",
+ },
+ {
+ loadNamespace: async () => ({
+ default: defineSchedule({ cron: "0 9 * * *", markdown: "Run the digest." }),
+ }),
+ logicalPath: "schedules/digest.ts",
},
],
- tools: [makeTool("get-weather"), makeTool("send-slack")],
+ name: "summary-agent",
+ skills: [{ description: "Research skill.", name: "research" }],
+ tools: [{ description: "Fetch weather.", name: "weather" }],
});
const summary = buildVercelAgentSummary({
@@ -189,224 +49,55 @@ describe("buildVercelAgentSummary", () => {
manifest,
});
- expect(summary.kind).toBe(VERCEL_EVE_AGENT_SUMMARY_KIND);
- expect(summary.schemaVersion).toBe(VERCEL_EVE_AGENT_SUMMARY_VERSION);
- expect(summary.generatorVersion).toBe(GENERATOR_VERSION);
-
- expect(summary.agent).toEqual({
- description: "An agent for tests.",
- modelId: "openai/gpt-5.4",
- name: "test-agent",
+ expect(summary).toMatchObject({
+ agent: { modelId: "openai/gpt-5.4", name: "summary-agent" },
+ generatorVersion: GENERATOR_VERSION,
+ kind: VERCEL_EVE_AGENT_SUMMARY_KIND,
+ schemaVersion: VERCEL_EVE_AGENT_SUMMARY_VERSION,
});
-
- expect(summary.instructions).toEqual([
- {
- content: "You are a helpful test agent. Always cite tools you use.",
- logicalPath: "instructions.md",
- role: "system",
- sourceKind: "markdown",
- },
- ]);
-
- expect(summary.tools).toEqual([
- {
- description: "get-weather description",
- logicalPath: "tools/get-weather.ts",
- name: "get-weather",
- },
- {
- description: "send-slack description",
- logicalPath: "tools/send-slack.ts",
- name: "send-slack",
- },
- ]);
-
- // Skills surface name + description + sourceKind so the dashboard can
- // tell flat markdown skills apart from packaged ones with sibling
- // assets/references/scripts. Full markdown body is intentionally not
- // included — overview shape only.
- expect(summary.skills).toEqual([
- {
- description: "get-weather description",
- logicalPath: "skills/get-weather.md",
- name: "get-weather",
- sourceKind: "markdown",
- },
- {
- description: "research description",
- logicalPath: "skills/research",
- name: "research",
- sourceKind: "skill-package",
- },
- ]);
-
- expect(summary.connections).toEqual([
- {
- description: "linear description",
- logicalPath: "connections/linear.ts",
- name: "linear",
- type: "mcp",
- url: "https://mcp.example.com/linear",
- // Connect-backed connections surface the connector identifier
- // so dashboards can deep-link to the matching settings page.
- vercelConnect: { connector: "oauth/mcp-linear-app" },
- },
- {
- // No `vercelConnect` field — github connection is just a raw
- // MCP server, not Connect-backed.
- description: "github description",
- logicalPath: "connections/github.ts",
- name: "github",
- type: "mcp",
- url: "https://mcp.example.com/github",
- },
- {
- // OpenAPI connections report their protocol as the type so the
- // dashboard can distinguish them from MCP servers.
- description: "notion-api description",
- logicalPath: "connections/notion-api.ts",
- name: "notion-api",
- type: "openapi",
- url: "https://api.notion.com",
- },
- ]);
-
- expect(summary.schedules).toEqual([
- {
- cron: "0 9 * * *",
- logicalPath: "schedules/morning-digest.md",
- name: "morning-digest",
- },
- {
- cron: "0 9 * * MON",
- logicalPath: "schedules/weekly-report.md",
- name: "weekly-report",
- },
- ]);
-
- // Disabled channels are dropped; remaining channels are normalized to
- // the four-value display type.
- expect(summary.channels).toEqual([
- {
- adapterKind: "slack",
- logicalPath: "channels/slack.ts",
- method: "POST",
- name: "slack",
- type: "slack",
- urlPath: "/slack",
- },
- {
- adapterKind: "weather-slack",
- logicalPath: "channels/weather-bot.ts",
- method: "POST",
- name: "weather-bot",
- type: "slack",
- urlPath: "/weather-bot",
- },
- {
- adapterKind: "http",
- logicalPath: "channels/messages.ts",
- method: "POST",
- name: "messages",
- type: "http",
- urlPath: "/messages",
- },
- {
- adapterKind: "stripe-webhook",
- logicalPath: "channels/stripe.ts",
- method: "POST",
- name: "stripe",
- type: "webhook",
- urlPath: "/stripe",
- },
- {
- logicalPath: "channels/mystery.ts",
- method: "POST",
- name: "mystery",
- type: "unknown",
- urlPath: "/mystery",
- },
- ]);
-
- expect(summary.sandbox).toBeNull();
-
- expect(summary.subagents).toEqual([
- {
- description: "research subagent description",
- logicalPath: "subagents/research",
- name: "research",
- },
- ]);
-
- expect(summary.diagnostics).toEqual({ errors: 0, warnings: 2 });
- });
-
- it("surfaces the package version when no generatorVersion is given", () => {
- const manifest = createCompiledAgentManifest({
- agentRoot: AGENT_ROOT,
- appRoot: APP_ROOT,
- config: {
- model: { id: "openai/gpt-5.4", routing: { kind: "gateway", target: "openai" } },
- name: "minimal-agent",
- },
+ expect(summary.instructions).toContainEqual({
+ content: "Resolved instructions.",
+ logicalPath: "instructions/summary.ts",
+ role: "user",
+ sourceKind: "module",
});
-
- const summary = buildVercelAgentSummary({ manifest });
-
- expect(typeof summary.generatorVersion).toBe("string");
- expect(summary.generatorVersion.length).toBeGreaterThan(0);
- expect(summary.instructions).toEqual([]);
- });
-
- it("captures module-backed instructions with their resolved content and role", () => {
- const manifest = createCompiledAgentManifest({
- agentRoot: AGENT_ROOT,
- appRoot: APP_ROOT,
- config: {
- model: { id: "openai/gpt-5.4", routing: { kind: "gateway", target: "openai" } },
- name: "module-instructions-agent",
- },
- instructions: [
- {
- content: "Module-backed instructions rendered at build time.",
- logicalPath: "instructions.ts",
- name: "instructions",
- role: "user",
- sourceId: "instructions.ts",
- sourceKind: "module",
- },
- ],
+ expect(summary.tools).toContainEqual({
+ description: "Fetch weather.",
+ logicalPath: "tools/weather.ts",
+ name: "weather",
});
+ expect(summary.skills).toContainEqual({
+ description: "Research skill.",
+ logicalPath: "skills/research.ts",
+ name: "research",
+ sourceKind: "module",
+ });
+ expect(summary.schedules).toContainEqual({
+ cron: "0 9 * * *",
+ logicalPath: "schedules/digest.ts",
+ name: "digest",
+ });
+ expect(summary.channels).toContainEqual(
+ expect.objectContaining({ method: "POST", name: "custom", urlPath: "/custom" }),
+ );
+ expect(summary.sandbox).toEqual({ logicalPath: "sandbox.ts" });
+ });
+ it("surfaces the installed package version by default", async () => {
+ const { manifest } = await compileFromMemory({ model: "openai/gpt-5.4" });
const summary = buildVercelAgentSummary({ manifest });
- expect(summary.instructions).toEqual([
- {
- content: "Module-backed instructions rendered at build time.",
- logicalPath: "instructions.ts",
- role: "user",
- sourceKind: "module",
- },
- ]);
+ expect(summary.generatorVersion.length).toBeGreaterThan(0);
});
});
describe("normalizeChannelKindForDisplay", () => {
it("normalizes well-known kinds to the closed display set", () => {
expect(normalizeChannelKindForDisplay("slack")).toBe("slack");
- expect(normalizeChannelKindForDisplay("Slack")).toBe("slack");
expect(normalizeChannelKindForDisplay("weather-slack")).toBe("slack");
- expect(normalizeChannelKindForDisplay("http")).toBe("http");
expect(normalizeChannelKindForDisplay("HTTP")).toBe("http");
expect(normalizeChannelKindForDisplay("stripe-webhook")).toBe("webhook");
- expect(normalizeChannelKindForDisplay("WEBHOOK")).toBe("webhook");
expect(normalizeChannelKindForDisplay("custom-kind")).toBe("unknown");
- expect(normalizeChannelKindForDisplay("")).toBe("unknown");
expect(normalizeChannelKindForDisplay(undefined)).toBe("unknown");
});
});
-
-// `emitVercelAgentSummary` is exercised end-to-end by
-// `build-application.scenario.test.ts`, which asserts the summary JSON file
-// is written under the Vercel Build Output directory. Tier 0 unit tests are
-// hermetic and may not perform filesystem I/O.
diff --git a/packages/eve/src/internal/nitro/host/build-vercel-agent-summary.ts b/packages/eve/src/internal/nitro/host/build-vercel-agent-summary.ts
index 04ca0ece2..fb3dafa69 100644
--- a/packages/eve/src/internal/nitro/host/build-vercel-agent-summary.ts
+++ b/packages/eve/src/internal/nitro/host/build-vercel-agent-summary.ts
@@ -4,7 +4,6 @@ import { dirname } from "node:path";
import type {
CompiledAgentManifest,
CompiledChannelDefinition,
- CompiledChannelEntry,
CompiledConnectionDefinition,
CompiledInstructionsDefinition,
CompiledScheduleDefinition,
@@ -60,7 +59,7 @@ export function buildVercelAgentSummary(input: {
tools: manifest.tools.map(toToolEntry),
skills: manifest.skills.map(toSkillEntry),
connections: manifest.connections.map(toConnectionEntry),
- channels: manifest.channels.filter(isActiveChannel).map(toChannelEntry),
+ channels: manifest.channelRoutes.effective.map(toChannelEntry),
sandbox:
manifest.sandbox === null
? null
@@ -107,10 +106,6 @@ export async function emitVercelAgentSummary(input: {
return input.outputPath;
}
-function isActiveChannel(entry: CompiledChannelEntry): entry is CompiledChannelDefinition {
- return entry.kind === "channel";
-}
-
function toInstructionsEntry(
instructions: CompiledInstructionsDefinition,
): VercelEveInstructionsEntry {
diff --git a/packages/eve/src/internal/nitro/host/configure-nitro-routes.test.ts b/packages/eve/src/internal/nitro/host/configure-nitro-routes.test.ts
index 49b28b4f4..949962425 100644
--- a/packages/eve/src/internal/nitro/host/configure-nitro-routes.test.ts
+++ b/packages/eve/src/internal/nitro/host/configure-nitro-routes.test.ts
@@ -24,7 +24,18 @@ interface PreparedApplicationHostStub {
appRoot: string;
compileResult: {
manifest: {
- channels: [];
+ channelRoutes: {
+ effective: Array<{
+ logicalPath: string;
+ method: "GET" | "HEAD";
+ name: string;
+ sourceId: string;
+ sourceKind: "module";
+ urlPath: string;
+ }>;
+ preflight: [];
+ shadowed: [];
+ };
config: {
name: string;
experimental?: { workflow?: { world?: string } };
@@ -131,7 +142,36 @@ function createPreparedHost(
appRoot,
compileResult: {
manifest: {
- channels: [],
+ channelRoutes: {
+ effective: [
+ ...["GET", "HEAD"].map((method) => ({
+ logicalPath: "channels/home.ts",
+ method: method as "GET" | "HEAD",
+ name: "home",
+ sourceId: "framework:home",
+ sourceKind: "module" as const,
+ urlPath: "/",
+ })),
+ ...["GET", "HEAD"].map((method) => ({
+ logicalPath: "channels/eve.ts",
+ method: method as "GET" | "HEAD",
+ name: "eve",
+ sourceId: "framework:eve",
+ sourceKind: "module" as const,
+ urlPath: EVE_HEALTH_ROUTE_PATH,
+ })),
+ {
+ logicalPath: "channels/eve.ts",
+ method: "GET",
+ name: "eve",
+ sourceId: "framework:eve",
+ sourceKind: "module",
+ urlPath: EVE_INFO_ROUTE_PATH,
+ },
+ ],
+ preflight: [],
+ shadowed: [],
+ },
config:
input.workflowWorld === undefined
? { name: input.agentName ?? "test-agent" }
@@ -168,7 +208,7 @@ describe("Nitro route configuration", () => {
vi.unstubAllEnvs();
});
- it("registers package-owned route files through file-url virtual handlers", async () => {
+ it("registers compiler-owned routes through channel virtual handlers", async () => {
const nitro = createNitroStub();
await configureProductionNitroRoutes(nitro, createPreparedHost());
@@ -176,16 +216,14 @@ describe("Nitro route configuration", () => {
const healthHandler = nitro.options.handlers.find(
(handler) => handler.route === EVE_HEALTH_ROUTE_PATH && handler.method === "GET",
);
- expect(healthHandler?.handler).toBe(`#eve-route-handler/GET ${EVE_HEALTH_ROUTE_PATH}`);
+ expect(healthHandler?.handler).toBe(`#nitro/virtual/eve-channel/GET ${EVE_HEALTH_ROUTE_PATH}`);
const virtualSource = nitro.options.virtual[healthHandler?.handler ?? ""];
- expect(virtualSource).toContain(
- 'import handler from "file:///G:/projects/test-eve/node_modules/.pnpm/[email protected]/node_modules/eve/dist/src/internal/nitro/routes/health.js";',
- );
+ expect(virtualSource).toContain("dispatchChannelRequest");
expect(virtualSource).not.toContain('"G:\\');
});
- it("bakes the agent name into the home page route", async () => {
+ it("routes the compiled home channel through the same dispatcher", async () => {
const nitro = createNitroStub();
await configureProductionNitroRoutes(nitro, createPreparedHost({ agentName: "support-agent" }));
@@ -193,11 +231,11 @@ describe("Nitro route configuration", () => {
const homeHandler = nitro.options.handlers.find(
(handler) => handler.route === "/" && handler.method === "GET",
);
- expect(homeHandler?.handler).toBe("#eve-route/");
+ expect(homeHandler?.handler).toBe("#nitro/virtual/eve-channel/GET /");
const virtualSource = nitro.options.virtual[homeHandler?.handler ?? ""];
- expect(virtualSource).toContain("handleHomePageRequest");
- expect(virtualSource).toContain('{"agentName":"support-agent"}');
+ expect(virtualSource).toContain("dispatchChannelRequest");
+ expect(virtualSource).not.toContain("support-agent");
});
it("registers the health route for HEAD so load balancers probing with HEAD see 200", async () => {
@@ -214,12 +252,10 @@ describe("Nitro route configuration", () => {
const headHandler = nitro.options.handlers.find(
(handler) => handler.route === EVE_HEALTH_ROUTE_PATH && handler.method === "HEAD",
);
- expect(headHandler?.handler).toBe(`#eve-route-handler/HEAD ${EVE_HEALTH_ROUTE_PATH}`);
+ expect(headHandler?.handler).toBe(`#nitro/virtual/eve-channel/HEAD ${EVE_HEALTH_ROUTE_PATH}`);
const virtualSource = nitro.options.virtual[headHandler?.handler ?? ""];
- expect(virtualSource).toContain(
- 'import handler from "file:///G:/projects/test-eve/node_modules/.pnpm/[email protected]/node_modules/eve/dist/src/internal/nitro/routes/health.js";',
- );
+ expect(virtualSource).toContain("dispatchChannelRequest");
});
it("registers workflow routes through physical handlers with relative bundle imports", async () => {
diff --git a/packages/eve/src/internal/nitro/host/configure-nitro-routes.ts b/packages/eve/src/internal/nitro/host/configure-nitro-routes.ts
index 9af4bec33..b2904980f 100644
--- a/packages/eve/src/internal/nitro/host/configure-nitro-routes.ts
+++ b/packages/eve/src/internal/nitro/host/configure-nitro-routes.ts
@@ -30,28 +30,6 @@ import {
import { registerChannelVirtualHandlers } from "#internal/nitro/host/channel-routes.js";
import type { PreparedApplicationHost } from "#internal/nitro/host/types.js";
-function registerHandler(
- nitro: Nitro,
- options: {
- handlerPath: string;
- method?: "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE";
- route: string;
- },
-): void {
- const virtualId = `#eve-route-handler/${options.method ?? "ALL"} ${options.route}`;
- const handlerPath = stringifyEsmImportSpecifier(options.handlerPath);
-
- nitro.options.handlers.push({
- handler: virtualId,
- method: options.method,
- route: options.route,
- });
- nitro.options.virtual[virtualId] = [
- `import handler from ${handlerPath};`,
- "export default handler;",
- ].join("\n");
-}
-
function resolveNitroWorkflowBuildDirectory(nitro: Nitro): string {
return join(nitro.options.buildDir, "workflow");
}
@@ -229,7 +207,7 @@ function buildWorkflowFileHandlerSource(input: {
* handler can run request-time auth, header inspection, etc. on top of
* its baked-in config.
*/
-function addFrameworkVirtualHandler(
+function addHostVirtualHandler(
nitro: Nitro,
input: {
args: string;
@@ -272,32 +250,11 @@ async function registerWorkflowArtifactBuildHook(
function registerApplicationRoutes(
nitro: Nitro,
- preparedHost: PreparedApplicationHost,
artifactsConfig: NitroArtifactsConfig,
registry: ApplicationRouteRegistry,
): void {
for (const route of registry.routes) {
switch (route.kind) {
- case "home": {
- addFrameworkVirtualHandler(nitro, {
- args: JSON.stringify({
- agentName: preparedHost.compileResult.manifest.config.name,
- }),
- handlerExport: "handleHomePageRequest",
- method: route.method,
- modulePath: resolvePackageSourceFilePath("src/internal/nitro/routes/index.ts"),
- route: route.path,
- });
- break;
- }
- case "health": {
- registerHandler(nitro, {
- handlerPath: resolvePackageSourceFilePath("src/internal/nitro/routes/health.ts"),
- method: route.method,
- route: route.path,
- });
- break;
- }
case "channel":
case "channel-preflight": {
registerChannelVirtualHandlers(nitro, {
@@ -308,7 +265,7 @@ function registerApplicationRoutes(
}
case "development-artifacts": {
const developmentConfig = artifactsConfig as DevelopmentNitroArtifactsConfig;
- addFrameworkVirtualHandler(nitro, {
+ addHostVirtualHandler(nitro, {
args: JSON.stringify({ appRoot: developmentConfig.appRoot }),
handlerExport: "handleDevRuntimeArtifactsRequest",
method: route.method,
@@ -324,7 +281,7 @@ function registerApplicationRoutes(
// and baked into the handler: resolving the module-map loader path from
// inside the bundled dev server can land on the authored app instead of
// the installed eve package (vercel/eve#311).
- addFrameworkVirtualHandler(nitro, {
+ addHostVirtualHandler(nitro, {
args: JSON.stringify(artifactsConfig),
handlerExport: "handleDevScheduleDispatchRequest",
method: route.method,
@@ -408,7 +365,7 @@ export async function configureDevelopmentNitroRoutes(
configuredWorld: preparedHost.compileResult.manifest.config.experimental?.workflow?.world,
});
const routeRegistry = createApplicationRouteRegistry(preparedHost, { development: true });
- registerApplicationRoutes(nitro, preparedHost, artifactsConfig, routeRegistry);
+ registerApplicationRoutes(nitro, artifactsConfig, routeRegistry);
const workflowBundlePath = join(workflowBuildDirectory, "workflows.mjs");
const directHandlers: WorkflowDirectHandlerEntry[] = [];
@@ -456,12 +413,7 @@ export async function configureProductionNitroRoutes(
await registerWorkflowArtifactBuildHook(nitro, syncWorkflowArtifacts);
const routeRegistry = createApplicationRouteRegistry(preparedHost);
- registerApplicationRoutes(
- nitro,
- preparedHost,
- createProductionNitroArtifactsConfig(),
- routeRegistry,
- );
+ registerApplicationRoutes(nitro, createProductionNitroArtifactsConfig(), routeRegistry);
const workflowBundlePath = join(preparedHost.workflowBuildDir, "workflows.mjs");
const hasConfiguredWorkflowWorld =
diff --git a/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts b/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts
index 16b417508..f07c65626 100644
--- a/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts
+++ b/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts
@@ -5,17 +5,14 @@ import { join } from "node:path";
import type { Nitro } from "nitro/types";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { compileFromMemory } from "#compiler/compile-from-memory.js";
import {
COMPILE_METADATA_KIND,
COMPILE_METADATA_VERSION,
type CompileMetadata,
resolveCompilerArtifactPaths,
} from "#compiler/artifacts.js";
-import {
- createCompiledAgentNodeManifest,
- type CompiledChannelEntry,
- type CompiledSubagentNode,
-} from "#compiler/manifest.js";
+import type { CompiledSubagentNode } from "#compiler/manifest.js";
import {
resolvePackageSourceDirectoryPath,
resolvePackageRoot,
@@ -32,6 +29,7 @@ import {
EVE_WORKFLOW_FLOW_ROUTE_PATH,
} from "#internal/nitro/host/vercel-build-output-config.js";
import { applyWorkflowTransform } from "#internal/workflow-bundle/workflow-builders.js";
+import { defineChannel, WS } from "#public/definitions/channel.js";
const configureDevelopmentNitroRoutes = vi.fn(async () => undefined);
const configureProductionNitroRoutes = vi.fn(async () => undefined);
@@ -91,11 +89,36 @@ function createNitroStub(input: { buildDir?: string; dev?: boolean } = {}): Nitr
};
}
-function createPreparedHost(): PreparedDevelopmentApplicationHost {
+async function createPreparedHost(
+ input: { readonly websocket?: boolean } = {},
+): Promise<PreparedDevelopmentApplicationHost> {
const appRoot = "/tmp/weather-agent";
const paths = resolveCompilerArtifactPaths(appRoot);
+ const { manifest } = await compileFromMemory({
+ agentRoot: `${appRoot}/agent`,
+ appRoot,
+ model: "openai/gpt-5.4",
+ modules:
+ input.websocket === true
+ ? [
+ {
+ logicalPath: "channels/voice.ts",
+ loadNamespace: async () => ({
+ default: defineChannel({
+ routes: [WS("/eve/v1/voice/ws", async () => ({ open() {} }))],
+ }),
+ }),
+ },
+ ]
+ : [],
+ name: "weather-agent",
+ });
const metadata: CompileMetadata = {
compile: {
+ manifest: {
+ path: paths.compiledManifestPath,
+ sha256: "compiled-manifest-sha",
+ },
moduleMap: {
path: paths.moduleMapPath,
sha256: "module-map-sha",
@@ -129,13 +152,7 @@ function createPreparedHost(): PreparedDevelopmentApplicationHost {
appRoot,
compileResult: {
diagnostics: [],
- manifest: {
- channels: [],
- config: { name: "weather-agent" },
- extensionMounts: [],
- sandbox: null,
- subagents: [],
- },
+ manifest,
metadata,
paths,
project: {
@@ -193,7 +210,7 @@ describe("application Nitro creation", () => {
const { createDevelopmentApplicationNitro } =
await import("#internal/nitro/host/create-application-nitro.js");
- const preparedHost = createPreparedHost();
+ const preparedHost = await createPreparedHost();
await createDevelopmentApplicationNitro(preparedHost);
const plugins = createNitroMock.mock.calls[0]?.[0].plugins as string[];
@@ -215,7 +232,7 @@ describe("application Nitro creation", () => {
createNitroMock.mockResolvedValueOnce(nitroStub.nitro);
const { createDevelopmentApplicationNitro } =
await import("#internal/nitro/host/create-application-nitro.js");
- const preparedHost = createPreparedHost();
+ const preparedHost = await createPreparedHost();
preparedHost.compiledArtifacts.instrumentationLayout = { kind: "file" };
preparedHost.compiledArtifacts.instrumentationPluginPath = "/app/instrumentation.mjs";
@@ -235,7 +252,7 @@ describe("application Nitro creation", () => {
for (const slots of ["rows", "local"] as const) {
const nitroStub = createNitroStub();
createNitroMock.mockResolvedValueOnce(nitroStub.nitro);
- const preparedHost = createPreparedHost();
+ const preparedHost = await createPreparedHost();
preparedHost.compiledArtifacts.instrumentationLayout = {
kind: "directory",
slots: [slots],
@@ -257,7 +274,7 @@ describe("application Nitro creation", () => {
const { createProductionApplicationNitro } =
await import("#internal/nitro/host/create-application-nitro.js");
- const preparedHost = createPreparedHost();
+ const preparedHost = await createPreparedHost();
await createProductionApplicationNitro(preparedHost, createProductionOptions(preparedHost));
const rollupBeforeHooks = nitroStub.hookHandlers.get("rollup:before") ?? [];
@@ -327,7 +344,7 @@ describe("application Nitro creation", () => {
const { createDevelopmentApplicationNitro } =
await import("#internal/nitro/host/create-application-nitro.js");
- const preparedHost = createPreparedHost();
+ const preparedHost = await createPreparedHost();
await createDevelopmentApplicationNitro(preparedHost);
const rollupBeforeHooks = nitroStub.hookHandlers.get("rollup:before") ?? [];
@@ -358,7 +375,7 @@ describe("application Nitro creation", () => {
const { createDevelopmentApplicationNitro } =
await import("#internal/nitro/host/create-application-nitro.js");
- const preparedHost = createPreparedHost();
+ const preparedHost = await createPreparedHost();
await createDevelopmentApplicationNitro(preparedHost);
expect(createNitroMock).toHaveBeenCalledTimes(1);
@@ -374,7 +391,7 @@ describe("application Nitro creation", () => {
const { createDevelopmentApplicationNitro } =
await import("#internal/nitro/host/create-application-nitro.js");
- const preparedHost = createPreparedHost();
+ const preparedHost = await createPreparedHost();
await createDevelopmentApplicationNitro(preparedHost);
expect(createNitroMock).toHaveBeenCalledTimes(1);
@@ -392,7 +409,7 @@ describe("application Nitro creation", () => {
const { createProductionApplicationNitro } =
await import("#internal/nitro/host/create-application-nitro.js");
- const preparedHost = createPreparedHost();
+ const preparedHost = await createPreparedHost();
await createProductionApplicationNitro(preparedHost, createProductionOptions(preparedHost));
expect(createNitroMock).toHaveBeenCalledWith(
@@ -423,17 +440,7 @@ describe("application Nitro creation", () => {
const { createProductionApplicationNitro } =
await import("#internal/nitro/host/create-application-nitro.js");
- const preparedHost = createPreparedHost();
- const websocketChannel: CompiledChannelEntry = {
- kind: "channel",
- logicalPath: "channels/voice.ts",
- method: "WEBSOCKET",
- name: "voice",
- sourceId: "channels/voice.ts",
- sourceKind: "module",
- urlPath: "/eve/v1/voice/ws",
- };
- preparedHost.compileResult.manifest.channels = [websocketChannel];
+ const preparedHost = await createPreparedHost({ websocket: true });
await createProductionApplicationNitro(preparedHost, createProductionOptions(preparedHost));
@@ -456,7 +463,7 @@ describe("application Nitro creation", () => {
const nitroStub = createNitroStub();
createNitroMock.mockResolvedValueOnce(nitroStub.nitro);
- const preparedHost = createPreparedHost();
+ const preparedHost = await createPreparedHost();
preparedHost.appRoot = tempRoot;
preparedHost.compileResult.project.appRoot = tempRoot;
preparedHost.compileResult.project.agentRoot = join(tempRoot, "agent");
@@ -496,7 +503,7 @@ describe("application Nitro creation", () => {
createNitroMock.mockResolvedValueOnce(nitroStub.nitro);
const { createProductionApplicationNitro } = await import("./create-application-nitro.js");
- const preparedHost = createPreparedHost();
+ const preparedHost = await createPreparedHost();
await createProductionApplicationNitro(preparedHost, createProductionOptions(preparedHost));
const rollupBeforeHooks = nitroStub.hookHandlers.get("rollup:before") ?? [];
@@ -550,7 +557,7 @@ describe("application Nitro creation", () => {
const { createProductionApplicationNitro } =
await import("#internal/nitro/host/create-application-nitro.js");
- const preparedHost = createPreparedHost();
+ const preparedHost = await createPreparedHost();
preparedHost.compileResult.manifest.config = {
...preparedHost.compileResult.manifest.config,
build: {
@@ -576,7 +583,7 @@ describe("application Nitro creation", () => {
const { createProductionApplicationNitro } =
await import("#internal/nitro/host/create-application-nitro.js");
- const preparedHost = createPreparedHost();
+ const preparedHost = await createPreparedHost();
preparedHost.compileResult.manifest.extensionMounts = [
{
externalDependencies: ["zod", "sharp"],
@@ -617,27 +624,38 @@ describe("application Nitro creation", () => {
const { createProductionApplicationNitro } =
await import("#internal/nitro/host/create-application-nitro.js");
- const preparedHost = createPreparedHost();
- const subagent: CompiledSubagentNode = {
- agent: createCompiledAgentNodeManifest({
- agentRoot: "/tmp/weather-agent/agent/subagents/investigator",
- appRoot: "/tmp/weather-agent",
- config: {
- build: {
- externalDependencies: ["subagent-external", "sharp"],
- },
- model: {
- id: "anthropic/claude-sonnet-5",
- routing: { kind: "gateway", target: "anthropic" },
- },
- name: "investigator",
+ const preparedHost = await createPreparedHost();
+ const { manifest: compiledSubagent } = await compileFromMemory({
+ agentRoot: "/tmp/weather-agent/agent/subagents/investigator",
+ appRoot: "/tmp/weather-agent",
+ agent: {
+ build: {
+ externalDependencies: ["subagent-external", "sharp"],
},
- }),
+ model: "anthropic/claude-sonnet-5",
+ },
+ model: "anthropic/claude-sonnet-5",
+ name: "investigator",
+ });
+ const {
+ kind: _kind,
+ subagents: _subagents,
+ version: _version,
+ ...subagentAgent
+ } = compiledSubagent;
+ const subagent: CompiledSubagentNode = {
+ agent: subagentAgent,
+ backing: {
+ kind: "resource",
+ sourcePath: "/tmp/weather-agent/agent/subagents/investigator",
+ },
description: "Investigates deployments.",
entryPath: "subagents/investigator",
logicalPath: "subagents/investigator/agent.ts",
name: "investigator",
nodeId: "root:subagents/investigator",
+ owner: { kind: "application" },
+ parentNodeId: "__root__",
rootPath: "/tmp/weather-agent/agent/subagents/investigator",
sourceId: "subagents/investigator/agent.ts",
sourceKind: "module",
@@ -659,7 +677,7 @@ describe("application Nitro creation", () => {
const { createProductionApplicationNitro } =
await import("#internal/nitro/host/create-application-nitro.js");
- const preparedHost = createPreparedHost();
+ const preparedHost = await createPreparedHost();
await createProductionApplicationNitro(preparedHost, createProductionOptions(preparedHost));
@@ -675,9 +693,13 @@ describe("application Nitro creation", () => {
const { createProductionApplicationNitro } =
await import("#internal/nitro/host/create-application-nitro.js");
- const directHost = createPreparedHost();
- const workflowHost = createPreparedHost();
- workflowHost.compileResult.manifest.workflowTool = {};
+ const directHost = await createPreparedHost();
+ const workflowHost = await createPreparedHost();
+ workflowHost.compileResult.manifest.workflowTool = {
+ logicalPath: "tools/workflow.ts",
+ sourceId: "test:workflow",
+ sourceKind: "module",
+ };
await createProductionApplicationNitro(directHost, createProductionOptions(directHost));
await createProductionApplicationNitro(workflowHost, createProductionOptions(workflowHost));
@@ -702,9 +724,9 @@ describe("application Nitro creation", () => {
const { createDevelopmentApplicationNitro, createProductionApplicationNitro } =
await import("#internal/nitro/host/create-application-nitro.js");
- const productionHost = createPreparedHost();
+ const productionHost = await createPreparedHost();
await createProductionApplicationNitro(productionHost, createProductionOptions(productionHost));
- await createDevelopmentApplicationNitro(createPreparedHost());
+ await createDevelopmentApplicationNitro(await createPreparedHost());
const productionPlugins = createNitroMock.mock.calls[0]?.[0].plugins as string[];
const devPlugins = createNitroMock.mock.calls[1]?.[0].plugins as string[];
@@ -723,7 +745,7 @@ describe("application Nitro creation", () => {
const { createProductionApplicationNitro } =
await import("#internal/nitro/host/create-application-nitro.js");
- const preparedHost = createPreparedHost();
+ const preparedHost = await createPreparedHost();
preparedHost.compileResult.manifest.config = {
...preparedHost.compileResult.manifest.config,
build: {
@@ -783,7 +805,7 @@ describe("application Nitro creation", () => {
try {
const { createProductionApplicationNitro } =
await import("#internal/nitro/host/create-application-nitro.js");
- const preparedHost = createPreparedHost();
+ const preparedHost = await createPreparedHost();
preparedHost.workflowBuildDir = workflowBuildDir;
await createProductionApplicationNitro(preparedHost, {
...createProductionOptions(preparedHost),
diff --git a/packages/eve/src/internal/nitro/host/create-application-nitro.ts b/packages/eve/src/internal/nitro/host/create-application-nitro.ts
index ba3ad09b1..2ca36ff79 100644
--- a/packages/eve/src/internal/nitro/host/create-application-nitro.ts
+++ b/packages/eve/src/internal/nitro/host/create-application-nitro.ts
@@ -95,9 +95,7 @@ function manifestEnablesWorkflow(manifest: CompiledAgentManifest): boolean {
}
function manifestHasWebSocketChannel(manifest: CompiledAgentManifest): boolean {
- return manifest.channels.some(
- (entry) => entry.kind === "channel" && entry.method === "WEBSOCKET",
- );
+ return manifest.channelRoutes.effective.some((entry) => entry.method === "WEBSOCKET");
}
function collectHostedTraceDependencies(
diff --git a/packages/eve/src/internal/nitro/host/dev-authored-source-watcher.scenario.test.ts b/packages/eve/src/internal/nitro/host/dev-authored-source-watcher.scenario.test.ts
index 68f9f4bc0..780a40371 100644
--- a/packages/eve/src/internal/nitro/host/dev-authored-source-watcher.scenario.test.ts
+++ b/packages/eve/src/internal/nitro/host/dev-authored-source-watcher.scenario.test.ts
@@ -3,7 +3,7 @@ import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { createCompiledAgentManifest } from "#compiler/manifest.js";
+import { compileFromMemory } from "#compiler/compile-from-memory.js";
import type { DevelopmentAuthoredRebuildCoordinator } from "#internal/nitro/host/dev-authored-rebuild-coordinator.js";
import type { PreparedDevelopmentApplicationHost } from "#internal/nitro/host/types.js";
import { STRUCTURAL_RELOAD_LOG_LINE } from "#internal/nitro/host/dev-watcher-log.js";
@@ -89,7 +89,7 @@ afterEach(async () => {
describe("startAuthoredSourceWatcher", () => {
it("forces a transactional rebuild for local setup actions", async () => {
- const host = createPreparedHost();
+ const host = await createPreparedHost();
const coordinator = createCoordinator(host);
const watcher = await startAuthoredSourceWatcher({ coordinator, preparedHost: host });
@@ -102,7 +102,7 @@ describe("startAuthoredSourceWatcher", () => {
});
it("rebuilds once after resuming a suspended watcher", async () => {
- const host = createPreparedHost();
+ const host = await createPreparedHost();
const coordinator = createCoordinator(host);
const watcher = await startAuthoredSourceWatcher({ coordinator, preparedHost: host });
@@ -123,7 +123,7 @@ describe("startAuthoredSourceWatcher", () => {
});
it("ignores generated directories while watching authored roots", async () => {
- const host = createPreparedHost();
+ const host = await createPreparedHost();
const watcher = await startAuthoredSourceWatcher({
coordinator: createCoordinator(host),
preparedHost: host,
@@ -142,7 +142,7 @@ describe("startAuthoredSourceWatcher", () => {
it("drops initial and directory-only events", async () => {
mockedWatcher.deferReadiness();
- const host = createPreparedHost();
+ const host = await createPreparedHost();
const coordinator = createCoordinator(host);
const watcherPromise = startAuthoredSourceWatcher({ coordinator, preparedHost: host });
@@ -163,7 +163,7 @@ describe("startAuthoredSourceWatcher", () => {
});
it("coalesces edits received during an in-flight rebuild", async () => {
- const host = createPreparedHost();
+ const host = await createPreparedHost();
const first = createDeferred<{ host: PreparedDevelopmentApplicationHost; kind: "runtime" }>();
const coordinator = createCoordinator(host);
vi.mocked(coordinator.rebuild)
@@ -188,7 +188,7 @@ describe("startAuthoredSourceWatcher", () => {
});
it("reports a structural commit only after the coordinator completes", async () => {
- const host = createPreparedHost();
+ const host = await createPreparedHost();
const coordinator = createCoordinator(host);
vi.mocked(coordinator.rebuild).mockResolvedValue({ host, kind: "structural" });
const watcher = await startAuthoredSourceWatcher({ coordinator, preparedHost: host });
@@ -215,7 +215,7 @@ describe("startAuthoredSourceWatcher", () => {
join(workspaceRoot, "tsconfig.base.json"),
'{"compilerOptions":{"strict":true}}\n',
);
- const host = createPreparedHost(appRoot);
+ const host = await createPreparedHost(appRoot);
const watcher = await startAuthoredSourceWatcher({
coordinator: createCoordinator(host),
preparedHost: host,
@@ -257,7 +257,7 @@ describe("startAuthoredSourceWatcher", () => {
);
await writeFile(join(packageRoot, "src", "index.ts"), "export const shared = true;\n");
await symlink(packageRoot, packageLink, "junction");
- const host = createPreparedHost(appRoot);
+ const host = await createPreparedHost(appRoot);
const watcher = await startAuthoredSourceWatcher({
coordinator: createCoordinator(host),
preparedHost: host,
@@ -285,7 +285,7 @@ describe("startAuthoredSourceWatcher", () => {
await writeFile(join(appRoot, "pnpm-workspace.yaml"), "packages:\n - packages/*\n");
await writeFile(tsconfigPath, "{}\n");
const host: PreparedDevelopmentApplicationHost = {
- ...createPreparedHost(appRoot),
+ ...(await createPreparedHost(appRoot)),
workspaceExtensions: [
{
packageRoot,
@@ -325,7 +325,7 @@ describe("startAuthoredSourceWatcher", () => {
temporaryDirectories.push(tempRoot);
await mkdir(join(appRoot, "agent"), { recursive: true });
await writeFile(join(appRoot, "package.json"), '{"name":"standalone-agent"}\n');
- const host = createPreparedHost(appRoot);
+ const host = await createPreparedHost(appRoot);
const watcher = await startAuthoredSourceWatcher({
coordinator: createCoordinator(host),
preparedHost: host,
@@ -347,7 +347,7 @@ describe("startAuthoredSourceWatcher", () => {
await writeFile(join(appRoot, "package.json"), '{"name":"watch-agent","type":"module"}\n');
await writeFile(join(appRoot, "tsconfig.base.a.json"), "{}\n");
await writeFile(join(appRoot, "tsconfig.json"), '{"extends":"./tsconfig.base.a.json"}\n');
- const host = createPreparedHost(appRoot);
+ const host = await createPreparedHost(appRoot);
const coordinator = createCoordinator(host);
const watcher = await startAuthoredSourceWatcher({ coordinator, preparedHost: host });
@@ -373,22 +373,21 @@ describe("startAuthoredSourceWatcher", () => {
});
});
-function createPreparedHost(
+async function createPreparedHost(
appRoot: string = DEFAULT_APP_ROOT,
-): PreparedDevelopmentApplicationHost {
+): Promise<PreparedDevelopmentApplicationHost> {
const agentRoot = join(appRoot, "agent");
+ const { manifest } = await compileFromMemory({
+ agentRoot,
+ appRoot,
+ model: "openai/gpt-5.4",
+ name: "watch-agent",
+ });
return {
appRoot,
compileResult: {
diagnostics: [],
- manifest: createCompiledAgentManifest({
- agentRoot,
- appRoot,
- config: {
- model: { id: "openai/gpt-5-mini", routing: { kind: "gateway", target: "openai" } },
- name: "watch-agent",
- },
- }),
+ manifest,
metadata: {} as PreparedDevelopmentApplicationHost["compileResult"]["metadata"],
paths: {} as PreparedDevelopmentApplicationHost["compileResult"]["paths"],
project: { agentRoot, appRoot, layout: "flat" },
diff --git a/packages/eve/src/internal/nitro/host/dev-host-fingerprint.integration.test.ts b/packages/eve/src/internal/nitro/host/dev-host-fingerprint.integration.test.ts
index b8d096c8b..afa6f5d40 100644
--- a/packages/eve/src/internal/nitro/host/dev-host-fingerprint.integration.test.ts
+++ b/packages/eve/src/internal/nitro/host/dev-host-fingerprint.integration.test.ts
@@ -3,9 +3,11 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
-import { createCompiledAgentManifest, type CompiledAgentManifest } from "#compiler/manifest.js";
+import { compileFromMemory } from "#compiler/compile-from-memory.js";
import { computeDevelopmentHostFingerprint } from "#internal/nitro/host/dev-host-fingerprint.js";
import type { PreparedDevelopmentApplicationHost } from "#internal/nitro/host/types.js";
+import { defineChannel, GET } from "#public/definitions/channel.js";
+import { defineSchedule } from "#public/definitions/schedule.js";
const temporaryDirectories: string[] = [];
@@ -19,10 +21,10 @@ afterEach(async () => {
});
interface HostVariant {
- readonly channels?: CompiledAgentManifest["channels"];
+ readonly channel?: { readonly path: string };
readonly instrumentationSlot?: string;
readonly instrumentationSource?: string;
- readonly schedules?: CompiledAgentManifest["schedules"];
+ readonly schedule?: { readonly cron: string; readonly markdown: string };
readonly workflowWorld?: "local" | "vercel";
}
@@ -38,18 +40,42 @@ async function createHost(variant: HostVariant = {}): Promise<PreparedDevelopmen
await writeFile(instrumentationSourcePath, variant.instrumentationSource);
}
- const manifest = createCompiledAgentManifest({
+ const modules = [
+ ...(variant.channel === undefined
+ ? []
+ : [
+ {
+ logicalPath: "channels/smoke.ts",
+ loadNamespace: async () => ({
+ default: defineChannel({
+ routes: [GET(variant.channel!.path, async () => new Response("ok"))],
+ }),
+ }),
+ },
+ ]),
+ ...(variant.schedule === undefined
+ ? []
+ : [
+ {
+ logicalPath: "schedules/heartbeat.ts",
+ loadNamespace: async () => ({
+ default: defineSchedule(variant.schedule!),
+ }),
+ },
+ ]),
+ ];
+ const { manifest } = await compileFromMemory({
agentRoot,
appRoot,
- channels: variant.channels ?? [],
- config: {
- model: { id: "openai/gpt-5-mini", routing: { kind: "gateway", target: "openai" } },
- name: "fingerprint-host",
+ agent: {
+ model: "openai/gpt-5.4",
...(variant.workflowWorld === undefined
? {}
: { experimental: { workflow: { world: variant.workflowWorld } } }),
},
- schedules: variant.schedules ?? [],
+ model: "openai/gpt-5.4",
+ modules,
+ name: "fingerprint-host",
});
return {
@@ -106,17 +132,7 @@ describe("computeDevelopmentHostFingerprint", () => {
const base = await computeDevelopmentHostFingerprint(await createHost());
const withRoute = await computeDevelopmentHostFingerprint(
await createHost({
- channels: [
- {
- kind: "channel",
- logicalPath: "channels/smoke.ts",
- method: "GET",
- name: "smoke",
- sourceId: "channels/smoke.ts",
- sourceKind: "module",
- urlPath: "/smoke",
- },
- ] as CompiledAgentManifest["channels"],
+ channel: { path: "/smoke" },
}),
);
@@ -150,17 +166,7 @@ describe("computeDevelopmentHostFingerprint", () => {
const base = await computeDevelopmentHostFingerprint(await createHost());
const withSchedule = await computeDevelopmentHostFingerprint(
await createHost({
- schedules: [
- {
- cron: "0 0 * * 0",
- hasRun: false,
- logicalPath: "schedules/heartbeat.md",
- markdown: "Report the weather.",
- name: "heartbeat",
- sourceId: "schedules/heartbeat.md",
- sourceKind: "markdown",
- },
- ],
+ schedule: { cron: "0 0 * * 0", markdown: "Report the weather." },
}),
);
diff --git a/packages/eve/src/internal/nitro/host/dev-host-fingerprint.ts b/packages/eve/src/internal/nitro/host/dev-host-fingerprint.ts
index 2b27a8a02..06a011456 100644
--- a/packages/eve/src/internal/nitro/host/dev-host-fingerprint.ts
+++ b/packages/eve/src/internal/nitro/host/dev-host-fingerprint.ts
@@ -2,6 +2,8 @@ import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";
import { readDevelopmentEnvironmentHostValues } from "#cli/dev/environment.js";
+import { resolveCompiledModuleExtensionScopeNamespace } from "#compiler/module-map.js";
+import { bundleAuthoredModuleForGeneration } from "#internal/authored-module-loader.js";
import { computeChannelRouteRegistrations } from "#internal/nitro/host/channel-routes.js";
import type { PreparedDevelopmentApplicationHost } from "#internal/nitro/host/types.js";
@@ -54,6 +56,24 @@ async function readInstrumentationSource(host: PreparedDevelopmentApplicationHos
readonly kind: "directory" | "file";
readonly modules: readonly { readonly slot: string | null; readonly source: string }[];
} | null> {
+ const instrumentation = host.compileResult.manifest.instrumentation;
+ if (instrumentation !== undefined) {
+ const binding = host.compileResult.manifest.bindings[instrumentation.sourceId];
+ if (binding === undefined) {
+ throw new Error(
+ `Compiled instrumentation source "${instrumentation.sourceId}" has no binding.`,
+ );
+ }
+ const source =
+ binding.backing.kind === "filesystem"
+ ? await bundleAuthoredModuleForGeneration(binding.backing.sourcePath, {
+ externalDependencies: binding.backing.externalDependencies,
+ extensionScopeNamespace: resolveCompiledModuleExtensionScopeNamespace(binding),
+ })
+ : JSON.stringify(binding.backing);
+ return { kind: "file", modules: [{ slot: null, source }] };
+ }
+
const paths = host.compiledArtifacts.instrumentationSourcePaths;
const layout = host.compiledArtifacts.instrumentationLayout;
if (paths === undefined || layout === undefined) {
diff --git a/packages/eve/src/internal/nitro/host/extension-capability-requirements.ts b/packages/eve/src/internal/nitro/host/extension-capability-requirements.ts
index 80c192260..366e25576 100644
--- a/packages/eve/src/internal/nitro/host/extension-capability-requirements.ts
+++ b/packages/eve/src/internal/nitro/host/extension-capability-requirements.ts
@@ -12,34 +12,50 @@ import type { AgentSourceManifest } from "#discover/manifest.js";
import { loadAuthoredModuleNamespace } from "#internal/authored-module-loader.js";
import { extensionUsesState } from "#internal/nitro/host/extension-state-usage.js";
import type { ModuleSourceRef } from "#shared/source-ref.js";
+import type { SourceDefinitionCompileOptions } from "#compiler/normalize-helpers.js";
/** Derives only the extension-facing contracts used by one authored tree. */
export async function deriveExtensionCapabilityRequirements(input: {
readonly declarationModule: ModuleSourceRef;
readonly manifest: AgentSourceManifest;
+ readonly packageName: string;
readonly runtimeDependencies: readonly string[];
+ readonly shortName: string;
readonly sourceRoot: string;
}): Promise<ExtensionCapabilityRequirements> {
const required = new Set<ExtensionCapability>(["extension"]);
- const loadOptions = { externalDependencies: input.runtimeDependencies };
const manifests = collectSubagentManifests(input.manifest);
const [tools, skills, instructions, declaration, usesState] = await Promise.all([
Promise.all(
manifests.flatMap((manifest) =>
- manifest.tools.map((source) => compileToolEntry(manifest.agentRoot, source, loadOptions)),
+ manifest.tools.map((source) =>
+ compileToolEntry(
+ manifest.agentRoot,
+ source,
+ createLoadOptions(input, source, manifest.agentRoot),
+ ),
+ ),
),
),
Promise.all(
manifests.flatMap((manifest) =>
manifest.skills.map((source) =>
- compileSkillSource(manifest.agentRoot, source, loadOptions),
+ compileSkillSource(
+ manifest.agentRoot,
+ source,
+ createLoadOptions(input, source, manifest.agentRoot),
+ ),
),
),
),
Promise.all(
manifests.flatMap((manifest) =>
manifest.instructions.map((source) =>
- compileInstructionsEntry(manifest.agentRoot, source, loadOptions),
+ compileInstructionsEntry(
+ manifest.agentRoot,
+ source,
+ createLoadOptions(input, source, manifest.agentRoot),
+ ),
),
),
),
@@ -80,6 +96,40 @@ export async function deriveExtensionCapabilityRequirements(input: {
);
}
+function createLoadOptions(
+ input: {
+ readonly packageName: string;
+ readonly runtimeDependencies: readonly string[];
+ readonly shortName: string;
+ readonly sourceRoot: string;
+ },
+ source: { readonly logicalPath: string },
+ moduleRoot: string,
+): SourceDefinitionCompileOptions & {
+ readonly binding: NonNullable<SourceDefinitionCompileOptions["binding"]>;
+ readonly registries: readonly [];
+} {
+ const owner = {
+ kind: "extension" as const,
+ namespace: input.shortName,
+ packageName: input.packageName,
+ };
+ return {
+ binding: {
+ backing: {
+ externalDependencies: input.runtimeDependencies,
+ extensionScope: { namespace: input.shortName, sourceRoot: input.sourceRoot },
+ kind: "filesystem",
+ sourcePath: join(moduleRoot, source.logicalPath),
+ },
+ logicalPath: source.logicalPath,
+ owner,
+ },
+ owner,
+ registries: [],
+ };
+}
+
function collectSubagentManifests(manifest: AgentSourceManifest): AgentSourceManifest[] {
return [
manifest,
diff --git a/packages/eve/src/internal/nitro/host/start-development-server.test.ts b/packages/eve/src/internal/nitro/host/start-development-server.test.ts
index f77095693..fef14764a 100644
--- a/packages/eve/src/internal/nitro/host/start-development-server.test.ts
+++ b/packages/eve/src/internal/nitro/host/start-development-server.test.ts
@@ -73,7 +73,7 @@ const mocks = vi.hoisted(() => {
return devServer;
}),
devServer,
- fetch: vi.fn(async () => new Response(null, { status: 200 })),
+ fetch: vi.fn(async () => Response.json({ revision: "test" })),
files,
fsControl,
listenerServer,
@@ -314,7 +314,7 @@ describe("isActiveDevelopmentServerForApp", () => {
it("matches only this app's recorded healthy loopback server", async () => {
const { isActiveDevelopmentServerForApp } = await import("./start-development-server.js");
seedStateRecord({ url: "http://127.0.0.1:42123/" });
- mocks.fetch.mockResolvedValue(new Response(null, { status: 200 }));
+ mocks.fetch.mockImplementation(async () => Response.json({ revision: "test" }));
vi.stubGlobal("fetch", mocks.fetch);
try {
@@ -330,6 +330,13 @@ describe("isActiveDevelopmentServerForApp", () => {
serverUrl: "http://127.0.0.1:42124/",
}),
).resolves.toBe(false);
+ mocks.fetch.mockResolvedValueOnce(new Response(null, { status: 200 }));
+ await expect(
+ isActiveDevelopmentServerForApp({
+ appRoot: "/tmp/eve-test",
+ serverUrl: "http://127.0.0.1:42123/",
+ }),
+ ).resolves.toBe(false);
} finally {
mocks.files.clear();
vi.unstubAllGlobals();
@@ -340,7 +347,7 @@ describe("isActiveDevelopmentServerForApp", () => {
describe("createDevelopmentServer", () => {
beforeEach(() => {
vi.clearAllMocks();
- mocks.fetch.mockResolvedValue(new Response(null, { status: 200 }));
+ mocks.fetch.mockImplementation(async () => Response.json({ revision: "test" }));
mocks.fsControl.stateReadError = undefined;
mocks.fsControl.stateWriteError = undefined;
mocks.authoredSourceWatcher.close.mockResolvedValue(undefined);
@@ -697,7 +704,7 @@ describe("createDevelopmentServer", () => {
expect(attached.kind).toBe("existing");
expect(attached.url).toBe(owner.url);
expect(mocks.createDevelopmentApplicationNitro).toHaveBeenCalledOnce();
- expect(mocks.fetch).toHaveBeenCalledWith("http://localhost:2000/eve/v1/health", {
+ expect(mocks.fetch).toHaveBeenCalledWith(new URL("/eve/v1/dev/runtime-artifacts", owner.url), {
redirect: "error",
signal: expect.any(AbortSignal),
});
@@ -817,10 +824,13 @@ describe("createDevelopmentServer", () => {
existing: "attach-if-unconfigured",
});
- expect(mocks.fetch).toHaveBeenCalledWith("http://localhost:2000/eve/v1/health", {
- redirect: "error",
- signal: expect.any(AbortSignal),
- });
+ expect(mocks.fetch).toHaveBeenCalledWith(
+ new URL("/eve/v1/dev/runtime-artifacts", "http://localhost:2000/"),
+ {
+ redirect: "error",
+ signal: expect.any(AbortSignal),
+ },
+ );
expect(mocks.fetch).toHaveBeenCalledOnce();
expect(mocks.createDevelopmentApplicationNitro).toHaveBeenCalledOnce();
expect(readStateRecord()).toEqual({ url: "http://localhost:2000/" });
diff --git a/packages/eve/src/internal/nitro/host/start-development-server.ts b/packages/eve/src/internal/nitro/host/start-development-server.ts
index 916bed8be..223dcb936 100644
--- a/packages/eve/src/internal/nitro/host/start-development-server.ts
+++ b/packages/eve/src/internal/nitro/host/start-development-server.ts
@@ -19,8 +19,8 @@ import {
import { resolveDiscoveryProject } from "#discover/project.js";
import { DevelopmentServerState } from "#internal/nitro/host/dev-server-state.js";
import { toErrorMessage } from "#shared/errors.js";
-import { isEveServerHealthy } from "#shared/eve-server-health.js";
import { isLoopbackServerUrl } from "#shared/network-address.js";
+import { readDevelopmentRuntimeArtifactsRevision } from "#services/dev-client/runtime-artifacts.js";
import { handleDevRuntimeArtifactsRequest } from "#internal/nitro/routes/dev-runtime-artifacts.js";
import { resolveNitroCompiledArtifactsSource } from "#internal/nitro/routes/runtime-artifacts.js";
import {
@@ -64,6 +64,7 @@ import {
} from "#internal/nitro/host/dev-server-url.js";
const MAX_ALLOWED_DEVELOPMENT_SERVER_PORT = 65_535;
+const DEVELOPMENT_SERVER_READINESS_TIMEOUT_MS = 1_000;
const PORT_ENV = "PORT";
export { normalizeDevelopmentServerClientUrl };
@@ -82,7 +83,7 @@ export async function isActiveDevelopmentServerForApp(input: {
if (
recordedServerUrl === undefined ||
!isLoopbackServerUrl(recordedServerUrl) ||
- !(await isEveServerHealthy(recordedServerUrl))
+ !(await isDevelopmentServerReady(recordedServerUrl))
) {
return false;
}
@@ -96,6 +97,15 @@ export async function isActiveDevelopmentServerForApp(input: {
}
}
+async function isDevelopmentServerReady(serverUrl: string): Promise<boolean> {
+ return (
+ (await readDevelopmentRuntimeArtifactsRevision({
+ serverUrl,
+ timeoutMs: DEVELOPMENT_SERVER_READINESS_TIMEOUT_MS,
+ })) !== undefined
+ );
+}
+
function isAddressInUseError(error: unknown): error is NodeJS.ErrnoException {
return error instanceof Error && "code" in error && error.code === "EADDRINUSE";
}
@@ -382,7 +392,7 @@ async function startNitroDevelopmentServer(
if (
existingServerUrl !== undefined &&
isLoopbackServerUrl(existingServerUrl) &&
- (await isEveServerHealthy(existingServerUrl))
+ (await isDevelopmentServerReady(existingServerUrl))
) {
if (options.existing === "attach-if-unconfigured" && !hasExplicitEndpoint) {
return {
diff --git a/packages/eve/src/internal/nitro/host/start-production-server.test.ts b/packages/eve/src/internal/nitro/host/start-production-server.test.ts
index d6ff76ca6..715657523 100644
--- a/packages/eve/src/internal/nitro/host/start-production-server.test.ts
+++ b/packages/eve/src/internal/nitro/host/start-production-server.test.ts
@@ -88,6 +88,7 @@ describe("startProductionServer", () => {
it("starts the built server with Nitro host and port environment", async () => {
const { startProductionServer } = await import("./start-production-server.js");
const child = createChildProcess();
+ (child.stdout as PassThrough).write("Listening on http://127.0.0.1:4321/\n");
mocks.spawn.mockReturnValueOnce(child);
const server = await startProductionServer("/tmp/app", {
@@ -115,11 +116,6 @@ describe("startProductionServer", () => {
stdio: ["ignore", "pipe", "pipe"],
},
);
- expect(globalThis.fetch).toHaveBeenCalledWith(
- "http://127.0.0.1:4321/eve/v1/health",
- expect.any(Object),
- );
-
await server.close();
expect(child.kill).toHaveBeenCalledWith("SIGTERM");
@@ -129,6 +125,7 @@ describe("startProductionServer", () => {
const { startProductionServer } = await import("./start-production-server.js");
const child = createChildProcess();
process.env.PORT = "4567";
+ (child.stdout as PassThrough).write("Listening on http://0.0.0.0:4567/\n");
mocks.spawn.mockReturnValueOnce(child);
const server = await startProductionServer("/tmp/app");
@@ -151,7 +148,11 @@ describe("startProductionServer", () => {
it("resolves port 0 before spawning the built server", async () => {
const { startProductionServer } = await import("./start-production-server.js");
const child = createChildProcess();
- mocks.spawn.mockReturnValueOnce(child);
+ mocks.spawn.mockImplementationOnce((_command, _args, options) => {
+ const port = (options as { env?: NodeJS.ProcessEnv }).env?.PORT;
+ (child.stdout as PassThrough).write(`Listening on http://127.0.0.1:${port}/\n`);
+ return child;
+ });
const server = await startProductionServer("/tmp/app", {
host: "127.0.0.1",
diff --git a/packages/eve/src/internal/nitro/host/start-production-server.ts b/packages/eve/src/internal/nitro/host/start-production-server.ts
index 4522ab7a5..5618f1960 100644
--- a/packages/eve/src/internal/nitro/host/start-production-server.ts
+++ b/packages/eve/src/internal/nitro/host/start-production-server.ts
@@ -1,12 +1,11 @@
import { spawn, type ChildProcess } from "node:child_process";
import { existsSync } from "node:fs";
-import { createServer } from "node:net";
+import { createConnection, createServer } from "node:net";
import { join, resolve } from "node:path";
import { setTimeout as sleep } from "node:timers/promises";
import { loadDevelopmentEnvironmentFiles } from "#cli/dev/environment.js";
import { prewarmBuiltAppSandboxes } from "#execution/sandbox/prewarm.js";
-import { EVE_HEALTH_ROUTE_PATH } from "#protocol/routes.js";
import type { ProductionServerHandle } from "#internal/nitro/host/types.js";
const DEFAULT_PRODUCTION_SERVER_HOST = "0.0.0.0";
@@ -24,10 +23,6 @@ function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
-function isAddressInUseError(error: unknown): boolean {
- return error instanceof Error && "code" in error && error.code === "EADDRINUSE";
-}
-
function resolveOutputServerEntry(appRoot: string): string {
return join(resolve(appRoot), ".output", "server", "index.mjs");
}
@@ -115,42 +110,19 @@ function parseServerUrlFromOutput(output: string): string | undefined {
return normalizeServerClientUrl(match[0]);
}
-async function waitForHealth(input: {
- child: ChildProcess;
- getStartError(): unknown;
- url: string;
-}): Promise<string> {
- const { child, url } = input;
- const healthUrl = new URL(EVE_HEALTH_ROUTE_PATH, url).toString();
- const deadline = Date.now() + HEALTH_TIMEOUT_MS;
-
- while (Date.now() < deadline) {
- const startError = input.getStartError();
- if (startError !== undefined) {
- throw startError;
- }
-
- if (child.exitCode !== null || child.signalCode !== null) {
- throw new Error(
- `Built server process exited (code=${String(child.exitCode)}, signal=${String(child.signalCode)}) before becoming healthy.`,
- );
- }
-
- try {
- const response = await fetch(healthUrl, { signal: AbortSignal.timeout(2_000) });
- if (response.ok) return new URL(url).toString();
- } catch (error) {
- if (isAddressInUseError(error)) {
- throw error;
- }
- }
-
- await sleep(HEALTH_POLL_INTERVAL_MS);
- }
-
- throw new Error(
- `Built server did not become healthy within ${HEALTH_TIMEOUT_MS / 1000}s at ${healthUrl}.`,
- );
+async function isListening(url: string): Promise<boolean> {
+ const target = new URL(url);
+ const port = Number(target.port || (target.protocol === "https:" ? 443 : 80));
+ return await new Promise((resolveReady) => {
+ const socket = createConnection({ host: target.hostname, port });
+ const finish = (ready: boolean) => {
+ socket.destroy();
+ resolveReady(ready);
+ };
+ socket.setTimeout(2_000, () => finish(false));
+ socket.once("connect", () => finish(true));
+ socket.once("error", () => finish(false));
+ });
}
async function waitForReady(input: {
@@ -170,12 +142,8 @@ async function waitForReady(input: {
const parsedUrl = parseServerUrlFromOutput(input.getOutput());
const url = parsedUrl ?? input.knownUrl;
- if (url !== undefined) {
- return await waitForHealth({
- child: input.child,
- getStartError: input.getStartError,
- url,
- });
+ if (url !== undefined && (parsedUrl !== undefined || (await isListening(url)))) {
+ return new URL(url).toString();
}
if (input.child.exitCode !== null || input.child.signalCode !== null) {
diff --git a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.test.ts b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.test.ts
deleted file mode 100644
index 73e9af5a9..000000000
--- a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.test.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { AgentInfoResultSchema } from "#client/agent-info-schema.js";
-import { createCompiledAgentManifest } from "#compiler/manifest.js";
-import { buildAgentInfoResponseFromManifest } from "#internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.js";
-
-describe("buildAgentInfoResponseFromManifest", () => {
- it("reports opt-in framework tools as unavailable", () => {
- const manifest = createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- model: {
- id: "openai/gpt-5",
- routing: { kind: "gateway", target: "openai" },
- },
- name: "app",
- },
- });
-
- const result = buildAgentInfoResponseFromManifest(
- { manifest, schedules: [] },
- {
- gatewayCredentials: { apiKey: false, oidc: false },
- mode: "development",
- },
- );
-
- expect(result.tools.available.map((tool) => tool.name)).not.toContain("glob");
- expect(result.tools.available.map((tool) => tool.name)).not.toContain("grep");
- expect(result.tools.framework.find((tool) => tool.name === "glob")?.status).toBe("opt-in");
- expect(result.tools.framework.find((tool) => tool.name === "grep")?.status).toBe("opt-in");
- expect(AgentInfoResultSchema.safeParse(result).success).toBe(true);
- });
-
- it("reports unresolved dynamic models without a model id", () => {
- const manifest = createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- dynamicModel: {
- eventNames: ["turn.started"],
- logicalPath: "agent.ts",
- sourceId: "agent-config",
- sourceKind: "module",
- },
- name: "app",
- },
- });
-
- const result = buildAgentInfoResponseFromManifest(
- { manifest, schedules: [] },
- {
- gatewayCredentials: { apiKey: false, oidc: false },
- mode: "development",
- },
- );
-
- expect(result.agent.model).toEqual({
- reasoning: undefined,
- routing: { kind: "dynamic" },
- });
- expect("id" in result.agent.model).toBe(false);
- expect(AgentInfoResultSchema.safeParse(result).success).toBe(true);
- });
-});
diff --git a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.ts b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.ts
deleted file mode 100644
index b4ba86fa5..000000000
--- a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.ts
+++ /dev/null
@@ -1,245 +0,0 @@
-import {
- getAllFrameworkToolNames,
- getFrameworkDynamicToolResolvers,
-} from "#runtime/framework-tools/index.js";
-import {
- getAllFrameworkChannelNames,
- getFrameworkChannelDefinitions,
-} from "#runtime/framework-channels/index.js";
-import type { AgentInfoManifestData } from "#internal/nitro/routes/agent-info/load-agent-info-data.js";
-import type { ResolvedChannelDefinition } from "#runtime/types.js";
-import { LOAD_SKILL_TOOL_NAME } from "#runtime/skills/fragment-context.js";
-import { WORKFLOW_TOOL_NAME } from "#shared/workflow-sandbox.js";
-import type {
- AgentInfoFrameworkChannelEntry,
- AgentInfoResponse,
-} from "#internal/nitro/routes/agent-info/build-agent-info-response.js";
-import {
- buildFrameworkToolInfo,
- getRootDelegationToolNames,
- renderChannel,
- renderDynamicResolver,
- renderSchedule,
- renderSubagent,
- toSource,
-} from "#internal/nitro/routes/agent-info/build-agent-info-response.js";
-import {
- type GatewayCredentialPresence,
- resolveModelEndpointStatus,
-} from "#internal/resolve-model-endpoint-status.js";
-import type { ChatGptAuthState } from "#public/models/openai/chatgpt/token-broker.js";
-
-function toChatGptEndpoint(state: ChatGptAuthState | undefined) {
- if (state === undefined) return undefined;
- return {
- state: state.kind,
- ...(state.kind === "ready" &&
- state.accountLabel !== undefined && { accountLabel: state.accountLabel }),
- };
-}
-
-export function buildAgentInfoResponseFromManifest(
- data: AgentInfoManifestData,
- input: {
- readonly mode: AgentInfoResponse["mode"];
- readonly gatewayCredentials: GatewayCredentialPresence;
- readonly chatgptAuth?: ChatGptAuthState;
- },
-): AgentInfoResponse {
- const manifest = data.manifest;
- const authoredChannels = manifest.channels.filter((channel) => channel.kind === "channel");
- const disabledFrameworkChannels = manifest.channels
- .filter((channel) => channel.kind === "disabled")
- .map((channel) => channel.name);
- const authoredToolNames = new Set(manifest.tools.map((tool) => tool.name));
- const disabledFrameworkTools = new Set(manifest.disabledFrameworkTools);
- const allFrameworkToolNames = getAllFrameworkToolNames();
- const allFrameworkChannelNames = getAllFrameworkChannelNames();
- const frameworkChannelDefinitions = getFrameworkChannelDefinitions();
- const authoredTools = manifest.tools.map((tool) => ({
- ...toSource(tool),
- description: tool.description,
- hasAuth: false,
- hasCompactionHook: false,
- hasExecute: true,
- hasModelOutputProjection: false,
- hasOutputSchema: tool.outputSchema !== undefined && tool.outputSchema !== null,
- inputSchema: tool.inputSchema,
- name: tool.name,
- origin: "authored" as const,
- outputSchema: tool.outputSchema ?? null,
- replacesFrameworkTool: allFrameworkToolNames.has(tool.name),
- requiresApproval: false,
- }));
- const authoredChannelNames = new Set(authoredChannels.map((channel) => channel.name));
- const disabledFrameworkChannelNames = new Set(disabledFrameworkChannels);
- const activeFrameworkChannels = frameworkChannelDefinitions.filter(
- (channel) =>
- !authoredChannelNames.has(channel.name) && !disabledFrameworkChannelNames.has(channel.name),
- );
- const frameworkToolInfo = buildFrameworkToolInfo({
- authoredToolNames,
- delegationToolNames: getRootDelegationToolNames(manifest),
- disabledFrameworkToolNames: disabledFrameworkTools,
- });
- const renderedAuthoredChannels = authoredChannels.map((channel) => ({
- ...toSource(channel),
- adapterKind: channel.adapterKind,
- method: channel.method,
- name: channel.name,
- origin: "authored" as const,
- urlPath: channel.urlPath,
- }));
-
- return {
- agent: {
- agentRoot: manifest.agentRoot,
- appRoot: manifest.appRoot,
- configSource: manifest.config.source ? toSource(manifest.config.source) : undefined,
- description: manifest.config.description,
- model:
- manifest.config.dynamicModel === undefined
- ? {
- contextWindowTokens: manifest.config.model.contextWindowTokens,
- id: manifest.config.model.id,
- providerOptions: manifest.config.model.providerOptions,
- reasoning: manifest.config.reasoning,
- source: manifest.config.model.source
- ? toSource(manifest.config.model.source)
- : undefined,
- routing: manifest.config.model.routing,
- endpoint: resolveModelEndpointStatus(
- manifest.config.model.routing,
- input.gatewayCredentials,
- toChatGptEndpoint(input.chatgptAuth),
- ),
- }
- : {
- reasoning: manifest.config.reasoning,
- routing: { kind: "dynamic" },
- },
- name: manifest.config.name,
- outputSchema: manifest.config.outputSchema,
- },
- capabilities: {
- devRoutes: input.mode === "development",
- },
- channels: {
- authored: renderedAuthoredChannels,
- available: [
- ...activeFrameworkChannels.map((channel) =>
- renderChannel(channel as ResolvedChannelDefinition, {
- origin: "framework",
- }),
- ),
- ...renderedAuthoredChannels,
- ],
- disabledFramework: disabledFrameworkChannels,
- framework: frameworkChannelDefinitions
- .filter((channel) => allFrameworkChannelNames.has(channel.name))
- .map((channel) => {
- const replacedByAuthoredChannel = authoredChannelNames.has(channel.name);
- const disabledByAuthor = disabledFrameworkChannelNames.has(channel.name);
- const status: AgentInfoFrameworkChannelEntry["status"] = disabledByAuthor
- ? "disabled"
- : replacedByAuthoredChannel
- ? "replaced"
- : "active";
-
- return {
- ...renderChannel(channel as ResolvedChannelDefinition, {
- origin: "framework",
- }),
- disabledByAuthor,
- replacedByAuthoredChannel,
- status,
- };
- }),
- },
- connections: manifest.connections.map((connection) => ({
- ...toSource(connection),
- connectionName: connection.connectionName,
- description: connection.description,
- hasApproval: false,
- hasAuthorization: connection.vercelConnect !== undefined,
- hasHeaders: false,
- protocol: connection.protocol,
- url: connection.url,
- })),
- diagnostics: {
- discoveryErrors: manifest.diagnosticsSummary.errors,
- discoveryWarnings: manifest.diagnosticsSummary.warnings,
- },
- hooks: manifest.hooks.map((hook) => ({
- ...toSource(hook),
- eventNames: [],
- slug: hook.slug,
- })),
- instructions: {
- dynamic: manifest.dynamicInstructions.map((resolver) =>
- renderDynamicResolver(resolver, { origin: "authored" }),
- ),
- static: manifest.instructions.map((instructions) => ({
- ...toSource(instructions),
- content: instructions.content,
- name: instructions.name,
- role: instructions.role,
- })),
- },
- kind: "eve-agent-info",
- mode: input.mode,
- sandbox:
- manifest.sandbox === null
- ? null
- : {
- ...toSource(manifest.sandbox),
- description: manifest.sandbox.description,
- hasBootstrap: false,
- hasOnSession: false,
- revalidationKey: manifest.sandbox.revalidationKey,
- sourceHash: manifest.sandbox.sourceHash,
- },
- schedules: data.schedules.map(renderSchedule),
- skills: {
- static: manifest.skills.map((skill) => ({
- ...toSource(skill),
- description: skill.description,
- license: skill.license,
- markdown: skill.markdown,
- metadata: skill.metadata,
- name: skill.name,
- })),
- dynamic: manifest.dynamicSkills.map((resolver) =>
- renderDynamicResolver(resolver, { origin: "authored" }),
- ),
- },
- subagents: {
- local: manifest.subagents.map(renderSubagent),
- total: manifest.subagents.length,
- },
- tools: {
- available: [...frameworkToolInfo.available, ...authoredTools],
- authored: authoredTools,
- disabledFramework: [...manifest.disabledFrameworkTools],
- dynamic: [
- ...getFrameworkDynamicToolResolvers().map((resolver) =>
- renderDynamicResolver(resolver, { origin: "framework" }),
- ),
- ...manifest.dynamicTools.map((resolver) =>
- renderDynamicResolver(resolver, { origin: "authored" }),
- ),
- ],
- framework: frameworkToolInfo.framework,
- reserved: [WORKFLOW_TOOL_NAME, LOAD_SKILL_TOOL_NAME],
- },
- version: 2,
- workflow: {
- enabled: manifest.workflowTool !== undefined,
- toolName: WORKFLOW_TOOL_NAME,
- },
- workspace: {
- resourceRoot: manifest.workspaceResourceRoot,
- rootEntries: [...manifest.workspaceResourceRoot.rootEntries],
- },
- };
-}
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.ts
index 31c7603d5..426b64111 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
@@ -1,125 +1,162 @@
import { describe, expect, it } from "vitest";
-import { createCompiledAgentManifest } from "#compiler/manifest.js";
-import {
- buildAgentInfoResponse,
- buildFrameworkToolInfo,
-} from "#internal/nitro/routes/agent-info/build-agent-info-response.js";
-import { resolveAgent } from "#runtime/resolve-agent.js";
+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";
-describe("buildFrameworkToolInfo", () => {
- it("reports opt-in tools as inactive and unavailable by default", () => {
- const info = buildFrameworkToolInfo({
- authoredToolNames: new Set(),
- delegationToolNames: new Set(),
- disabledFrameworkToolNames: new Set(),
- });
-
- expect(info.available.map((tool) => tool.name)).not.toContain("glob");
- expect(info.available.map((tool) => tool.name)).not.toContain("grep");
- expect(info.framework.find((tool) => tool.name === "glob")).toMatchObject({
- status: "opt-in",
- });
- expect(info.framework.find((tool) => tool.name === "grep")).toMatchObject({
- status: "opt-in",
- });
- });
-
- it("reports an authored opt-in tool as replacing the framework definition", () => {
- const info = buildFrameworkToolInfo({
- authoredToolNames: new Set(["grep"]),
- delegationToolNames: new Set(),
- disabledFrameworkToolNames: new Set(),
- });
-
- expect(info.framework.find((tool) => tool.name === "grep")).toMatchObject({
- replacedByAuthoredTool: true,
- status: "replaced",
+describe("buildAgentInfoResponse", () => {
+ it("projects v3 exclusively from the effective compiled graph", async () => {
+ const { manifest } = await compileFromMemory({
+ model: "openai/gpt-5.4",
+ name: "info-agent",
+ tools: [{ name: "weather" }],
});
- });
- it("reports the built-in agent action as active and available by default", () => {
- const info = buildFrameworkToolInfo({
- authoredToolNames: new Set(),
- delegationToolNames: new Set(),
- disabledFrameworkToolNames: new Set(),
- });
+ const response = buildAgentInfoResponse(
+ { manifest, schedules: [] },
+ {
+ gatewayCredentials: { apiKey: true, oidc: false },
+ mode: "development",
+ },
+ );
- expect(info.available.map((tool) => tool.name)).toContain("agent");
- expect(info.framework.find((tool) => tool.name === "agent")).toMatchObject({
- status: "active",
- });
+ expect(response).toMatchObject({
+ agent: {
+ model: {
+ endpoint: { connected: true, credential: "api-key", kind: "gateway" },
+ id: "openai/gpt-5.4",
+ routing: { kind: "gateway", target: "openai" },
+ },
+ name: "info-agent",
+ nodeId: "__root__",
+ },
+ capabilities: { devRoutes: true },
+ kind: "eve-agent-info",
+ version: 3,
+ });
+ expect(response.tools.static).toContainEqual(
+ expect.objectContaining({
+ name: "weather",
+ owner: { kind: "application" },
+ sourceKind: "module",
+ }),
+ );
+ expect(response.channels.routes).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ method: "GET", urlPath: "/eve/v1/health" }),
+ expect.objectContaining({ method: "GET", urlPath: "/eve/v1/info" }),
+ ]),
+ );
+ expect(response.sandbox).toMatchObject({
+ logicalPath: "sandbox.ts",
+ owner: { feature: "eve:defaults", kind: "framework" },
+ });
+ expect(response.composition.shadowed).toContainEqual(
+ expect.objectContaining({
+ logicalPath: "agent.ts",
+ owner: { feature: "eve:defaults", kind: "framework" },
+ winnerSourceId: "memory:info-agent:agent.ts",
+ }),
+ );
});
- it("reports the built-in agent action as disabled and unavailable", () => {
- const info = buildFrameworkToolInfo({
- authoredToolNames: new Set(),
- delegationToolNames: new Set(),
- disabledFrameworkToolNames: new Set(["agent"]),
- });
+ it("derives kernel effects only from active framework-owned canonical slots", async () => {
+ const { manifest } = await compileFromMemory({ model: "openai/gpt-5.4" });
+ const response = buildAgentInfoResponse(
+ { manifest, schedules: [] },
+ {
+ gatewayCredentials: { apiKey: false, oidc: false },
+ mode: "production",
+ },
+ );
- expect(info.available.map((tool) => tool.name)).not.toContain("agent");
- expect(info.framework.find((tool) => tool.name === "agent")).toMatchObject({
- disabledByAuthor: true,
- status: "disabled",
- });
+ expect(response.kernelEffects).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ kind: "request-input" }),
+ expect.objectContaining({ action: "subagent-call", kind: "dispatch" }),
+ ]),
+ );
});
- it("reports a declared agent delegation tool as replacing the recursive action", () => {
- const info = buildFrameworkToolInfo({
- authoredToolNames: new Set(),
- delegationToolNames: new Set(["agent"]),
- disabledFrameworkToolNames: new Set(),
+ it("reports selected instrumentation provenance from the compiled graph", async () => {
+ const { manifest } = await compileFromMemory({
+ model: "openai/gpt-5.4",
+ modules: [
+ {
+ loadNamespace: async () => ({ default: defineInstrumentation({}) }),
+ logicalPath: "instrumentation.ts",
+ },
+ ],
});
+ const response = buildAgentInfoResponse(
+ { manifest, schedules: [] },
+ {
+ gatewayCredentials: { apiKey: false, oidc: false },
+ mode: "production",
+ },
+ );
- expect(info.available.map((tool) => tool.name)).not.toContain("agent");
- expect(info.framework.find((tool) => tool.name === "agent")).toMatchObject({
- replacedByAuthoredTool: false,
- status: "replaced",
+ expect(response.instrumentation).toMatchObject({
+ binding: { backing: { kind: "programmatic" } },
+ logicalPath: "instrumentation.ts",
+ owner: { kind: "application" },
});
});
- it("reports an authored agent tool as replacing the recursive action", () => {
- const info = buildFrameworkToolInfo({
- authoredToolNames: new Set(["agent"]),
- delegationToolNames: new Set(),
- disabledFrameworkToolNames: new Set(),
+ it("reports selected Workflow provenance from the compiled graph", async () => {
+ const { manifest } = await compileFromMemory({
+ model: "openai/gpt-5.4",
+ modules: [
+ {
+ loadNamespace: async () => ({ default: experimental_workflow({ maxSubagents: 5 }) }),
+ logicalPath: "tools/workflow.ts",
+ },
+ ],
});
+ const response = buildAgentInfoResponse(
+ { manifest, schedules: [] },
+ {
+ gatewayCredentials: { apiKey: false, oidc: false },
+ mode: "production",
+ },
+ );
- expect(info.framework.find((tool) => tool.name === "agent")).toMatchObject({
- replacedByAuthoredTool: true,
- status: "replaced",
+ expect(response.workflow).toMatchObject({
+ enabled: true,
+ source: {
+ binding: { backing: { kind: "programmatic" } },
+ logicalPath: "tools/workflow.ts",
+ owner: { kind: "application" },
+ },
+ toolName: "Workflow",
});
});
-});
-describe("buildAgentInfoResponse", () => {
- it("preserves direct-provider routing from the compiled manifest", async () => {
- const manifest = createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- compaction: {},
- model: {
- id: "openai/gpt-5",
- routing: { kind: "external", provider: "openai" },
+ it("reports an authored webSearch sentinel as a prepared provider effect", async () => {
+ const { manifest } = await compileFromMemory({
+ model: "openai/gpt-5.4",
+ modules: [
+ {
+ loadNamespace: async () => ({ default: webSearch({ provider: "parallel" }) }),
+ logicalPath: "tools/web_search.ts",
},
- name: "direct-model-agent",
- },
+ ],
});
- const agent = await resolveAgent({
- manifest,
- moduleMap: { nodes: { __root__: { modules: {} } } },
- });
-
const response = buildAgentInfoResponse(
- { agent, manifest, schedules: [] },
- { mode: "development" },
+ { manifest, schedules: [] },
+ {
+ gatewayCredentials: { apiKey: false, oidc: false },
+ mode: "production",
+ },
);
- expect(response.agent.model).toMatchObject({
- id: "openai/gpt-5",
- routing: { kind: "external", provider: "openai" },
- });
+ expect(response.kernelEffects).toContainEqual(
+ expect.objectContaining({
+ kind: "provider-tool",
+ sourceId: expect.stringContaining("tools/web_search.ts"),
+ }),
+ );
});
});
diff --git a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts
index f130f23e8..d604f9fe8 100644
--- a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts
+++ b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts
@@ -1,617 +1,383 @@
-import { ROOT_COMPILED_AGENT_NODE_ID } from "#compiler/manifest.js";
-import {
- getAllFrameworkToolDefinitions,
- getAllFrameworkToolNames,
- getFrameworkDynamicToolResolvers,
- getOptInFrameworkToolNames,
-} from "#runtime/framework-tools/index.js";
-import {
- getAllFrameworkChannelNames,
- getFrameworkChannelDefinitions,
-} from "#runtime/framework-channels/index.js";
import type {
- AgentInfoData,
CompiledAgentManifest,
- CompiledSubagentNode,
- ResolvedSandboxDefinition,
- ResolvedScheduleDefinition,
- ResolvedSkillDefinition,
-} from "#internal/nitro/routes/agent-info/load-agent-info-data.js";
-import type {
- ResolvedAgent,
- ResolvedChannelDefinition,
- ResolvedToolDefinition,
-} from "#runtime/types.js";
-import { serializeInputSchema, serializeOutputSchema } from "#shared/tool-schema.js";
-import { LOAD_SKILL_TOOL_NAME } from "#runtime/skills/fragment-context.js";
+ CompiledAgentNodeManifest,
+ CompiledAgentResources,
+ CompiledDynamicInstructionsDefinition,
+ CompiledDynamicSkillDefinition,
+ CompiledDynamicToolDefinition,
+} from "#compiler/manifest.js";
+import { ROOT_COMPILED_AGENT_NODE_ID } from "#compiler/manifest.js";
+import type { AgentSourceOwner, CompiledModuleBinding } from "#compiler/source-graph.js";
+import type { AgentInfoResult, AgentInfoSource } from "#client/agent-info-schema.js";
+import type { AgentInfoManifestData } from "#internal/nitro/routes/agent-info/load-agent-info-data.js";
+import {
+ type GatewayCredentialPresence,
+ resolveModelEndpointStatus,
+} from "#internal/resolve-model-endpoint-status.js";
+import type { ChatGptAuthState } from "#public/models/openai/chatgpt/token-broker.js";
import { WORKFLOW_TOOL_NAME } from "#shared/workflow-sandbox.js";
-import type { AgentReasoningDefinition, ModelRouting } from "#shared/agent-definition.js";
-import type { ModelEndpointStatus } from "#shared/model-endpoint-status.js";
-
-export interface AgentInfoSource {
- readonly exportName?: string;
- readonly logicalPath: string;
- readonly sourceId?: string;
- readonly sourceKind: string;
-}
-
-export interface AgentInfoToolEntry extends AgentInfoSource {
- readonly description: string;
- readonly hasAuth: boolean;
- readonly hasExecute: boolean;
- readonly hasModelOutputProjection: boolean;
- readonly hasOutputSchema: boolean;
- readonly inputSchema: unknown;
- readonly name: string;
- readonly origin: "authored" | "framework";
- readonly outputSchema: unknown;
- readonly replacesFrameworkTool: boolean;
- readonly requiresApproval: boolean;
-}
-
-export interface AgentInfoFrameworkToolEntry extends AgentInfoToolEntry {
- readonly disabledByAuthor: boolean;
- readonly replacedByAuthoredTool: boolean;
- readonly status: "active" | "disabled" | "opt-in" | "replaced";
-}
-
-export interface AgentInfoDynamicResolverEntry extends AgentInfoSource {
- readonly eventNames: readonly string[];
- readonly origin: "authored" | "framework";
- readonly slug: string;
-}
-
-export interface AgentInfoTools {
- readonly available: readonly AgentInfoToolEntry[];
- readonly authored: readonly AgentInfoToolEntry[];
- readonly disabledFramework: readonly string[];
- readonly dynamic: readonly AgentInfoDynamicResolverEntry[];
- readonly framework: readonly AgentInfoFrameworkToolEntry[];
- readonly reserved: readonly string[];
-}
-
-export interface AgentInfoSkillEntry extends AgentInfoSource {
- readonly description: string;
- readonly license?: string;
- readonly markdown: string;
- readonly metadata?: Readonly<Record<string, string>>;
- readonly name: string;
-}
-
-export interface AgentInfoInstructionsEntry extends AgentInfoSource {
- readonly content: string;
- readonly name: string;
- readonly role: "system" | "user";
-}
-
-export interface AgentInfoInstructions {
- readonly dynamic: readonly AgentInfoDynamicResolverEntry[];
- readonly static: readonly AgentInfoInstructionsEntry[];
-}
-
-export interface AgentInfoScheduleEntry extends AgentInfoSource {
- readonly cron: string;
- readonly hasRun: boolean;
- readonly markdown?: string;
- readonly name: string;
-}
-
-export interface AgentInfoSubagentEntry extends AgentInfoSource {
- readonly description?: string;
- readonly entryPath: string;
- readonly name: string;
- readonly nodeId: string;
- readonly rootPath: string;
- readonly summary: {
- readonly channels: number;
- readonly connections: number;
- readonly hooks: number;
- readonly instructions: boolean;
- readonly schedules: number;
- readonly skills: number;
- readonly tools: number;
- };
-}
-
-export interface AgentInfoChannelEntry extends AgentInfoSource {
- readonly adapterKind?: string;
- readonly method: string;
- readonly name: string;
- readonly origin: "authored" | "framework";
- readonly urlPath: string;
-}
-
-export interface AgentInfoFrameworkChannelEntry extends AgentInfoChannelEntry {
- readonly disabledByAuthor: boolean;
- readonly replacedByAuthoredChannel: boolean;
- readonly status: "active" | "disabled" | "replaced";
-}
-
-export interface AgentInfoChannels {
- readonly authored: readonly AgentInfoChannelEntry[];
- readonly available: readonly AgentInfoChannelEntry[];
- readonly disabledFramework: readonly string[];
- readonly framework: readonly AgentInfoFrameworkChannelEntry[];
-}
-
-export interface AgentInfoConnectionEntry extends AgentInfoSource {
- readonly connectionName: string;
- readonly description: string;
- readonly hasApproval: boolean;
- readonly hasAuthorization: boolean;
- readonly hasHeaders: boolean;
- readonly protocol: string;
- readonly toolFilter?: unknown;
- readonly url: string;
-}
-
-export interface AgentInfoHookEntry extends AgentInfoSource {
- readonly eventNames: readonly string[];
- readonly slug: string;
-}
-
-export interface AgentInfoSandboxEntry extends AgentInfoSource {
- readonly backendKind?: string;
- readonly description?: string;
- readonly hasBootstrap: boolean;
- readonly hasOnSession: boolean;
- readonly revalidationKey?: string;
- readonly sourceHash?: string;
-}
-
-export interface AgentInfoDiagnostics {
- readonly discoveryErrors: number;
- readonly discoveryWarnings: number;
-}
-
-interface AgentInfoModelBase {
- readonly contextWindowTokens?: number;
- readonly providerOptions?: unknown;
- /** The agent's authored reasoning effort, forwarded to the model call. */
- readonly reasoning?: AgentReasoningDefinition;
- readonly source?: AgentInfoSource;
-}
-export type AgentInfoModel = AgentInfoModelBase &
- (
- | {
- readonly id: string;
- readonly routing: ModelRouting;
- readonly endpoint?: ModelEndpointStatus;
- }
- | {
- readonly id?: never;
- readonly routing: { readonly kind: "dynamic" };
- readonly endpoint?: never;
- }
- );
+export type AgentInfoResponse = AgentInfoResult;
-export interface AgentInfoResponse {
- readonly agent: {
- readonly agentRoot: string;
- readonly appRoot: string;
- readonly configSource?: AgentInfoSource;
- readonly description?: string;
- readonly model: AgentInfoModel;
- readonly name: string;
- readonly outputSchema?: unknown;
- };
- readonly capabilities: {
- readonly devRoutes: boolean;
- };
- readonly channels: AgentInfoChannels;
- readonly connections: readonly AgentInfoConnectionEntry[];
- readonly diagnostics: AgentInfoDiagnostics;
- readonly hooks: readonly AgentInfoHookEntry[];
- readonly instructions: AgentInfoInstructions;
- readonly kind: "eve-agent-info";
- readonly mode: "development" | "production";
- readonly sandbox: AgentInfoSandboxEntry | null;
- readonly schedules: readonly AgentInfoScheduleEntry[];
- readonly skills: {
- readonly static: readonly AgentInfoSkillEntry[];
- readonly dynamic: readonly AgentInfoDynamicResolverEntry[];
- };
- readonly subagents: {
- readonly local: readonly AgentInfoSubagentEntry[];
- readonly total: number;
- };
- readonly tools: AgentInfoTools;
- readonly version: 2;
- readonly workflow: {
- readonly enabled: boolean;
- readonly toolName: string;
- };
- readonly workspace: {
- readonly resourceRoot: unknown;
- readonly rootEntries: readonly string[];
- };
+function toChatGptEndpoint(state: ChatGptAuthState | undefined) {
+ if (state === undefined) return undefined;
+ const endpoint = { state: state.kind };
+ if (state.kind === "ready" && state.accountLabel !== undefined) {
+ return { ...endpoint, accountLabel: state.accountLabel };
+ }
+ return endpoint;
}
+/** Projects v3 exclusively from the effective compiled graph. */
export function buildAgentInfoResponse(
- data: AgentInfoData,
+ data: AgentInfoManifestData,
input: {
readonly mode: AgentInfoResponse["mode"];
+ readonly gatewayCredentials: GatewayCredentialPresence;
+ readonly chatgptAuth?: ChatGptAuthState;
},
): AgentInfoResponse {
- const agent = data.agent;
- const config = agent.config;
- if (config === undefined) {
- throw new Error("Cannot inspect unresolved dynamic subagent resources as a root agent.");
+ const { manifest } = data;
+ const configSource = toModuleSource(manifest, manifest.config.source);
+ if (configSource.binding === undefined) {
+ throw new Error(`Compiled config source "${manifest.config.source.sourceId}" has no binding.`);
}
- const tools = buildToolInfo(agent, getRootDelegationToolNames(data.manifest));
+ const composition = collectCompositionDiagnostics(manifest);
+ const remoteAgents = collectRemoteAgents(manifest);
return {
agent: {
- agentRoot: agent.metadata.agentRoot,
- appRoot: agent.metadata.appRoot,
- configSource: config.source ? toSource(config.source) : undefined,
- description: config.description,
+ agentRoot: manifest.agentRoot,
+ appRoot: manifest.appRoot,
+ config: { ...configSource, binding: configSource.binding },
+ description: manifest.config.description,
model:
- config.dynamicModel === undefined
+ manifest.config.dynamicModel === undefined
? {
- contextWindowTokens: config.model.contextWindowTokens,
- id: config.model.id,
- providerOptions: config.model.providerOptions,
- reasoning: config.reasoning,
- source: config.model.source ? toSource(config.model.source) : undefined,
- routing: resolveStaticAgentModelRouting(data.manifest),
+ contextWindowTokens: manifest.config.model.contextWindowTokens,
+ endpoint: resolveModelEndpointStatus(
+ manifest.config.model.routing,
+ input.gatewayCredentials,
+ toChatGptEndpoint(input.chatgptAuth),
+ ),
+ id: manifest.config.model.id,
+ providerOptions: manifest.config.model.providerOptions,
+ reasoning: manifest.config.reasoning,
+ routing: manifest.config.model.routing,
+ source:
+ manifest.config.model.source === undefined
+ ? undefined
+ : toModuleSource(manifest, manifest.config.model.source),
}
: {
- reasoning: config.reasoning,
- routing: { kind: "dynamic" },
+ reasoning: manifest.config.reasoning,
+ routing: {
+ kind: "dynamic",
+ resolver: renderDynamicResolver(manifest, {
+ ...manifest.config.dynamicModel,
+ slug: "model",
+ }),
+ },
},
- name: config.name,
- outputSchema: config.outputSchema,
+ name: manifest.config.name,
+ nodeId: ROOT_COMPILED_AGENT_NODE_ID,
+ outputSchema: manifest.config.outputSchema,
},
- capabilities: {
- devRoutes: input.mode === "development",
+ capabilities: { devRoutes: input.mode === "development" },
+ channels: {
+ routes: manifest.channelRoutes.effective.map((route) => ({
+ ...toModuleSource(manifest, route),
+ adapterKind: route.adapterKind,
+ method: route.method,
+ name: route.name,
+ urlPath: route.urlPath,
+ })),
+ shadowed: [...manifest.channelRoutes.shadowed],
},
- channels: buildChannelInfo(agent),
- connections: agent.connections.map((connection) => ({
- ...toSource(connection),
+ composition,
+ connections: manifest.connections.map((connection) => ({
+ ...toModuleSource(manifest, connection),
connectionName: connection.connectionName,
description: connection.description,
- hasApproval: connection.approval !== undefined,
- hasAuthorization: connection.authorization !== undefined,
- hasHeaders: connection.headers !== undefined,
+ hasApproval: false,
+ hasAuthorization: connection.vercelConnect !== undefined,
+ hasHeaders: false,
protocol: connection.protocol,
- toolFilter: connection.tools,
url: connection.url,
})),
diagnostics: {
- discoveryErrors: agent.metadata.diagnosticsSummary.errors,
- discoveryWarnings: agent.metadata.diagnosticsSummary.warnings,
+ discoveryErrors: manifest.diagnosticsSummary.errors,
+ discoveryWarnings: manifest.diagnosticsSummary.warnings,
},
- hooks: agent.hooks.map((hook) => ({
- ...toSource(hook),
- eventNames: Object.keys(hook.events).sort(),
+ hooks: manifest.hooks.map((hook) => ({
+ ...toModuleSource(manifest, hook),
+ eventNames: [...hook.eventNames],
slug: hook.slug,
})),
instructions: {
- dynamic: agent.dynamicInstructionsResolvers.map((resolver) =>
- renderDynamicResolver(resolver, { origin: "authored" }),
+ dynamic: manifest.dynamicInstructions.map((resolver) =>
+ renderDynamicResolver(manifest, resolver),
),
- static: agent.instructions.map((instructions) => ({
- ...toSource(instructions),
- content: instructions.content,
- name: instructions.name,
- role: instructions.role,
+ static: manifest.instructions.map((definition) => ({
+ ...toOwnedSource(manifest, definition),
+ content: definition.content,
+ name: definition.name,
+ role: definition.role,
})),
},
+ instrumentation:
+ manifest.instrumentation === undefined
+ ? undefined
+ : toModuleSource(manifest, manifest.instrumentation),
+ kernelEffects: projectPreparedKernelEffects(manifest),
kind: "eve-agent-info",
mode: input.mode,
- sandbox: renderSandbox(agent.sandbox),
- schedules: data.schedules.map(renderSchedule),
+ remoteAgents: {
+ entries: remoteAgents,
+ total: remoteAgents.length,
+ },
+ sandbox: {
+ ...toModuleSource(manifest, manifest.sandbox),
+ backendKind: manifest.sandbox.backendName,
+ description: manifest.sandbox.description,
+ hasBootstrap: false,
+ hasOnSession: false,
+ revalidationKey: manifest.sandbox.revalidationKey,
+ sourceHash: manifest.sandbox.sourceHash,
+ },
+ schedules: manifest.schedules.map((schedule) => ({
+ ...toOwnedSource(manifest, schedule),
+ cron: schedule.cron,
+ hasRun: schedule.hasRun,
+ markdown: schedule.markdown,
+ name: schedule.name,
+ })),
skills: {
- static: agent.skills.map(renderSkill),
- dynamic: agent.dynamicSkillResolvers.map((resolver) =>
- renderDynamicResolver(resolver, { origin: "authored" }),
- ),
+ dynamic: manifest.dynamicSkills.map((resolver) => renderDynamicResolver(manifest, resolver)),
+ static: manifest.skills.map((skill) => ({
+ ...toOwnedSource(manifest, skill),
+ description: skill.description,
+ license: skill.license,
+ markdown: skill.markdown,
+ metadata: skill.metadata,
+ name: skill.name,
+ })),
},
subagents: {
- local: data.manifest.subagents.map(renderSubagent),
- total: data.manifest.subagents.length,
+ local: manifest.subagents.map((subagent) => {
+ const projected = {
+ ...toOwnedSource(manifest, subagent),
+ description: subagent.description,
+ entryPath: subagent.entryPath,
+ name: subagent.name,
+ nodeId: subagent.nodeId,
+ parentNodeId: subagent.parentNodeId,
+ rootPath: subagent.rootPath,
+ summary: summarizeNode(subagent.agent),
+ };
+ if (subagent.configResolver === undefined) return projected;
+ return {
+ ...projected,
+ configResolver: renderDynamicResolver(subagent.agent, {
+ ...subagent.configResolver,
+ slug: "config",
+ }),
+ };
+ }),
+ total: manifest.subagents.length,
},
- tools,
- version: 2,
- workflow: {
- enabled: agent.workflowTool !== undefined,
- toolName: WORKFLOW_TOOL_NAME,
+ tools: {
+ dynamic: manifest.dynamicTools.map((resolver) => renderDynamicResolver(manifest, resolver)),
+ static: manifest.tools.map((tool) => ({
+ ...toModuleSource(manifest, tool),
+ description: tool.description,
+ hasAuth: false,
+ hasExecute: tool.hasExecute,
+ hasModelOutputProjection: tool.hasModelOutputProjection,
+ hasOutputSchema: tool.outputSchema !== undefined,
+ inputSchema: tool.inputSchema,
+ name: tool.name,
+ outputSchema: tool.outputSchema,
+ requiresApproval: tool.requiresApproval,
+ })),
},
+ version: 3,
+ workflow:
+ manifest.workflowTool === undefined
+ ? { enabled: false, toolName: WORKFLOW_TOOL_NAME }
+ : {
+ enabled: true,
+ source: toModuleSource(manifest, manifest.workflowTool),
+ toolName: WORKFLOW_TOOL_NAME,
+ },
workspace: {
- resourceRoot: agent.workspaceResourceRoot,
- rootEntries: [...agent.workspaceSpec.rootEntries],
+ resourceRoot: manifest.workspaceResourceRoot,
+ rootEntries: [...manifest.workspaceResourceRoot.rootEntries],
},
};
}
-function resolveStaticAgentModelRouting(manifest: CompiledAgentManifest): ModelRouting {
- if (manifest.config.model === undefined) {
- throw new Error("Resolved static agent config does not match its compiled manifest.");
- }
- return manifest.config.model.routing;
-}
-
-function buildChannelInfo(agent: ResolvedAgent): AgentInfoChannels {
- const authoredChannelNames = new Set(agent.channels.map((channel) => channel.name));
- const disabledFrameworkChannels = new Set(agent.disabledFrameworkChannels);
- const allFrameworkChannelNames = getAllFrameworkChannelNames();
- const frameworkChannelDefinitions = getFrameworkChannelDefinitions();
- const activeFrameworkChannels = frameworkChannelDefinitions.filter(
- (channel) =>
- !authoredChannelNames.has(channel.name) && !disabledFrameworkChannels.has(channel.name),
- );
- const authored = agent.channels.map((channel) =>
- renderChannel(channel, {
- origin: "authored",
- }),
- );
- const framework = frameworkChannelDefinitions.map((channel) => {
- const replacedByAuthoredChannel = authoredChannelNames.has(channel.name);
- const disabledByAuthor = disabledFrameworkChannels.has(channel.name);
- const status: AgentInfoFrameworkChannelEntry["status"] = disabledByAuthor
- ? "disabled"
- : replacedByAuthoredChannel
- ? "replaced"
- : "active";
-
- return {
- ...renderChannel(channel, {
- origin: "framework",
- }),
- disabledByAuthor,
- replacedByAuthoredChannel,
- status,
- };
- });
-
- return {
- authored,
- available: [
- ...activeFrameworkChannels.map((channel) =>
- renderChannel(channel, {
- origin: "framework",
- }),
- ),
- ...authored,
- ],
- disabledFramework: [...agent.disabledFrameworkChannels],
- framework: framework.filter((channel) => allFrameworkChannelNames.has(channel.name)),
- };
-}
-
-function buildToolInfo(
- agent: ResolvedAgent,
- delegationToolNames: ReadonlySet<string>,
-): AgentInfoTools {
- const authoredToolNames = new Set(agent.tools.map((tool) => tool.name));
- const disabledFrameworkTools = new Set(agent.disabledFrameworkTools);
- const allFrameworkToolNames = getAllFrameworkToolNames();
- const dynamicFrameworkResolvers = getFrameworkDynamicToolResolvers();
- const authored = agent.tools.map((tool) =>
- renderTool(tool, {
- origin: "authored",
- replacesFrameworkTool: allFrameworkToolNames.has(tool.name),
- }),
- );
- const frameworkInfo = buildFrameworkToolInfo({
- authoredToolNames,
- delegationToolNames,
- disabledFrameworkToolNames: disabledFrameworkTools,
- });
-
- return {
- available: [...frameworkInfo.available, ...authored],
- authored,
- disabledFramework: [...agent.disabledFrameworkTools],
- dynamic: [
- ...dynamicFrameworkResolvers.map((resolver) =>
- renderDynamicResolver(resolver, { origin: "framework" }),
- ),
- ...agent.dynamicToolResolvers.map((resolver) =>
- renderDynamicResolver(resolver, { origin: "authored" }),
- ),
- ],
- framework: frameworkInfo.framework,
- reserved: [WORKFLOW_TOOL_NAME, LOAD_SKILL_TOOL_NAME],
- };
-}
-
-export function buildFrameworkToolInfo(input: {
- readonly authoredToolNames: ReadonlySet<string>;
- readonly delegationToolNames: ReadonlySet<string>;
- readonly disabledFrameworkToolNames: ReadonlySet<string>;
-}): Pick<AgentInfoTools, "available" | "framework"> {
- const occupiedToolNames = new Set([...input.authoredToolNames, ...input.delegationToolNames]);
- const available: AgentInfoToolEntry[] = [];
- const framework: AgentInfoFrameworkToolEntry[] = [];
- const optInFrameworkToolNames = getOptInFrameworkToolNames();
-
- for (const definition of getAllFrameworkToolDefinitions()) {
- const disabledByAuthor = input.disabledFrameworkToolNames.has(definition.name);
- const replacedByAuthoredTool = input.authoredToolNames.has(definition.name);
- const status: AgentInfoFrameworkToolEntry["status"] = disabledByAuthor
- ? "disabled"
- : occupiedToolNames.has(definition.name)
- ? "replaced"
- : optInFrameworkToolNames.has(definition.name)
- ? "opt-in"
- : "active";
- const rendered = renderTool(definition, {
- origin: "framework",
- replacesFrameworkTool: false,
- });
-
- if (status === "active") {
- available.push(rendered);
- }
-
- framework.push({
- ...rendered,
- disabledByAuthor,
- replacedByAuthoredTool,
- status,
- });
+function toModuleSource(
+ node: CompiledAgentNodeManifest | CompiledAgentResources,
+ source: {
+ readonly exportName?: string;
+ readonly logicalPath: string;
+ readonly sourceId: string;
+ readonly sourceKind: string;
+ },
+): AgentInfoSource {
+ const binding = node.bindings[source.sourceId];
+ if (binding === undefined) {
+ throw new Error(`Compiled source "${source.sourceId}" has no binding.`);
}
-
- return { available, framework };
+ return sourceProjection(source, binding.owner, binding);
}
-export function getRootDelegationToolNames(manifest: CompiledAgentManifest): ReadonlySet<string> {
- const rootChildNodeIds = new Set(
- manifest.subagentEdges
- .filter((edge) => edge.parentNodeId === ROOT_COMPILED_AGENT_NODE_ID)
- .map((edge) => edge.childNodeId),
- );
-
- return new Set([
- ...manifest.subagents
- .filter((subagent) => rootChildNodeIds.has(subagent.nodeId))
- .map((subagent) => subagent.name),
- ...manifest.remoteAgents.map((remoteAgent) => remoteAgent.name),
- ]);
-}
-
-export function renderChannel(
- channel: ResolvedChannelDefinition,
- input: {
- readonly origin: "authored" | "framework";
+function toOwnedSource(
+ node: CompiledAgentNodeManifest | CompiledAgentResources,
+ source: {
+ readonly exportName?: string;
+ readonly logicalPath: string;
+ readonly owner?: AgentSourceOwner;
+ readonly sourceId: string;
+ readonly sourceKind: string;
},
-): AgentInfoChannelEntry {
- return {
- ...toSource(channel),
- adapterKind: channel.adapter?.kind,
- method: channel.method,
- name: channel.name,
- origin: input.origin,
- urlPath: channel.urlPath,
- };
+): AgentInfoSource {
+ const binding = node.bindings[source.sourceId];
+ const owner = binding?.owner ?? source.owner;
+ if (owner === undefined) {
+ throw new Error(`Compiled source "${source.sourceId}" has no owner.`);
+ }
+ return sourceProjection(source, owner, binding);
}
-export function renderTool(
- tool: ResolvedToolDefinition,
- input: {
- readonly origin: "authored" | "framework";
- readonly replacesFrameworkTool: boolean;
+function sourceProjection(
+ source: {
+ readonly exportName?: string;
+ readonly logicalPath: string;
+ readonly sourceId: string;
+ readonly sourceKind: string;
},
-): AgentInfoToolEntry {
- const inputSchema = serializeInputSchema(tool.inputSchema);
- const outputSchema = serializeOutputSchema(tool.outputSchema);
-
- return {
- ...toSource(tool),
- description: tool.description,
- hasAuth: false,
- hasExecute: tool.execute !== undefined,
- hasModelOutputProjection: tool.toModelOutput !== undefined,
- hasOutputSchema: outputSchema !== undefined,
- inputSchema,
- name: tool.name,
- origin: input.origin,
- outputSchema,
- replacesFrameworkTool: input.replacesFrameworkTool,
- requiresApproval: tool.approval !== undefined,
+ owner: AgentSourceOwner,
+ binding?: CompiledModuleBinding,
+): AgentInfoSource {
+ const projected = {
+ logicalPath: source.logicalPath,
+ owner,
+ sourceId: source.sourceId,
+ sourceKind: toAgentInfoSourceKind(source.sourceKind),
};
+ if (binding !== undefined && source.exportName !== undefined) {
+ return { ...projected, binding, exportName: source.exportName };
+ }
+ if (binding !== undefined) return { ...projected, binding };
+ if (source.exportName !== undefined) return { ...projected, exportName: source.exportName };
+ return projected;
+}
+
+function toAgentInfoSourceKind(sourceKind: string): AgentInfoSource["sourceKind"] {
+ switch (sourceKind) {
+ case "markdown":
+ case "module":
+ case "skill-package":
+ return sourceKind;
+ default:
+ throw new Error(`Unsupported compiled source kind "${sourceKind}".`);
+ }
}
-function renderSkill(skill: ResolvedSkillDefinition): AgentInfoSkillEntry {
+function renderDynamicResolver(
+ node: CompiledAgentNodeManifest | CompiledAgentResources,
+ resolver:
+ | CompiledDynamicInstructionsDefinition
+ | CompiledDynamicSkillDefinition
+ | CompiledDynamicToolDefinition
+ | {
+ readonly eventNames: readonly string[];
+ readonly exportName?: string;
+ readonly logicalPath: string;
+ readonly slug: string;
+ readonly sourceId: string;
+ readonly sourceKind: "module";
+ },
+) {
return {
- ...toSource(skill),
- description: skill.description,
- license: skill.license,
- markdown: skill.markdown,
- metadata: skill.metadata,
- name: skill.name,
+ ...toModuleSource(node, resolver),
+ eventNames: [...resolver.eventNames],
+ slug: resolver.slug,
};
}
-export function renderSchedule(schedule: ResolvedScheduleDefinition): AgentInfoScheduleEntry {
+function summarizeNode(node: CompiledAgentNodeManifest | CompiledAgentResources) {
return {
- ...toSource(schedule),
- cron: schedule.cron,
- hasRun: schedule.hasRun,
- markdown: schedule.markdown,
- name: schedule.name,
+ channels: node.channelRoutes.effective.length,
+ connections: node.connections.length,
+ hooks: node.hooks.length,
+ instructions: node.instructions.length,
+ schedules: node.schedules.length,
+ skills: node.skills.length,
+ tools: node.tools.length,
};
}
-function renderSandbox(sandbox: ResolvedSandboxDefinition | null): AgentInfoSandboxEntry | null {
- if (sandbox === null) {
- return null;
- }
-
- return {
- ...toSource(sandbox),
- backendKind: resolveBackendKind(sandbox.backend),
- description: sandbox.description,
- hasBootstrap: sandbox.bootstrap !== undefined,
- hasOnSession: sandbox.onSession !== undefined,
- revalidationKey: sandbox.revalidationKey,
- sourceHash: sandbox.sourceHash,
- };
+function collectRemoteAgents(manifest: CompiledAgentManifest) {
+ return [manifest, ...manifest.subagents.map((subagent) => subagent.agent)].flatMap((node) =>
+ node.remoteAgents.map((remote) => ({
+ ...sourceProjection(remote, remote.owner, remote.binding),
+ description: remote.description,
+ name: remote.name,
+ nodeId: remote.nodeId,
+ parentNodeId: remote.parentNodeId,
+ url: remote.url,
+ })),
+ );
}
-export function renderSubagent(subagent: CompiledSubagentNode): AgentInfoSubagentEntry {
+function collectCompositionDiagnostics(manifest: CompiledAgentManifest) {
+ const entries = [manifest, ...manifest.subagents.map((subagent) => subagent.agent)].flatMap(
+ (node) => node.sourceComposition.entries,
+ );
+ const projected = entries.map((entry) => {
+ const diagnostic = {
+ kind: entry.kind,
+ logicalPath: entry.source.logicalPath,
+ owner: entry.source.owner,
+ sourceId: entry.source.sourceId,
+ };
+ if (entry.kind === "shadowed") {
+ return { ...diagnostic, winnerSourceId: entry.winnerSourceId };
+ }
+ return diagnostic;
+ });
return {
- ...toSource(subagent),
- description: subagent.description,
- entryPath: subagent.entryPath,
- name: subagent.name,
- nodeId: subagent.nodeId,
- rootPath: subagent.rootPath,
- summary: {
- channels: subagent.agent.channels.length,
- connections: subagent.agent.connections.length,
- hooks: subagent.agent.hooks.length,
- instructions: subagent.agent.instructions.length > 0,
- schedules: subagent.agent.schedules.length,
- skills: subagent.agent.skills.length,
- tools: subagent.agent.tools.length,
- },
+ disabled: projected.filter((entry) => entry.kind === "disabled"),
+ shadowed: projected.filter((entry) => entry.kind === "shadowed"),
};
}
-export function renderDynamicResolver(
- resolver: {
- readonly eventNames: readonly string[];
- readonly exportName?: string;
- readonly logicalPath: string;
- readonly slug: string;
- readonly sourceId: string;
- readonly sourceKind: string;
+const KERNEL_EFFECT_BY_SLOT = {
+ "tools/agent": { action: "subagent-call", audience: ["root-session"], kind: "dispatch" },
+ "tools/ask_question": {
+ audience: ["requires-request-input"],
+ kind: "request-input",
},
- input: {
- readonly origin: "authored" | "framework";
+ "tools/task_cancel": { action: "task-cancel", audience: ["root-session"], kind: "dispatch" },
+ "tools/task_update": {
+ action: "task-update",
+ audience: ["delegated-task-child"],
+ kind: "dispatch",
},
-): AgentInfoDynamicResolverEntry {
- return {
- ...toSource(resolver),
- eventNames: [...resolver.eventNames],
- origin: input.origin,
- slug: resolver.slug,
- };
-}
-
-export function toSource(source: {
- readonly exportName?: string;
- readonly logicalPath: string;
- readonly sourceId?: string;
- readonly sourceKind: string;
-}): AgentInfoSource {
- return {
- exportName: source.exportName,
- logicalPath: source.logicalPath,
- sourceId: source.sourceId,
- sourceKind: source.sourceKind,
- };
-}
-
-function resolveBackendKind(backend: unknown): string | undefined {
- if (backend === null || typeof backend !== "object") {
- return undefined;
- }
-
- const kind = (backend as { readonly kind?: unknown }).kind;
- return typeof kind === "string" ? kind : undefined;
+ "tools/web_search": { audience: [], kind: "provider-tool" },
+} as const;
+
+function projectPreparedKernelEffects(manifest: CompiledAgentManifest) {
+ return manifest.tools.flatMap((tool) => {
+ const binding = manifest.bindings[tool.sourceId];
+ const slot = tool.logicalPath.replace(/\.(?:[cm]?[jt]sx?)$/, "");
+ const effect = KERNEL_EFFECT_BY_SLOT[slot as keyof typeof KERNEL_EFFECT_BY_SLOT];
+ const isAuthoredWebSearch =
+ slot === "tools/web_search" && manifest.webSearchProvider !== undefined;
+ if (binding?.owner.kind !== "framework" && !isAuthoredWebSearch) return [];
+ return effect === undefined ? [] : [{ ...effect, sourceId: tool.sourceId }];
+ });
}
diff --git a/packages/eve/src/internal/nitro/routes/agent-info/load-agent-info-data.ts b/packages/eve/src/internal/nitro/routes/agent-info/load-agent-info-data.ts
index 6ccabcb9b..ce945af9d 100644
--- a/packages/eve/src/internal/nitro/routes/agent-info/load-agent-info-data.ts
+++ b/packages/eve/src/internal/nitro/routes/agent-info/load-agent-info-data.ts
@@ -5,41 +5,18 @@ import {
resolveNitroCompiledArtifactsSource,
} from "#internal/nitro/routes/runtime-artifacts.js";
import { loadCompiledManifest } from "#runtime/loaders/manifest.js";
-import { loadCompiledModuleMap } from "#runtime/loaders/module-map.js";
-import { resolveAgent } from "#runtime/resolve-agent.js";
import { resolveSchedules } from "#runtime/schedules/resolve-schedule.js";
-import type {
- ResolvedAgent,
- ResolvedSandboxDefinition,
- ResolvedScheduleDefinition,
- ResolvedSkillDefinition,
- ResolvedInstructionsDefinition,
-} from "#runtime/types.js";
+import type { ResolvedScheduleDefinition } from "#runtime/types.js";
/**
* Runtime data needed to build the package-owned `GET /eve/v1/info`
* inspection JSON.
*/
-export interface AgentInfoData {
- readonly agent: ResolvedAgent;
- readonly manifest: CompiledAgentManifest;
- readonly schedules: readonly ResolvedScheduleDefinition[];
-}
-
export interface AgentInfoManifestData {
readonly manifest: CompiledAgentManifest;
readonly schedules: readonly ResolvedScheduleDefinition[];
}
-/**
- * Loads the resolved runtime data projected by `GET /eve/v1/info`.
- */
-export async function loadAgentInfoData(input: {
- readonly compiledArtifactsSource: RuntimeCompiledArtifactsSource;
-}): Promise<AgentInfoData> {
- return await loadAgentInfoDataFromArtifacts(input.compiledArtifactsSource);
-}
-
/**
* Loads manifest-only runtime data for inspection surfaces that must not
* execute or import authored modules.
@@ -70,36 +47,4 @@ export function resolveAgentInfoCompiledArtifactsSource(
return resolveNitroCompiledArtifactsSource(input);
}
-async function loadAgentInfoDataFromArtifacts(
- compiledArtifactsSource: RuntimeCompiledArtifactsSource,
-): Promise<AgentInfoData> {
- const [manifest, moduleMap] = await Promise.all([
- loadCompiledManifest({
- compiledArtifactsSource,
- }),
- loadCompiledModuleMap({
- compiledArtifactsSource,
- }),
- ]);
- const schedules = await resolveSchedules({
- manifest,
- });
-
- return {
- agent: await resolveAgent({
- manifest,
- moduleMap,
- }),
- manifest,
- schedules,
- };
-}
-
-export type {
- CompiledAgentManifest,
- CompiledSubagentNode,
- ResolvedSandboxDefinition,
- ResolvedScheduleDefinition,
- ResolvedSkillDefinition,
- ResolvedInstructionsDefinition,
-};
+export type { CompiledAgentManifest, CompiledSubagentNode, ResolvedScheduleDefinition };
diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts
index b5bf4bc51..afb6ce16c 100644
--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts
+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts
@@ -27,7 +27,7 @@ import {
} from "#harness/instrumentation/config.js";
import type { Runtime } from "#channel/types.js";
import { readVercelProjectLink } from "#internal/vercel/project-link.js";
-import { resolveVercelOidcCurrentProject } from "#runtime/governance/auth/vercel-oidc-project.js";
+import { resolveVercelOidcCurrentProject } from "#channel/auth/vercel-oidc-project.js";
import type { ResolvedChannelDefinition } from "#runtime/types.js";
import {
dispatchChannelRequest,
@@ -113,6 +113,7 @@ describe("dispatchChannelRequest", () => {
.mockResolvedValueOnce({ orgId: "team_1", projectId: "prj_second" });
const currentProjects: Array<Awaited<ReturnType<typeof resolveVercelOidcCurrentProject>>> = [];
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
+ agentName: "test-agent",
channels: [
{
handler: async (request) => {
@@ -155,6 +156,7 @@ describe("dispatchChannelRequest", () => {
const waitUntil = vi.fn<(task: Promise<unknown>) => void>();
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
+ agentName: "test-agent",
channels: [
{
fetch: async (_request: Request, ctx: { waitUntil: (t: Promise<unknown>) => void }) => {
@@ -233,6 +235,7 @@ describe("dispatchChannelRequest", () => {
let capturedArgs: RouteHandlerArgs | undefined;
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
+ agentName: "test-agent",
channels: [
{
handler: async (_req, args) => {
@@ -297,6 +300,7 @@ describe("dispatchChannelRequest", () => {
});
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
+ agentName: "test-agent",
channels: [
{
handler: async (_req, args) => {
@@ -342,6 +346,7 @@ describe("dispatchChannelRequest", () => {
});
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
+ agentName: "test-agent",
channels: [
{
handler: async (_req, args) =>
@@ -386,6 +391,7 @@ describe("dispatchChannelRequest", () => {
});
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
+ agentName: "test-agent",
channels: [
{
handler: async (_req, args) =>
@@ -427,6 +433,7 @@ describe("dispatchChannelRequest", () => {
});
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
+ agentName: "test-agent",
channels: [
{
handler: async (_req, args) => {
@@ -465,6 +472,7 @@ describe("dispatchChannelRequest", () => {
let capturedArgs: RouteHandlerArgs | undefined;
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
+ agentName: "test-agent",
channels: [
{
fetch: async () => new Response("not used"),
@@ -509,6 +517,7 @@ describe("dispatchChannelRequest", () => {
it("rejects websocket upgrades when no websocket channel matches", async () => {
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
+ agentName: "test-agent",
channels: [],
runtime,
});
@@ -532,6 +541,7 @@ describe("dispatchChannelRequest", () => {
it("logs and returns a 500 with an errorId when a handler throws", async () => {
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
+ agentName: "test-agent",
channels: [
{
fetch: async () => {
@@ -575,6 +585,7 @@ describe("dispatchChannelRequest", () => {
});
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
+ agentName: "test-agent",
channels: [
{
fetch: async (_req, ctx: { waitUntil: (t: Promise<unknown>) => void }) => {
@@ -614,6 +625,7 @@ describe("dispatchChannelRequest", () => {
const waitUntil = vi.fn<(task: Promise<unknown>) => void>();
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
+ agentName: "test-agent",
channels: [
{
fetch: async () => new Response("ok"),
@@ -725,6 +737,7 @@ describe("dispatchChannelRequest tracing", () => {
it("emits one SERVER span named for the route with method, channel, and status attributes", async () => {
let spansDuringHandler = -1;
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
+ agentName: "test-agent",
channels: [
slackChannel(
async () => {
@@ -775,6 +788,7 @@ describe("dispatchChannelRequest tracing", () => {
setChannelInstrumentationKind(definition, "channel:support");
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
+ agentName: "test-agent",
channels: [
slackChannel(async () => new Response("ok"), {
adapter: { kind: "http" },
@@ -792,6 +806,7 @@ describe("dispatchChannelRequest tracing", () => {
it("makes a span created inside the handler a child of the request span", async () => {
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
+ agentName: "test-agent",
channels: [
slackChannel(async () => {
// Model hook.resume: a nested span opened under the active context.
@@ -821,6 +836,7 @@ describe("dispatchChannelRequest tracing", () => {
.mockResolvedValue({ sessionId: "session-1", status: "accepted" }),
});
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
+ agentName: "test-agent",
channels: [
slackChannel(async () => new Response("unused"), {
adapter: { kind: "channel:slack" },
@@ -866,6 +882,7 @@ describe("dispatchChannelRequest tracing", () => {
const traceId = "0af7651916cd43dd8448eb211c80319c";
const parentId = "b7ad6b7169203331";
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
+ agentName: "test-agent",
channels: [slackChannel(async () => new Response("ok"))],
runtime,
});
@@ -887,6 +904,7 @@ describe("dispatchChannelRequest tracing", () => {
it("marks the span an error and records the exception once for a handler that throws", async () => {
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
+ agentName: "test-agent",
channels: [
slackChannel(async () => {
throw new Error("handler exploded");
@@ -931,7 +949,11 @@ describe("dispatchChannelRequest tracing", () => {
});
it("still emits a 404 span with the route but no channel identity when nothing matches", async () => {
- mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({ channels: [], runtime });
+ mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
+ agentName: "test-agent",
+ channels: [],
+ runtime,
+ });
const response = await dispatchChannelRequest(
createEvent({ waitUntil: vi.fn() }),
@@ -956,6 +978,7 @@ describe("dispatchChannelRequest tracing", () => {
const bodySecret = "body_payload_secret";
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
+ agentName: "test-agent",
channels: [
{
fetch: async () => new Response("ok"),
@@ -1019,6 +1042,7 @@ describe("dispatchChannelRequest without an OTel provider", () => {
it("handles the request identically and records no spans", async () => {
const waitUntil = vi.fn<(task: Promise<unknown>) => void>();
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
+ agentName: "test-agent",
channels: [slackChannel(async () => new Response("ok"))],
runtime,
});
@@ -1063,6 +1087,7 @@ describe("dispatchChannelRequest with request tracing not enabled", () => {
async function expectNoSpan(): Promise<void> {
const waitUntil = vi.fn<(task: Promise<unknown>) => void>();
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
+ agentName: "test-agent",
channels: [slackChannel(async () => new Response("ok"))],
runtime,
});
diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.ts
index 72251b0ba..d51fab0c5 100644
--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts
+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.ts
@@ -12,6 +12,7 @@ import { readTrustedDevelopmentClientAddress } from "#internal/nitro/dev-client-
import { DEVELOPMENT_WORKFLOW_SECRET_ENV } from "#internal/workflow/development-world-protocol.js";
import {
attachAgentInfoRouteResponse,
+ attachHomeRouteMetadata,
attachRouteChannelName,
attachRemoteAgentStreamHeadersResolver,
attachRouteSessionCreator,
@@ -20,7 +21,7 @@ import type { NitroArtifactsConfig } from "#internal/nitro/routes/runtime-artifa
import { traceChannelRequest } from "#internal/nitro/routes/channel-request-instrumentation.js";
import { resolveNitroChannelRuntimeBundle } from "#internal/nitro/routes/runtime-stack.js";
import { readVercelProjectLink } from "#internal/vercel/project-link.js";
-import { withVercelOidcProjectResolver } from "#runtime/governance/auth/vercel-oidc-project.js";
+import { withVercelOidcProjectResolver } from "#channel/auth/vercel-oidc-project.js";
const log = createLogger("channel.dispatch");
@@ -250,22 +251,25 @@ function buildRouteArgs(
const to = createCrossChannelToFn(bundle.runtime, toCrossChannelTargets(bundle.channels));
const args = attachRouteSessionCreator(
- attachRouteChannelName(
- attachAgentInfoRouteResponse(
- {
- attachSession,
- ...channelOperations,
- params,
- requestIp,
- to,
- waitUntil,
- },
- async () => {
- const { handleAgentInfoRequest } = await import("#internal/nitro/routes/info.js");
- return await handleAgentInfoRequest(config);
- },
+ attachHomeRouteMetadata(
+ attachRouteChannelName(
+ attachAgentInfoRouteResponse(
+ {
+ attachSession,
+ ...channelOperations,
+ params,
+ requestIp,
+ to,
+ waitUntil,
+ },
+ async () => {
+ const { handleAgentInfoRequest } = await import("#internal/nitro/routes/info.js");
+ return await handleAgentInfoRequest(config);
+ },
+ ),
+ channelName,
),
- channelName,
+ { agentName: bundle.agentName },
),
async (input) =>
await bundle.runtime.createSession({
diff --git a/packages/eve/src/internal/nitro/routes/channel-route-context.ts b/packages/eve/src/internal/nitro/routes/channel-route-context.ts
index d3abad60a..728e8278b 100644
--- a/packages/eve/src/internal/nitro/routes/channel-route-context.ts
+++ b/packages/eve/src/internal/nitro/routes/channel-route-context.ts
@@ -2,6 +2,9 @@ import type { RouteHandlerArgs } from "#channel/routes.js";
import type { RunHandle, RunInput } from "#channel/types.js";
type AgentInfoRouteResponse = () => Promise<Response>;
+export interface HomeRouteMetadata {
+ readonly agentName: string;
+}
/**
* Creates one session from a route handler. `continuationToken` is
* channel-local (the dispatcher prepends the channel name), so ownership
@@ -18,12 +21,14 @@ export type RemoteAgentStreamHeadersResolver = (input: {
}) => Promise<Record<string, string>>;
const agentInfoRouteResponseKey = "__eveAgentInfoRouteResponse";
+const homeRouteMetadataKey = "__eveHomeRouteMetadata";
const routeChannelNameKey = "__eveRouteChannelName";
const remoteAgentStreamHeadersResolverKey = "__eveRemoteAgentStreamHeadersResolver";
const routeSessionCreatorKey = "__eveRouteSessionCreator";
type InternalRouteArgs = RouteHandlerArgs & {
[agentInfoRouteResponseKey]?: AgentInfoRouteResponse;
+ [homeRouteMetadataKey]?: HomeRouteMetadata;
[routeChannelNameKey]?: string;
[remoteAgentStreamHeadersResolverKey]?: RemoteAgentStreamHeadersResolver;
[routeSessionCreatorKey]?: RouteSessionCreator;
@@ -59,6 +64,20 @@ export function readAgentInfoRouteResponse(
return routeArgs[agentInfoRouteResponseKey];
}
+export function attachHomeRouteMetadata<TArgs extends RouteHandlerArgs>(
+ args: TArgs,
+ metadata: HomeRouteMetadata,
+): TArgs {
+ const routeArgs: InternalRouteArgs = args;
+ routeArgs[homeRouteMetadataKey] = metadata;
+ return args;
+}
+
+export function readHomeRouteMetadata(args: RouteHandlerArgs): HomeRouteMetadata | undefined {
+ const routeArgs: InternalRouteArgs = args;
+ return routeArgs[homeRouteMetadataKey];
+}
+
export function attachRouteSessionCreator<TArgs extends RouteHandlerArgs>(
args: TArgs,
createSession: RouteSessionCreator,
diff --git a/packages/eve/src/internal/nitro/routes/health.ts b/packages/eve/src/internal/nitro/routes/health.ts
deleted file mode 100644
index 787119d2e..000000000
--- a/packages/eve/src/internal/nitro/routes/health.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import type { H3Event } from "nitro";
-import { workflowEntryReference } from "#execution/workflow-runtime.js";
-
-/**
- * Nitro route for eve's health endpoint.
- *
- * The health endpoint is intentionally always-public so platform load
- * balancers and uptime monitors can probe it without credentials.
- * Channels that need authenticated health probes should author their own
- * channel file with the verifier helpers from
- * `eve/channels/auth`.
- */
-export default async (_event: H3Event<{ body: unknown }>): Promise<Response> => {
- return Response.json({
- ok: true,
- status: "ready",
- workflowId: workflowEntryReference.workflowId,
- });
-};
diff --git a/packages/eve/src/internal/nitro/routes/index.ts b/packages/eve/src/internal/nitro/routes/index.ts
index 06be285da..90af70e38 100644
--- a/packages/eve/src/internal/nitro/routes/index.ts
+++ b/packages/eve/src/internal/nitro/routes/index.ts
@@ -1,5 +1,3 @@
-import type { H3Event } from "nitro";
-
/**
* Public docs URL surfaced from the barebones home page. Kept in source
* so the deployment output is a fully static, build-time-baked HTML
@@ -275,20 +273,3 @@ export function buildHomePageResponse(
},
});
}
-
-/**
- * Nitro route handler for `GET /`. Adapts the Nitro event shape into
- * {@link buildHomePageResponse}.
- */
-export function handleHomePageRequest(
- input: {
- readonly agentName: string;
- },
- request: Request,
-): Response {
- return buildHomePageResponse(input, request);
-}
-
-export default function handleStaticHomePageRequest(event: H3Event): Response {
- return buildHomePageResponse({ agentName: "eve" }, event.req);
-}
diff --git a/packages/eve/src/internal/nitro/routes/info.test.ts b/packages/eve/src/internal/nitro/routes/info.test.ts
index cf81fb7d8..eb5eca4bb 100644
--- a/packages/eve/src/internal/nitro/routes/info.test.ts
+++ b/packages/eve/src/internal/nitro/routes/info.test.ts
@@ -1,7 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
- buildAgentInfoResponseFromManifest: vi.fn(() => ({ kind: "eve-agent-info", version: 2 })),
+ buildAgentInfoResponse: vi.fn(() => ({ kind: "eve-agent-info", version: 3 })),
getVercelOidcToken: vi.fn(),
refreshChatGptState: vi.fn(async () => ({ kind: "ready" as const })),
loadAgentInfoManifestData: vi.fn(async (): Promise<unknown> => ({
@@ -28,8 +28,8 @@ vi.mock("#public/models/openai/chatgpt/token-broker.js", () => ({
getDefaultCodexTokenBroker: () => ({ refreshState: mocks.refreshChatGptState }),
}));
-vi.mock("#internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.js", () => ({
- buildAgentInfoResponseFromManifest: mocks.buildAgentInfoResponseFromManifest,
+vi.mock("#internal/nitro/routes/agent-info/build-agent-info-response.js", () => ({
+ buildAgentInfoResponse: mocks.buildAgentInfoResponse,
}));
vi.mock("#internal/nitro/routes/agent-info/load-agent-info-data.js", () => ({
@@ -76,7 +76,7 @@ describe("handleAgentInfoRequest", () => {
beforeEach(() => {
vi.stubEnv("AI_GATEWAY_API_KEY", "");
vi.stubEnv("VERCEL_OIDC_TOKEN", "");
- mocks.buildAgentInfoResponseFromManifest.mockClear();
+ mocks.buildAgentInfoResponse.mockClear();
mocks.getVercelOidcToken.mockReset();
mocks.getVercelOidcToken.mockRejectedValue(new Error("not linked"));
mocks.refreshChatGptState.mockClear();
@@ -100,7 +100,7 @@ describe("handleAgentInfoRequest", () => {
kind: "disk",
},
});
- expect(mocks.buildAgentInfoResponseFromManifest).toHaveBeenCalledWith(GATEWAY_MANIFEST_DATA, {
+ expect(mocks.buildAgentInfoResponse).toHaveBeenCalledWith(GATEWAY_MANIFEST_DATA, {
mode: "development",
gatewayCredentials: { apiKey: false, oidc: false },
});
@@ -113,7 +113,7 @@ describe("handleAgentInfoRequest", () => {
const response = await requestAgentInfo();
expect(response.status).toBe(200);
- expect(mocks.buildAgentInfoResponseFromManifest).toHaveBeenCalledWith(GATEWAY_MANIFEST_DATA, {
+ expect(mocks.buildAgentInfoResponse).toHaveBeenCalledWith(GATEWAY_MANIFEST_DATA, {
mode: "development",
gatewayCredentials: { apiKey: false, oidc: true },
});
@@ -126,7 +126,7 @@ describe("handleAgentInfoRequest", () => {
const response = await requestAgentInfo();
expect(response.status).toBe(200);
- expect(mocks.buildAgentInfoResponseFromManifest).toHaveBeenCalledWith(GATEWAY_MANIFEST_DATA, {
+ expect(mocks.buildAgentInfoResponse).toHaveBeenCalledWith(GATEWAY_MANIFEST_DATA, {
mode: "development",
gatewayCredentials: { apiKey: true, oidc: false },
});
@@ -140,7 +140,7 @@ describe("handleAgentInfoRequest", () => {
expect(response.status).toBe(200);
expect(mocks.refreshChatGptState).toHaveBeenCalledOnce();
- expect(mocks.buildAgentInfoResponseFromManifest).toHaveBeenCalledWith(CHATGPT_MANIFEST_DATA, {
+ expect(mocks.buildAgentInfoResponse).toHaveBeenCalledWith(CHATGPT_MANIFEST_DATA, {
mode: "development",
gatewayCredentials: { apiKey: false, oidc: false },
chatgptAuth: { kind: "ready" },
diff --git a/packages/eve/src/internal/nitro/routes/info.ts b/packages/eve/src/internal/nitro/routes/info.ts
index 868e3f90f..ccf8f57bf 100644
--- a/packages/eve/src/internal/nitro/routes/info.ts
+++ b/packages/eve/src/internal/nitro/routes/info.ts
@@ -1,6 +1,6 @@
import { getVercelOidcToken } from "#compiled/@vercel/oidc/index.js";
import { hasEnvValue } from "#internal/resolve-model-endpoint-status.js";
-import { buildAgentInfoResponseFromManifest } from "#internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.js";
+import { buildAgentInfoResponse } from "#internal/nitro/routes/agent-info/build-agent-info-response.js";
import {
loadAgentInfoManifestData,
resolveAgentInfoCompiledArtifactsSource,
@@ -20,7 +20,7 @@ async function createAgentInfoPayload(input: NitroArtifactsConfig) {
data.manifest.config.dynamicModel === undefined
? data.manifest.config.model.routing
: undefined;
- return buildAgentInfoResponseFromManifest(data, {
+ return buildAgentInfoResponse(data, {
mode: input.kind,
gatewayCredentials:
routing === undefined
diff --git a/packages/eve/src/internal/nitro/routes/runtime-artifacts.test.ts b/packages/eve/src/internal/nitro/routes/runtime-artifacts.test.ts
index ba594dea4..9a30323af 100644
--- a/packages/eve/src/internal/nitro/routes/runtime-artifacts.test.ts
+++ b/packages/eve/src/internal/nitro/routes/runtime-artifacts.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { COMPILED_AGENT_MANIFEST_VERSION } from "#compiler/manifest.js";
+import { compileFromMemory } from "#compiler/compile-from-memory.js";
import { installBundledCompiledArtifacts } from "#runtime/loaders/bundled-artifacts.js";
import { createRuntimeSession, withRuntimeSession } from "#runtime/sessions/runtime-session.js";
import { resolveNitroCompiledArtifactsSource } from "#internal/nitro/routes/runtime-artifacts.js";
@@ -11,40 +11,15 @@ import { resolveNitroCompiledArtifactsSource } from "#internal/nitro/routes/runt
* scope so the install targets the scoped session rather than the
* process-default singleton.
*/
-function installEmptyBundledArtifacts(): void {
- const manifest = {
- agentId: "test-agent",
- agentRoot: "/tmp/agent",
- appRoot: "/tmp/app",
- channels: [],
- config: {
- model: {
- id: "openai/gpt-5.4-mini",
- },
- name: "Test Agent",
- },
- diagnosticsSummary: {
- errors: 0,
- warnings: 0,
- },
- disabledFrameworkTools: [],
- kind: "eve-agent-compiled-manifest",
- sandbox: null,
- schedules: [],
- skills: [],
- subagentEdges: [],
- subagents: [],
- tools: [],
- version: COMPILED_AGENT_MANIFEST_VERSION,
- };
+async function installEmptyBundledArtifacts(): Promise<void> {
+ const { manifest, moduleMap } = await compileFromMemory({
+ model: "openai/gpt-5.4",
+ name: "test-agent",
+ });
installBundledCompiledArtifacts({
- manifest: manifest as unknown as Parameters<
- typeof installBundledCompiledArtifacts
- >[0]["manifest"],
- moduleMap: {
- nodes: {},
- },
+ manifest,
+ moduleMap,
});
}
@@ -64,8 +39,8 @@ async function withScopedRuntimeSession<T>(fn: () => T | Promise<T>): Promise<T>
describe("resolveNitroCompiledArtifactsSource", () => {
it("prefers disk artifacts in development mode even when bundled artifacts exist", async () => {
- await withScopedRuntimeSession(() => {
- installEmptyBundledArtifacts();
+ await withScopedRuntimeSession(async () => {
+ await installEmptyBundledArtifacts();
const moduleMapLoaderPath = "/package/src/internal/authored-module-map-loader.ts";
expect(
@@ -85,8 +60,8 @@ describe("resolveNitroCompiledArtifactsSource", () => {
});
it("uses bundled artifacts outside development mode when they exist", async () => {
- await withScopedRuntimeSession(() => {
- installEmptyBundledArtifacts();
+ await withScopedRuntimeSession(async () => {
+ await installEmptyBundledArtifacts();
expect(
resolveNitroCompiledArtifactsSource({
diff --git a/packages/eve/src/internal/nitro/routes/runtime-stack.ts b/packages/eve/src/internal/nitro/routes/runtime-stack.ts
index 27ff5051e..878704677 100644
--- a/packages/eve/src/internal/nitro/routes/runtime-stack.ts
+++ b/packages/eve/src/internal/nitro/routes/runtime-stack.ts
@@ -12,22 +12,22 @@ import {
/**
* Bundle returned to the per-channel Nitro dispatch handler.
*
- * Carries the resolved channel set (framework defaults + authored
- * overrides minus authored disables) and the per-request workflow runtime.
+ * Carries the effective resolved channel set from the compiled route plan and
+ * the per-request workflow runtime.
* The dispatch handler walks `channels` to match the inbound request
* against a registered URL pattern, then calls the matched channel's
* `fetch` with a `RouteContext` built from `runtime`.
*/
export interface NitroChannelRuntimeBundle {
+ readonly agentName: string;
readonly channels: readonly ResolvedChannelDefinition[];
readonly resolveRemoteAgentStreamHeaders?: RemoteAgentStreamHeadersResolver;
readonly runtime: Runtime;
}
/**
- * Resolves the per-request channel bundle: the agent's resolved channels
- * (already merged with framework defaults by `resolve-agent-graph.ts`)
- * and a fresh workflow runtime.
+ * Resolves the per-request channel bundle from the effective compiled graph
+ * and creates a fresh workflow runtime.
*
* No singleton caching is needed — session state lives inside the
* workflow's durable execution and the channel set is recomputed from the
@@ -42,6 +42,7 @@ export async function resolveNitroChannelRuntimeBundle(
});
const runtime = createWorkflowRuntime({ compiledArtifactsSource });
return {
+ agentName: bundle.resolvedAgent.config?.name ?? "eve",
channels: bundle.graph.root.channels,
resolveRemoteAgentStreamHeaders: async (input) =>
await resolveRemoteAgentStreamHeaders({ bundle, ...input }),
diff --git a/packages/eve/src/internal/programmatic-source-loader.ts b/packages/eve/src/internal/programmatic-source-loader.ts
new file mode 100644
index 000000000..482f2b726
--- /dev/null
+++ b/packages/eve/src/internal/programmatic-source-loader.ts
@@ -0,0 +1 @@
+export { loadFrameworkProgrammaticModule } from "#framework/sources/registry.js";
diff --git a/packages/eve/src/internal/runtime-registry.ts b/packages/eve/src/internal/runtime-registry.ts
index 11c156c8d..ff1f7b351 100644
--- a/packages/eve/src/internal/runtime-registry.ts
+++ b/packages/eve/src/internal/runtime-registry.ts
@@ -62,8 +62,8 @@ interface RuntimeRegistryRegisterOptions {
* collision.
*
* The optional `reserved` set lets a registry detect collisions across
- * multiple registration passes — for example the tool registry seeds
- * reserved framework tool names so authored tools cannot shadow them.
+ * multiple registration passes — for example when runtime-derived tools and
+ * selected compiled tools share one model-visible namespace.
* Once an entry is registered its name is automatically added to the
* reserved set.
*/
@@ -126,8 +126,7 @@ export class RuntimeRegistry<TEntry> {
/**
* Adds or replaces an entry without uniqueness or reservation checks.
- * Use for framework-owned defaults that the caller has already
- * validated.
+ * Use for entries the caller has already validated.
*/
set(name: string, entry: TEntry): void {
this._entries.set(name, entry);
diff --git a/packages/eve/src/internal/structural-tests/file-length.test.ts b/packages/eve/src/internal/structural-tests/file-length.test.ts
index 52209b567..fa5fc1f13 100644
--- a/packages/eve/src/internal/structural-tests/file-length.test.ts
+++ b/packages/eve/src/internal/structural-tests/file-length.test.ts
@@ -19,7 +19,6 @@ const LONG_SOURCE_FILE_ALLOWLIST = new Set<string>([
"harness/tool-loop.ts",
"internal/nitro/host/create-application-nitro.ts",
"protocol/message.ts",
- "public/channels/eve.ts",
"public/channels/auth.ts",
"public/channels/slack/slackChannel.ts",
"public/channels/teams/teamsChannel.ts",
diff --git a/packages/eve/src/internal/testing/agent-info-fixture.ts b/packages/eve/src/internal/testing/agent-info-fixture.ts
new file mode 100644
index 000000000..954370720
--- /dev/null
+++ b/packages/eve/src/internal/testing/agent-info-fixture.ts
@@ -0,0 +1,77 @@
+import type { AgentInfoResult } from "#client/types.js";
+
+export function createTestAgentInfoResult(
+ input: {
+ readonly agentRoot?: string;
+ readonly appRoot?: string;
+ readonly modelId?: string;
+ readonly name?: string;
+ } = {},
+): AgentInfoResult {
+ const agentRoot = input.agentRoot ?? "/tmp/test-agent/agent";
+ const appRoot = input.appRoot ?? "/tmp/test-agent";
+ const owner = { kind: "application" as const };
+ const configBinding = {
+ backing: {
+ externalDependencies: [],
+ kind: "filesystem" as const,
+ sourcePath: `${agentRoot}/agent.ts`,
+ },
+ logicalPath: "agent.ts",
+ owner,
+ };
+ return {
+ agent: {
+ agentRoot,
+ appRoot,
+ config: {
+ binding: configBinding,
+ logicalPath: "agent.ts",
+ owner,
+ sourceId: "agent.ts",
+ sourceKind: "module",
+ },
+ model: {
+ id: input.modelId ?? "openai/gpt-5.5",
+ routing: { kind: "gateway", target: "openai" },
+ },
+ name: input.name ?? "Test Agent",
+ nodeId: "__root__",
+ },
+ capabilities: { devRoutes: true },
+ channels: { routes: [], shadowed: [] },
+ composition: { disabled: [], shadowed: [] },
+ connections: [],
+ diagnostics: { discoveryErrors: 0, discoveryWarnings: 0 },
+ hooks: [],
+ instructions: { dynamic: [], static: [] },
+ kernelEffects: [],
+ kind: "eve-agent-info",
+ mode: "development",
+ remoteAgents: { entries: [], total: 0 },
+ sandbox: {
+ binding: {
+ backing: {
+ externalDependencies: [],
+ kind: "filesystem",
+ sourcePath: `${agentRoot}/sandbox.ts`,
+ },
+ logicalPath: "sandbox.ts",
+ owner,
+ },
+ hasBootstrap: false,
+ hasOnSession: false,
+ logicalPath: "sandbox.ts",
+ owner,
+ sourceId: "sandbox.ts",
+ sourceKind: "module",
+ },
+ schedules: [],
+ skills: { dynamic: [], static: [] },
+ subagents: { local: [], total: 0 },
+ tools: { dynamic: [], static: [] },
+ version: 3,
+ workflow: { enabled: false, toolName: "Workflow" },
+ workspace: { resourceRoot: null, rootEntries: [] },
+ };
+}
diff --git a/packages/eve/src/internal/testing/app-harness.integration.test.ts b/packages/eve/src/internal/testing/app-harness.integration.test.ts
index d2e4bdb6e..fae71ffda 100644
--- a/packages/eve/src/internal/testing/app-harness.integration.test.ts
+++ b/packages/eve/src/internal/testing/app-harness.integration.test.ts
@@ -22,7 +22,7 @@ function buildSerializedContext(overrides: {
describe("AppHarness pilot", () => {
it("runs a task-mode turn end-to-end against an in-memory test runtime", async () => {
- const runtime = createTestRuntime({ agent: { name: "pilot-agent" } });
+ const runtime = await createTestRuntime({ agent: { name: "pilot-agent" } });
const output = await runtime.run(async () => {
const run = await start(workflowEntry, [
@@ -45,7 +45,7 @@ describe("AppHarness pilot", () => {
});
it("keeps compiled artifacts scoped to the test runtime session", async () => {
- const runtime = createTestRuntime({ agent: { name: "scope-probe" } });
+ const runtime = await createTestRuntime({ agent: { name: "scope-probe" } });
// Before `run`, the session has no artifacts installed.
expect(runtime.session.compiledArtifacts).toBeNull();
@@ -66,8 +66,8 @@ describe("AppHarness pilot", () => {
});
it("isolates two concurrent test runtimes without cache crosstalk", async () => {
- const runtimeA = createTestRuntime({ agent: { name: "tenant-a" } });
- const runtimeB = createTestRuntime({ agent: { name: "tenant-b" } });
+ const runtimeA = await createTestRuntime({ agent: { name: "tenant-a" } });
+ const runtimeB = await createTestRuntime({ agent: { name: "tenant-b" } });
const outputs = await Promise.all([
runtimeA.run(async () => {
diff --git a/packages/eve/src/internal/testing/app-harness.ts b/packages/eve/src/internal/testing/app-harness.ts
index 4f102a71c..d85d80481 100644
--- a/packages/eve/src/internal/testing/app-harness.ts
+++ b/packages/eve/src/internal/testing/app-harness.ts
@@ -1,6 +1,6 @@
import type { JsonObject } from "#shared/json.js";
import type { ChannelAdapter } from "#channel/adapter.js";
-import { compileFromMemory } from "#compiler/compile-from-memory.js";
+import { compileFromMemory, type CompileFromMemoryInput } from "#compiler/compile-from-memory.js";
import type { CompiledAgentManifest, CompiledSkillDefinition } from "#compiler/manifest.js";
import type { CompiledModuleMap } from "#compiler/module-map.js";
import type { SessionParent, SessionTurn } from "#context/keys.js";
@@ -11,15 +11,18 @@ import {
type RuntimeSession,
withRuntimeSession,
} from "#runtime/sessions/runtime-session.js";
-import { createRuntimeToolRegistry } from "#runtime/tools/registry.js";
import type { ResolvedToolDefinition } from "#runtime/types.js";
-import { serializeInputSchema } from "#shared/tool-schema.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 { defineSandbox } from "#public/definitions/sandbox.js";
+import type { SandboxBackend } from "#public/definitions/sandbox-backend.js";
import {
buildActiveSessionContext,
type ActiveSessionInit,
runWithActiveSessionContext,
} from "#internal/testing/active-session-context.js";
-import type { MockSandbox } from "#internal/testing/mocks/mock-sandbox.js";
+import { mockSandbox, type MockSandbox } from "#internal/testing/mocks/mock-sandbox.js";
/**
* Declarative, in-memory eve app stand-in used by integration tests.
@@ -30,7 +33,8 @@ import type { MockSandbox } from "#internal/testing/mocks/mock-sandbox.js";
*
* Every field is optional — omitting everything produces an agent named
* `"test-agent"` that uses the framework default runtime model and declares
- * no tools, sandboxes, skills, or subagents.
+ * no tools, skills, or subagents. The harness installs an in-memory sandbox
+ * backend so runtime tests never depend on a host container or VM service.
*/
export interface TestAppDescriptor {
readonly agent?: {
@@ -112,7 +116,10 @@ export interface TestRuntime {
* Runs a single authored tool through the runtime tool registry and
* returns whatever its `execute` function produced.
*/
- executeTool(tool: ResolvedToolDefinition, input: unknown): Promise<unknown>;
+ executeTool(
+ tool: string | Pick<ResolvedToolDefinition, "name">,
+ input: unknown,
+ ): Promise<unknown>;
/**
* Clears the compiled-artifact snapshot and bundle cache on this session.
* Tests that re-use a runtime across multiple assertions can call this to
@@ -133,57 +140,74 @@ const DEFAULT_AGENT_NAME = "test-agent";
*/
export const TEST_DEFAULT_MODEL_ID = "openai/gpt-5.4";
-export function createTestRuntime(descriptor: TestAppDescriptor = {}): TestRuntime {
- const compileInput: {
- name: string;
- model: string;
- limits?: {
- readonly maxInputTokensPerSession?: number | false;
- readonly maxOutputTokensPerSession?: number | false;
- readonly sessionTimeoutMs?: number | false;
+const TEST_SANDBOX_BACKEND: SandboxBackend = {
+ name: "eve-test-memory",
+ async create(input) {
+ const sandbox = mockSandbox({ id: input.sessionKey });
+ return {
+ session: sandbox.session,
+ useSessionFn: async () => sandbox.session,
+ captureState: async () => ({
+ backendName: TEST_SANDBOX_BACKEND.name,
+ metadata: {},
+ sessionKey: input.sessionKey,
+ }),
+ shutdown: async () => undefined,
+ stop: async () => undefined,
};
- outputSchema?: JsonObject;
- tools?: readonly {
- readonly name: string;
- readonly description?: string;
- readonly inputSchema?: JsonObject | null;
- }[];
- skills?: readonly {
- readonly name: string;
- readonly description: string;
- readonly markdown?: string;
- }[];
- } = {
+ },
+ prewarm: async () => ({ reused: true }),
+};
+
+export async function createTestRuntime(descriptor: TestAppDescriptor = {}): Promise<TestRuntime> {
+ const compileInput: CompileFromMemoryInput = {
name: descriptor.agent?.name ?? DEFAULT_AGENT_NAME,
model: descriptor.agent?.model ?? TEST_DEFAULT_MODEL_ID,
limits: descriptor.agent?.limits,
+ modules: [
+ {
+ loadNamespace: async () => ({
+ default: defineSandbox({ backend: TEST_SANDBOX_BACKEND }),
+ }),
+ logicalPath: "sandbox.ts",
+ },
+ ],
outputSchema: descriptor.agent?.outputSchema,
};
if (descriptor.tools !== undefined && descriptor.tools.length > 0) {
- compileInput.tools = descriptor.tools.map((tool) => ({
- name: tool.name,
- description: tool.description,
- inputSchema: serializeInputSchema(tool.inputSchema),
- }));
+ Object.assign(compileInput, {
+ tools: descriptor.tools.map((tool) => ({
+ name: tool.name,
+ description: tool.description,
+ execute: tool.execute,
+ inputSchema: serializeInputSchema(tool.inputSchema),
+ outputSchema:
+ tool.outputSchema === undefined ? undefined : serializeOutputSchema(tool.outputSchema),
+ approval: tool.approval,
+ toModelOutput: tool.toModelOutput,
+ })),
+ });
}
if (descriptor.skills !== undefined && descriptor.skills.length > 0) {
- compileInput.skills = descriptor.skills.map((skill) => {
- const entry: { name: string; description: string; markdown?: string } = {
- name: skill.name,
- description: skill.description,
- };
+ Object.assign(compileInput, {
+ skills: descriptor.skills.map((skill) => {
+ const entry: { name: string; description: string; markdown?: string } = {
+ name: skill.name,
+ description: skill.description,
+ };
- if (skill.markdown !== undefined) {
- entry.markdown = skill.markdown;
- }
+ if (skill.markdown !== undefined) {
+ entry.markdown = skill.markdown;
+ }
- return entry;
+ return entry;
+ }),
});
}
- const { manifest, moduleMap } = compileFromMemory(compileInput);
+ const { manifest, moduleMap } = await compileFromMemory(compileInput);
const session = createRuntimeSession(descriptor.agent?.name ?? DEFAULT_AGENT_NAME);
const tools = descriptor.tools ?? [];
const skills = descriptor.skills ?? [];
@@ -222,21 +246,18 @@ export function createTestRuntime(descriptor: TestAppDescriptor = {}): TestRunti
session.bundleCacheKeyBySourceKey.clear();
}
- async function executeTool(tool: ResolvedToolDefinition, input: unknown): Promise<unknown> {
- const registry = await createRuntimeToolRegistry({ tools: [tool] });
- const registered = registry.toolsByName.get(tool.name);
-
- if (registered === undefined) {
- throw new Error(`Tool "${tool.name}" is not registered.`);
- }
-
- const execute = registered.definition.execute;
-
- if (execute === undefined) {
- throw new Error(`Tool "${tool.name}" is not executable.`);
- }
-
- return await execute(input, { messages: [], toolCallId: "call_test" });
+ async function executeTool(
+ tool: string | Pick<ResolvedToolDefinition, "name">,
+ input: unknown,
+ ): Promise<unknown> {
+ const name = typeof tool === "string" ? tool : tool.name;
+ return await run(async () => {
+ const graph = await resolveRuntimeAgentGraph({ manifest, moduleMap });
+ const definition = createNodeHarnessTools({ node: graph.root }).get(name);
+ if (definition === undefined) throw new Error(`Tool "${name}" is not installed.`);
+ if (definition.execute === undefined) throw new Error(`Tool "${name}" is not executable.`);
+ return await definition.execute(input, { messages: [], toolCallId: "call_test" });
+ });
}
return {
diff --git a/packages/eve/src/internal/testing/mocks/mock-channel-operations.ts b/packages/eve/src/internal/testing/mocks/mock-channel-operations.ts
index 7b9d7e45b..ab821c5a3 100644
--- a/packages/eve/src/internal/testing/mocks/mock-channel-operations.ts
+++ b/packages/eve/src/internal/testing/mocks/mock-channel-operations.ts
@@ -7,7 +7,7 @@ import type {
InternalChannelSource,
} from "#channel/channel-operations.js";
import { INTERNAL_CHANNEL_DELIVER } from "#channel/channel-operations.js";
-import { type InputResponse, inputResponseSchema } from "#runtime/input/types.js";
+import { type InputResponse, inputResponseSchema } from "#shared/input.js";
export type ObservedChannelDelivery<TState> =
| (ChannelSendOptions<TState> & { readonly message: string | UserContent })
diff --git a/packages/eve/src/internal/testing/mocks/mock-skill.ts b/packages/eve/src/internal/testing/mocks/mock-skill.ts
index 596d36815..f668e6627 100644
--- a/packages/eve/src/internal/testing/mocks/mock-skill.ts
+++ b/packages/eve/src/internal/testing/mocks/mock-skill.ts
@@ -176,6 +176,7 @@ function buildSkillSource(input: {
logicalPath: `skills/${input.name}/SKILL.md`,
markdown: input.markdown,
name: input.name,
+ owner: { kind: "application" },
sourceId: `skills/${input.name}/SKILL.md`,
sourceKind: "skill-package",
skillId: input.name,
diff --git a/packages/eve/src/internal/testing/mocks/mock-tool.ts b/packages/eve/src/internal/testing/mocks/mock-tool.ts
index 61aa98373..8b2cbadcc 100644
--- a/packages/eve/src/internal/testing/mocks/mock-tool.ts
+++ b/packages/eve/src/internal/testing/mocks/mock-tool.ts
@@ -52,6 +52,7 @@ export function mockTool(input: MockToolInput): ResolvedToolDefinition {
inputSchema: toInputSchema(input.inputSchema ?? null),
logicalPath,
name: input.name,
+ owner: { kind: "application" },
sourceId: logicalPath,
sourceKind: "module",
};
diff --git a/packages/eve/src/internal/testing/scenario-app.ts b/packages/eve/src/internal/testing/scenario-app.ts
index d09ce2c00..d22e11e5e 100644
--- a/packages/eve/src/internal/testing/scenario-app.ts
+++ b/packages/eve/src/internal/testing/scenario-app.ts
@@ -275,7 +275,10 @@ async function installScenarioDependencies(input: {
// A project .npmrc overrides any host-global release-age gate, which
// would otherwise reject the workspace's freshly published dependency
// versions and make the test outcome depend on host configuration.
- await writeFile(join(input.appRoot, ".npmrc"), "min-release-age=0\n");
+ await writeFile(
+ join(input.appRoot, ".npmrc"),
+ "registry=https://registry.npmjs.org/\nmin-release-age=0\n",
+ );
await runInstallCommand(input.appRoot, "npm", [
"install",
"--no-audit",
@@ -293,6 +296,7 @@ async function installScenarioDependencies(input: {
join(input.appRoot, "bunfig.toml"),
["[install]", "minimumReleaseAge = 0", ""].join("\n"),
);
+ await writeFile(join(input.appRoot, ".npmrc"), "registry=https://registry.npmjs.org/\n");
await runInstallCommand(input.appRoot, "bun", ["install", "--ignore-scripts"]);
return;
}
@@ -320,6 +324,10 @@ async function runInstallCommand(
try {
await runFile(command, [...args], {
cwd: appRoot,
+ env: {
+ ...process.env,
+ NPM_CONFIG_USERCONFIG: join(appRoot, ".npmrc"),
+ },
maxBuffer: 10 * 1024 * 1024,
shell: process.platform === "win32",
});
diff --git a/packages/eve/src/internal/testing/scenario-apps/tool-overrides.ts b/packages/eve/src/internal/testing/scenario-apps/tool-overrides.ts
index bb24aeadd..4557bcf52 100644
--- a/packages/eve/src/internal/testing/scenario-apps/tool-overrides.ts
+++ b/packages/eve/src/internal/testing/scenario-apps/tool-overrides.ts
@@ -27,7 +27,7 @@ export default disableTool();
`,
"agent/tools/bash.ts": `import { defineTool } from "eve/tools";
import { always } from "eve/tools/approval";
-import { bash } from "eve/tools/defaults";
+import { bash } from "eve/tools/bash";
// Wraps the framework \`bash\` tool: spread the default and replace \`execute\`
// with a thin pre-hook that delegates to the original. The framework's
diff --git a/packages/eve/src/internal/testing/stub-sandbox-registry.ts b/packages/eve/src/internal/testing/stub-sandbox-registry.ts
index 29bf27808..751fa542c 100644
--- a/packages/eve/src/internal/testing/stub-sandbox-registry.ts
+++ b/packages/eve/src/internal/testing/stub-sandbox-registry.ts
@@ -1,7 +1,5 @@
-import {
- createFrameworkSandboxDefinition,
- type RuntimeSandboxRegistry,
-} from "#runtime/sandbox/registry.js";
+import { type RuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";
+import { defaultSandbox } from "#public/sandbox/backends/default.js";
/**
* Stub registry for tests that exercise harness/execution paths that do
@@ -15,7 +13,12 @@ import {
export function createStubSandboxRegistry(): RuntimeSandboxRegistry {
return {
sandbox: {
- definition: createFrameworkSandboxDefinition(),
+ definition: {
+ backend: defaultSandbox(),
+ logicalPath: "sandbox.ts",
+ sourceId: "test:stub-sandbox",
+ sourceKind: "module",
+ },
workspaceResourceRoot: {
logicalPath: "test:stub-sandbox/workspace",
rootEntries: [],
diff --git a/packages/eve/src/internal/testing/use-temporary-app-roots.ts b/packages/eve/src/internal/testing/use-temporary-app-roots.ts
index c52f9b1cb..c0af8d060 100644
--- a/packages/eve/src/internal/testing/use-temporary-app-roots.ts
+++ b/packages/eve/src/internal/testing/use-temporary-app-roots.ts
@@ -1,8 +1,9 @@
-import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach } from "vitest";
+import { resolvePackageRoot } from "#internal/application/package.js";
/**
* Options accepted by the factory returned from
@@ -77,7 +78,6 @@ export function useTemporaryAppRoots(): (
`${JSON.stringify(packageJson, null, 2)}\n`,
"utf8",
);
-
for (const [relativePath, contents] of Object.entries(options.files ?? {})) {
const destinationPath = join(appRoot, relativePath);
@@ -87,6 +87,9 @@ export function useTemporaryAppRoots(): (
await writeFile(destinationPath, contents, "utf8");
}
+ await mkdir(join(appRoot, "node_modules"), { recursive: true });
+ await symlink(resolvePackageRoot(), join(appRoot, "node_modules", "eve"), "junction");
+
return {
agentRoot,
appRoot,
diff --git a/packages/eve/src/protocol/message.ts b/packages/eve/src/protocol/message.ts
index 286602808..d7913a06b 100644
--- a/packages/eve/src/protocol/message.ts
+++ b/packages/eve/src/protocol/message.ts
@@ -16,8 +16,8 @@ import type {
RuntimeActionRequest,
RuntimeActionResult,
RuntimeToolResultActionResult,
-} from "#runtime/actions/types.js";
-import type { InputRequest, InputResponse } from "#runtime/input/types.js";
+} from "#shared/action-types.js";
+import type { InputRequest, InputResponse } from "#shared/input.js";
import { toChannelLocalContinuationToken } from "#shared/continuation-token.js";
import type { JsonObject, JsonValue } from "#shared/json.js";
diff --git a/packages/eve/src/protocol/routes.ts b/packages/eve/src/protocol/routes.ts
index 9bd97b9e6..6de1a9aaa 100644
--- a/packages/eve/src/protocol/routes.ts
+++ b/packages/eve/src/protocol/routes.ts
@@ -4,6 +4,9 @@
*/
export const EVE_ROUTE_PREFIX = "/eve/v1";
+/** Reservation pattern for the production cron bridge's unguessable token. */
+export const EVE_PRODUCTION_CRON_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/cron/:token`;
+
/**
* Stable framework-owned health route.
*/
diff --git a/packages/eve/src/public/channels/auth.test.ts b/packages/eve/src/public/channels/auth.test.ts
index 20192a33e..4d318731d 100644
--- a/packages/eve/src/public/channels/auth.test.ts
+++ b/packages/eve/src/public/channels/auth.test.ts
@@ -3,7 +3,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { EVE_SESSION_ROUTE_PATH } from "#protocol/routes.js";
import type { SessionAuthContext } from "#channel/types.js";
-import { withVercelOidcProjectResolver } from "#runtime/governance/auth/vercel-oidc-project.js";
+import { withVercelOidcProjectResolver } from "#channel/auth/vercel-oidc-project.js";
import {
type AuthFn,
createIpAllowList,
diff --git a/packages/eve/src/public/channels/auth.ts b/packages/eve/src/public/channels/auth.ts
index b0a15a9f4..2a256dc23 100644
--- a/packages/eve/src/public/channels/auth.ts
+++ b/packages/eve/src/public/channels/auth.ts
@@ -10,25 +10,25 @@ import { decodeJwt } from "#compiled/jose/index.js";
import type { SessionAuthContext } from "#channel/types.js";
import { isEveDevEnvironment } from "#internal/application/dev-environment.js";
import { createLogger } from "#internal/logging.js";
-import { authenticateHttpBasicStrategy } from "#runtime/governance/auth/http-basic.js";
-import { authenticateJwtEcdsaStrategy } from "#runtime/governance/auth/jwt-ecdsa.js";
-import { authenticateJwtHmacStrategy } from "#runtime/governance/auth/jwt-hmac.js";
-import { authenticateOidcStrategy } from "#runtime/governance/auth/oidc.js";
-import { resolveVercelOidcCurrentProject } from "#runtime/governance/auth/vercel-oidc-project.js";
+import { authenticateHttpBasicStrategy } from "#channel/auth/http-basic.js";
+import { authenticateJwtEcdsaStrategy } from "#channel/auth/jwt-ecdsa.js";
+import { authenticateJwtHmacStrategy } from "#channel/auth/jwt-hmac.js";
+import { authenticateOidcStrategy } from "#channel/auth/oidc.js";
+import { resolveVercelOidcCurrentProject } from "#channel/auth/vercel-oidc-project.js";
import {
createRuntimeSessionAuthContext,
type ResolvedJwtEcdsaAuthStrategy,
type ResolvedJwtHmacAuthStrategy,
type ResolvedOidcAuthStrategy,
type RouteStrategyAuthenticationResult,
-} from "#runtime/governance/auth/types.js";
+} from "#channel/auth/types.js";
const vercelOidcLog = createLogger("auth.vercel-oidc");
import {
createRuntimeIpAllowList,
isRuntimeIpAllowed,
type RuntimeIpAllowList,
-} from "#runtime/governance/network/ip-allow-list.js";
+} from "#channel/ip-allow-list.js";
import { isLoopbackHostname } from "#shared/network-address.js";
// ---------------------------------------------------------------------------
diff --git a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts
index ed970d85f..6abd8b75f 100644
--- a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts
+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts
@@ -13,7 +13,7 @@ import { ContextContainer, contextStorage } from "#context/container.js";
import { ContextKey } from "#context/key.js";
import { createLogger, extractErrorId, formatErrorHint } from "#internal/logging.js";
import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
-import type { InputRequest } from "#runtime/input/types.js";
+import type { InputRequest } from "#shared/input.js";
import type {
ActionEvent,
Adapter,
diff --git a/packages/eve/src/public/channels/discord/discordChannel.ts b/packages/eve/src/public/channels/discord/discordChannel.ts
index b06552955..e300a919e 100644
--- a/packages/eve/src/public/channels/discord/discordChannel.ts
+++ b/packages/eve/src/public/channels/discord/discordChannel.ts
@@ -51,7 +51,7 @@ import { verifyDiscordInbound } from "#public/channels/discord/verifyInbound.js"
import { readNonEmptyString } from "#shared/guards.js";
import { parseJsonObject, type JsonObject } from "#shared/json.js";
import { defineChannel, POST, type Channel } from "#public/definitions/channel.js";
-import type { ValidatedInputResponse } from "#runtime/input/types.js";
+import type { ValidatedInputResponse } from "#shared/input.js";
import type { ChannelAudience } from "#shared/channel-audience.js";
import { discordAudience, discordInstrumentationMetadata } from "./audience.js";
diff --git a/packages/eve/src/public/channels/discord/hitl.test.ts b/packages/eve/src/public/channels/discord/hitl.test.ts
index 74e51974d..8c58ffe0f 100644
--- a/packages/eve/src/public/channels/discord/hitl.test.ts
+++ b/packages/eve/src/public/channels/discord/hitl.test.ts
@@ -12,7 +12,7 @@ import type {
DiscordComponentInteraction,
DiscordModalSubmitInteraction,
} from "#public/channels/discord/inbound.js";
-import type { InputRequest } from "#runtime/input/types.js";
+import type { InputRequest } from "#shared/input.js";
const BASE_COMPONENT: Omit<
DiscordComponentInteraction,
diff --git a/packages/eve/src/public/channels/discord/hitl.ts b/packages/eve/src/public/channels/discord/hitl.ts
index 63285c44a..405a8d1b8 100644
--- a/packages/eve/src/public/channels/discord/hitl.ts
+++ b/packages/eve/src/public/channels/discord/hitl.ts
@@ -15,7 +15,7 @@ import {
type InputRequest,
parseInputResponse,
type ValidatedInputResponse,
-} from "#runtime/input/types.js";
+} from "#shared/input.js";
/** Maps Discord component kinds (ACTION_ROW, BUTTON, STRING_SELECT, TEXT_INPUT) to their wire `type` integers used in component payloads. */
export const DISCORD_COMPONENT_TYPE = {
diff --git a/packages/eve/src/public/channels/eve-forwarded-principal.integration.test.ts b/packages/eve/src/public/channels/eve-forwarded-principal.integration.test.ts
index d6ccb19a9..5f144772d 100644
--- a/packages/eve/src/public/channels/eve-forwarded-principal.integration.test.ts
+++ b/packages/eve/src/public/channels/eve-forwarded-principal.integration.test.ts
@@ -48,6 +48,23 @@ const FORWARDED_INITIATOR: SessionAuthContext = {
subject: "U999",
};
+function createEmptySkillBundle(): CompiledBundle {
+ return {
+ adapterRegistry: undefined as never,
+ compiledArtifactsSource: undefined as never,
+ graph: undefined as never,
+ hookRegistry: undefined as never,
+ moduleMap: undefined as never,
+ nodeId: undefined,
+ resolvedAgent: { skills: [] } as never,
+ subagentRegistry: undefined as never,
+ toolRegistry: undefined as never,
+ turnAgent: undefined as never,
+ };
+}
+
+const EMPTY_SKILL_BUNDLE = createEmptySkillBundle();
+
function createEveCreateHandler(input: EveChannelInput) {
const channel = eveChannel(input);
const createRoute = channel.routes.find(
@@ -112,7 +129,7 @@ describe("eveChannel forwarded principal → runtime principal", () => {
channelName: "eve",
...options,
};
- const ctx = buildRunContext({ bundle: {} as CompiledBundle, run });
+ const ctx = buildRunContext({ bundle: EMPTY_SKILL_BUNDLE, run });
const current = ctx.get(AuthKey);
const initiator = ctx.get(InitiatorAuthKey);
@@ -163,7 +180,7 @@ describe("eveChannel forwarded principal → runtime principal", () => {
"adapter" | "channelName" | "requestId"
>;
const ctx = buildRunContext({
- bundle: {} as CompiledBundle,
+ bundle: EMPTY_SKILL_BUNDLE,
run: {
adapter: { kind: "eve" },
channelName: "eve",
diff --git a/packages/eve/src/public/channels/eve.ts b/packages/eve/src/public/channels/eve.ts
index 39d385616..8b8d7410a 100644
--- a/packages/eve/src/public/channels/eve.ts
+++ b/packages/eve/src/public/channels/eve.ts
@@ -1,1390 +1 @@
-import { type FilePart, type TextPart, type UserContent } from "ai";
-
-import type {
- SessionAuthContext,
- SessionCallback,
- SessionCapabilities,
- TurnPolicy,
-} from "#channel/types.js";
-import type { CancelTurnResponse } from "#protocol/cancel-turn.js";
-import type { ClearResponse } from "#protocol/clear-session.js";
-import type { CompactResponse } from "#protocol/compact-session.js";
-import type { ResetResponse } from "#protocol/reset-session.js";
-import type { Session } from "#channel/session.js";
-import { resolveForwardedPrincipal, type TrustedForwarders } from "#channel/forwarded-principal.js";
-import { parseSessionCallback } from "#channel/session-callback.js";
-import { isRuntimeSessionOwnershipConflictError } from "#execution/runtime-errors.js";
-import { hasInternalRefScheme } from "#internal/attachments/url-refs.js";
-import { createLogger, logError } from "#internal/logging.js";
-import {
- readAgentInfoRouteResponse,
- readRemoteAgentStreamHeadersResolver,
- readRouteSessionCreator,
-} from "#internal/nitro/routes/channel-route-context.js";
-import {
- EVE_MESSAGE_STREAM_CONTENT_TYPE,
- EVE_MESSAGE_STREAM_FORMAT,
- EVE_MESSAGE_STREAM_VERSION,
- EVE_SESSION_ID_HEADER,
- EVE_STREAM_FORMAT_HEADER,
- EVE_STREAM_TAIL_INDEX_HEADER,
- EVE_STREAM_VERSION_HEADER,
- type MessageStreamEvent,
- type SubagentCalledStreamEvent,
-} from "#protocol/message.js";
-import { parseTraceparent } from "#protocol/traceparent.js";
-import {
- EVE_INFO_ROUTE_PATH,
- EVE_SESSION_ROUTE_PATH,
- EVE_SESSION_CANCEL_ROUTE_PATTERN,
- EVE_SESSION_CLEAR_ROUTE_PATTERN,
- EVE_SESSION_COMPACT_ROUTE_PATTERN,
- EVE_SESSION_ROUTE_PATTERN,
- EVE_SESSION_RESET_ROUTE_PATTERN,
- EVE_SESSION_STREAM_ROUTE_PATTERN,
- EVE_SUBAGENT_STREAM_ROUTE_PATTERN,
- createEveSessionStreamRoutePath,
- createEveSubagentStreamRoutePath,
-} from "#protocol/routes.js";
-import { isInputResponse, type ValidatedInputResponse } from "#runtime/input/types.js";
-import { type AuthFn, routeAuth } from "#public/channels/auth.js";
-import {
- collectUploadPolicyViolations,
- formatUploadPolicyViolation,
- mergeUploadPolicy,
- type UploadPolicy,
- type UploadPolicyInput,
-} from "#public/channels/upload-policy.js";
-import {
- defineChannel,
- POST,
- GET,
- type Channel,
- type ChannelCors,
- type ChannelEvents,
- type ChannelContinuationOps,
-} from "#public/definitions/channel.js";
-import type { ChannelMethod } from "#public/definitions/channel.js";
-import type { RunMode } from "#shared/run-mode.js";
-import { parseJsonObject, type JsonObject } from "#shared/json.js";
-
-const log = createLogger("eve.channel");
-
-/**
- * Event-handler channel context exposed by `eveChannel({ events })`. The default eve HTTP channel
- * has no platform-specific state, so handlers receive optional continuation routing here and the
- * `SessionContext` third argument from {@link ChannelEvents}.
- */
-export type EveEventContext = ChannelContinuationOps;
-
-/** Runtime stream-event handlers supported by `eveChannel({ events })`. */
-export type EveChannelEvents = ChannelEvents<EveEventContext>;
-
-export interface EveChannelCorsOptions {
- /**
- * Allowed request origin. Pass a single origin string, an exact-origin list,
- * `"null"`, or `"*"`. Omit for `"*"`.
- */
- readonly origin?: "*" | "null" | string | readonly string[];
- /** Methods emitted on preflight responses. Omit for `"*"`. */
- readonly methods?: "*" | readonly ChannelMethod[];
- /** Request headers emitted on preflight responses. Omit for `"*"`. */
- readonly allowedHeaders?: "*" | readonly string[];
- /** Response headers exposed to browser callers. Omit for `"*"`. */
- readonly exposedHeaders?: "*" | readonly string[];
- /** Whether to emit `access-control-allow-credentials: true`. */
- readonly credentials?: boolean;
- /** Max age, in seconds, emitted on preflight responses. */
- readonly maxAge?: number | false;
- /** Preflight response status code. Defaults to 204. */
- readonly preflightStatus?: number;
-}
-
-/**
- * Higher-level CORS policy for the default eve HTTP channel. Pass `true` for
- * fully permissive browser access, or pass an options object to narrow it.
- */
-export type EveChannelCors = boolean | EveChannelCorsOptions;
-
-/** Low-level eve HTTP handle exposed to `eveChannel({ onMessage })`. */
-export interface EveHandle {
- /** Route-auth result for the request; `onMessage` chooses session auth by returning `{ auth }`. */
- readonly caller: SessionAuthContext | null;
- readonly request: Request;
- /** Existing runtime session id for follow-up requests. */
- readonly sessionId?: string;
-}
-
-/** Pre-dispatch context passed to `eveChannel({ onMessage })`. */
-export interface EveMessageContext {
- readonly eve: EveHandle;
-}
-
-/**
- * Result of `eveChannel({ onMessage })`. The object dispatches the inbound message,
- * optionally prepending `context` strings as user messages.
- */
-export type EveMessageResult = {
- readonly auth: SessionAuthContext | null;
- readonly context?: readonly string[];
- /** Overrides the workflow run title without changing the message sent to the model. */
- readonly title?: string;
-};
-
-/** Synchronous or asynchronous `onMessage` result. */
-export type EveMessageResultOrPromise = EveMessageResult | Promise<EveMessageResult>;
-
-/**
- * Default `onMessage` auth projection: returns {@link EveHandle.caller} unchanged as the
- * runtime session auth when {@link EveChannelInput.onMessage} is omitted. Call it from a custom `onMessage` to inherit the default while adding `context`.
- */
-export function defaultEveAuth(ctx: EveMessageContext): SessionAuthContext | null {
- return ctx.eve.caller;
-}
-
-/**
- * Configuration for {@link eveChannel}. Only {@link auth} is required;
- * `uploadPolicy`, `onMessage`, and `events` refine the default HTTP behavior.
- */
-export interface EveChannelInput {
- /**
- * Route auth policy: a single {@link AuthFn} or an ordered array walked by {@link routeAuth}.
- * The first entry returning a {@link SessionAuthContext} wins; `null` / `undefined` skips to
- * the next; exhaustion (including the empty array) rejects with 401. Include `none()` last for anonymous traffic.
- */
- readonly auth: AuthFn<Request> | readonly AuthFn<Request>[];
- /**
- * The trusted-forwarders policy: which transport-authenticated callers may
- * assert a forwarded principal on the create-session or continuation route (the
- * `forwardedPrincipal` body field a `defineRemoteAgent({ forwardPrincipal:
- * true })` sender emits). The predicate receives the *verified* route-auth
- * principal of the forwarder — who is asserting, never what is asserted —
- * and must match it precisely (for example
- * `(forwarder) => forwarder.subject === vercelSubject({ teamSlug, projectName })`).
- * A permissive predicate lets any authenticated forwarder assert any
- * principal.
- *
- * When a trusted forwarder's assertion is accepted on session creation, the
- * forwarded principal replaces `session.auth.current` and
- * `session.auth.initiator`. On continuation, only `session.auth.current`
- * changes; the initiator remains pinned to the session's creator. The
- * forwarder is recorded on accepted contexts as the `eve:forwarded-by`
- * attribute. Omit the option to reject every forwarded assertion with 403.
- */
- readonly trustedForwarders?: TrustedForwarders;
- /**
- * Attachment policy for inbound file parts. Omit for the framework default (25 MB cap, all media
- * types); `"disabled"` rejects every attachment; a partial config is merged onto the default. Violations reject with 413 (too large) or 415 (bad type).
- */
- readonly uploadPolicy?: UploadPolicyInput;
- /**
- * Browser CORS policy for the eve HTTP routes. Omit or pass `false` to leave
- * CORS untouched, pass `true` for fully permissive CORS, or pass an options
- * object to narrow the policy.
- */
- readonly cors?: EveChannelCors;
- /** Policy for follow-up messages that arrive while a turn is active. */
- readonly turnPolicy?: TurnPolicy;
- /**
- * Pre-dispatch hook for inbound eve HTTP messages. Runs after route auth and body
- * parsing, before runtime dispatch.
- */
- readonly onMessage?: (
- ctx: EveMessageContext,
- message: string | UserContent,
- ) => EveMessageResultOrPromise;
- /**
- * Runtime stream-event handlers for the default eve HTTP channel. Handlers receive
- * the event data, {@link EveEventContext}, and `SessionContext` (the same shape as custom channels).
- */
- readonly events?: EveChannelEvents;
-}
-
-/**
- * Concrete return type of {@link eveChannel}. Named so consumers can default-export an
- * `eveChannel(...)` call under `declaration: true` without TypeScript falling back to an
- * internal path for `Channel`.
- */
-export interface EveChannel extends Channel {}
-
-/**
- * Builds the default eve HTTP channel: a {@link defineChannel} instance serving the
- * built-in `/eve/v1` routes (GET inspects the agent, POST creates a session,
- * ID-addressed POST routes deliver follow-ups and controls, and GET streams a
- * session's NDJSON event feed). Every route
- * runs {@link EveChannelInput.auth} via {@link routeAuth} before dispatching.
- * Default-export the result as your `agent/channels/eve.ts` channel; reach for
- * {@link defineChannel} directly only for a custom transport.
- */
-export function eveChannel(input: EveChannelInput): EveChannel {
- const uploadPolicy = mergeUploadPolicy(input.uploadPolicy);
-
- return defineChannel<undefined, EveEventContext>({
- cors: normalizeEveCors(input.cors),
- turnPolicy: input.turnPolicy,
- routes: [
- GET(EVE_INFO_ROUTE_PATH, async (req, args) => {
- const authResult = await routeAuth(req, input.auth);
- if (authResult instanceof Response) return authResult;
-
- const respond = readAgentInfoRouteResponse(args);
- if (respond === undefined) {
- return Response.json(
- { error: "Agent info route requires internal channel dispatch context.", ok: false },
- { status: 500 },
- );
- }
-
- return await respond();
- }),
-
- POST(EVE_SESSION_ROUTE_PATH, async (req, args) => {
- const authResult = await routeAuth(req, input.auth);
- if (authResult instanceof Response) return authResult;
-
- const payload = await parseJsonRequest(req);
- if (payload instanceof Response) return payload;
- const tokenRejection = rejectSessionContinuationToken(payload);
- if (tokenRejection !== null) return tokenRejection;
-
- const forwarded = await resolveForwardedPrincipal({
- trustedForwarders: input.trustedForwarders,
- forwarder: authResult,
- payload,
- });
- if (forwarded instanceof Response) return forwarded;
-
- const body = parseCreateBody(payload);
- if (body instanceof Response) return body;
- // Top-level sessions own their trace. Callback sessions are delegated
- // remote agents and intentionally continue the dispatching agent trace.
- const parentTraceContext =
- body.callback === undefined
- ? undefined
- : parseTraceparent(req.headers.get("traceparent"));
-
- const policyRejection = checkUploadPolicy(body, uploadPolicy);
- if (policyRejection !== null) return policyRejection;
-
- if (body.operationId !== undefined && forwarded.auth.principalType === "anonymous") {
- return Response.json(
- { error: "operationId requires an authenticated principal.", ok: false },
- { status: 400 },
- );
- }
- const operationToken =
- body.operationId === undefined
- ? undefined
- : await deriveOperationContinuationToken({
- auth: forwarded.auth,
- operationId: body.operationId,
- });
- if (operationToken !== undefined) {
- const owner = await args.resolveSession(operationToken);
- if (owner !== undefined) {
- return Response.json(
- { ok: true, sessionId: owner.id, status: "accepted" },
- {
- headers: {
- "cache-control": "no-store",
- [EVE_SESSION_ID_HEADER]: owner.id,
- },
- status: 202,
- },
- );
- }
- }
-
- const messageResult = await resolveOnMessage({
- auth: forwarded.auth,
- config: input,
- message: body.message,
- request: req,
- });
- if (messageResult instanceof Response) return messageResult;
- const createSession = readRouteSessionCreator(args);
- if (createSession === undefined) {
- return Response.json(
- { error: "Session creation requires internal channel dispatch context.", ok: false },
- { status: 500 },
- );
- }
-
- let handle: Awaited<ReturnType<typeof createSession>>;
- try {
- handle = await createSession({
- auth: messageResult.auth,
- capabilities:
- body.capabilities ?? (body.mode === "task" ? undefined : { requestInput: true }),
- callback: body.callback,
- continuationToken: operationToken,
- initiatorAuth: forwarded.accepted ? forwarded.initiatorAuth : undefined,
- input: {
- message: body.message,
- context: mergeContext(body.context, messageResult.context),
- outputSchema: body.outputSchema,
- },
- mode: body.mode ?? "conversation",
- parentTraceContext,
- title: messageResult.title,
- });
- } catch (error) {
- // A concurrent create-once request won the token: adopt its session
- // without delivering this duplicate input.
- if (operationToken !== undefined && isRuntimeSessionOwnershipConflictError(error)) {
- return Response.json(
- { ok: true, sessionId: error.ownerSessionId, status: "accepted" },
- {
- headers: {
- "cache-control": "no-store",
- [EVE_SESSION_ID_HEADER]: error.ownerSessionId,
- },
- status: 202,
- },
- );
- }
- const errorId = logError(log, "session-create request failed", error);
- return Response.json(
- { error: "Failed to create the session.", errorId, ok: false },
- { status: 500 },
- );
- }
-
- return Response.json(
- { ok: true, sessionId: handle.sessionId, status: "accepted" },
- {
- headers: {
- "cache-control": "no-store",
- [EVE_SESSION_ID_HEADER]: handle.sessionId,
- },
- status: 202,
- },
- );
- }),
-
- POST(EVE_SESSION_ROUTE_PATTERN, async (req, { attachSession, params }) => {
- const authResult = await routeAuth(req, input.auth);
- if (authResult instanceof Response) return authResult;
-
- const sessionId = requireSessionId(params);
- if (sessionId instanceof Response) return sessionId;
- const payload = await parseJsonRequest(req);
- if (payload instanceof Response) return payload;
- const forwarded = await resolveForwardedPrincipal({
- trustedForwarders: input.trustedForwarders,
- forwarder: authResult,
- payload,
- });
- if (forwarded instanceof Response) return forwarded;
- const body = parseSessionMessageBody(payload);
- if (body instanceof Response) return body;
-
- const policyRejection = checkUploadPolicy(body, uploadPolicy);
- if (policyRejection !== null) return policyRejection;
-
- let context = body.context;
- let dispatchAuth: SessionAuthContext | null = forwarded.auth;
- if (body.message !== undefined) {
- const messageResult = await resolveOnMessage({
- auth: forwarded.auth,
- config: input,
- message: body.message,
- request: req,
- sessionId,
- });
- if (messageResult instanceof Response) return messageResult;
- context = mergeContext(body.context, messageResult.context);
- dispatchAuth = messageResult.auth;
- }
-
- let result: Awaited<ReturnType<Session["send"]>>;
- try {
- const session = attachSession(sessionId);
- const options = {
- auth: dispatchAuth,
- callback: body.callback,
- context,
- outputSchema: body.outputSchema,
- turnPolicy: body.turnPolicy,
- };
- result =
- body.inputResponses === undefined
- ? await session.send(body.message!, options)
- : await session.respond(body.inputResponses, options);
- } catch (error) {
- const errorId = logError(log, "session-message request failed", error, { sessionId });
- return Response.json(
- { error: "Failed to send the session message.", errorId, ok: false },
- { status: 500 },
- );
- }
- if (result.status === "session_not_active") {
- return Response.json(
- {
- code: "session_not_active",
- error: "The session is no longer active.",
- ok: false,
- },
- { headers: { "cache-control": "no-store" }, status: 409 },
- );
- }
-
- return Response.json(
- { ok: true, sessionId: result.sessionId, status: "accepted" },
- {
- headers: {
- "cache-control": "no-store",
- [EVE_SESSION_ID_HEADER]: result.sessionId,
- },
- status: 202,
- },
- );
- }),
-
- POST(EVE_SESSION_CANCEL_ROUTE_PATTERN, async (req, { attachSession, params }) => {
- const authResult = await routeAuth(req, input.auth);
- if (authResult instanceof Response) return authResult;
- const sessionId = requireSessionId(params);
- if (sessionId instanceof Response) return sessionId;
- const body = await parseCancelTurnBody(req);
- if (body instanceof Response) return body;
- let result: Awaited<ReturnType<Session["cancel"]>>;
- try {
- result = await attachSession(sessionId).cancel({
- taskId: body.taskId,
- turnId: body.turnId,
- });
- } catch (error) {
- const errorId = logError(log, "cancel-turn request failed", error, { sessionId });
- return Response.json(
- { error: "Failed to cancel the turn.", errorId, ok: false },
- { status: 500 },
- );
- }
- return Response.json(
- result.status === "accepted"
- ? ({
- ok: true,
- sessionId: result.sessionId,
- status: "accepted",
- } satisfies CancelTurnResponse)
- : ({ ok: true, status: "no_active_turn" } satisfies CancelTurnResponse),
- {
- headers: { "cache-control": "no-store" },
- status: result.status === "accepted" ? 202 : 200,
- },
- );
- }),
-
- POST(EVE_SESSION_COMPACT_ROUTE_PATTERN, async (req, { attachSession, params }) => {
- const authResult = await routeAuth(req, input.auth);
- if (authResult instanceof Response) return authResult;
- const sessionId = requireSessionId(params);
- if (sessionId instanceof Response) return sessionId;
- const body = await parseSessionControlBody(req);
- if (body instanceof Response) return body;
- let result: Awaited<ReturnType<Session["compact"]>>;
- try {
- result = await attachSession(sessionId).compact();
- } catch (error) {
- const errorId = logError(log, "session-compaction request failed", error, { sessionId });
- return Response.json(
- { error: "Failed to compact the session.", errorId, ok: false },
- { status: 500 },
- );
- }
- return Response.json(
- result.status === "accepted"
- ? ({
- ok: true,
- sessionId: result.sessionId,
- status: "accepted",
- } satisfies CompactResponse)
- : ({ ok: true, status: "no_active_session" } satisfies CompactResponse),
- {
- headers: { "cache-control": "no-store" },
- status: result.status === "accepted" ? 202 : 200,
- },
- );
- }),
-
- POST(EVE_SESSION_CLEAR_ROUTE_PATTERN, async (req, { attachSession, params }) => {
- const authResult = await routeAuth(req, input.auth);
- if (authResult instanceof Response) return authResult;
- const sessionId = requireSessionId(params);
- if (sessionId instanceof Response) return sessionId;
- const body = await parseSessionControlBody(req);
- if (body instanceof Response) return body;
- let result: Awaited<ReturnType<Session["clear"]>>;
- try {
- result = await attachSession(sessionId).clear();
- } catch (error) {
- const errorId = logError(log, "session-clear request failed", error, { sessionId });
- return Response.json(
- { error: "Failed to clear the session context.", errorId, ok: false },
- { status: 500 },
- );
- }
- return Response.json(
- result.status === "accepted"
- ? ({
- ok: true,
- sessionId: result.sessionId,
- status: "accepted",
- } satisfies ClearResponse)
- : ({ ok: true, status: "no_active_session" } satisfies ClearResponse),
- {
- headers: { "cache-control": "no-store" },
- status: result.status === "accepted" ? 202 : 200,
- },
- );
- }),
-
- POST(EVE_SESSION_RESET_ROUTE_PATTERN, async (req, { attachSession, params }) => {
- const authResult = await routeAuth(req, input.auth);
- if (authResult instanceof Response) return authResult;
- const sessionId = requireSessionId(params);
- if (sessionId instanceof Response) return sessionId;
- const body = await parseResetBody(req);
- if (body instanceof Response) return body;
- let result: Awaited<ReturnType<Session["reset"]>>;
- try {
- result = await attachSession(sessionId).reset({ reason: body.reason });
- } catch (error) {
- const errorId = logError(log, "session-reset request failed", error, { sessionId });
- return Response.json(
- { error: "Failed to reset the session.", errorId, ok: false },
- { status: 500 },
- );
- }
- return Response.json(
- result.status === "reset"
- ? ({
- ok: true,
- previousSessionId: result.previousSessionId,
- status: "reset",
- } satisfies ResetResponse)
- : ({ ok: true, status: "no_active_session" } satisfies ResetResponse),
- { headers: { "cache-control": "no-store" } },
- );
- }),
-
- GET(EVE_SESSION_STREAM_ROUTE_PATTERN, async (req, { attachSession, params }) => {
- const authResult = await routeAuth(req, input.auth);
- if (authResult instanceof Response) return authResult;
- const sessionId = requireSessionId(params);
- if (sessionId instanceof Response) return sessionId;
- return await createSessionStreamResponse(req, attachSession(sessionId));
- }),
-
- GET(EVE_SUBAGENT_STREAM_ROUTE_PATTERN, async (req, args) => {
- const authResult = await routeAuth(req, input.auth);
- if (authResult instanceof Response) return authResult;
-
- const parentSessionId = args.params.parentSessionId;
- const callId = args.params.callId;
- const childSessionId = args.params.childSessionId;
- if (!parentSessionId || !callId || !childSessionId) {
- return Response.json(
- { error: "Missing subagent stream coordinates.", ok: false },
- { status: 400 },
- );
- }
-
- const startIndex = parseStartIndex(req);
- if (startIndex instanceof Response) return startIndex;
- const includeTailIndex = parseIncludeTailIndex(req);
-
- const childStreamPath = createEveSubagentStreamRoutePath({
- callId,
- childSessionId,
- parentSessionId,
- });
- let binding: SubagentCalledStreamEvent;
- try {
- const parent = args.attachSession(parentSessionId);
- const found = await findRemoteSubagentBinding({
- callId,
- childSessionId,
- childStreamPath,
- parentSessionId,
- parent,
- });
- if (found === undefined) {
- throw new Error("Remote subagent binding not found.");
- }
- binding = found;
- } catch {
- return Response.json({ error: "Subagent stream not found.", ok: false }, { status: 404 });
- }
-
- const resolveHeaders = readRemoteAgentStreamHeadersResolver(args);
- if (resolveHeaders === undefined) {
- return Response.json(
- {
- error: "Subagent stream proxy requires internal channel dispatch context.",
- ok: false,
- },
- { status: 500 },
- );
- }
-
- let headers: Record<string, string>;
- try {
- headers = await resolveHeaders({
- name: binding.data.toolName,
- resolverId: binding.data.remote!.resolverId,
- url: binding.data.remote!.url,
- });
- } catch {
- return Response.json({ error: "Subagent stream not found.", ok: false }, { status: 404 });
- }
-
- const upstreamUrl = new URL(
- createEveSessionStreamRoutePath(childSessionId).replace(/^\/+/, ""),
- `${binding.data.remote!.url.replace(/\/+$/, "")}/`,
- );
- if (startIndex !== undefined) {
- upstreamUrl.searchParams.set("startIndex", String(startIndex));
- }
- if (includeTailIndex) {
- upstreamUrl.searchParams.set("includeTailIndex", "1");
- }
-
- const upstream = await fetch(upstreamUrl, {
- cache: "no-store",
- headers,
- redirect: "manual",
- signal: req.signal,
- });
- const responseHeaders = new Headers();
- for (const name of [
- "cache-control",
- "content-type",
- "x-accel-buffering",
- EVE_SESSION_ID_HEADER,
- EVE_STREAM_FORMAT_HEADER,
- EVE_STREAM_TAIL_INDEX_HEADER,
- EVE_STREAM_VERSION_HEADER,
- ]) {
- const value = upstream.headers.get(name);
- if (value !== null) responseHeaders.set(name, value);
- }
- return new Response(upstream.body, {
- headers: responseHeaders,
- status: upstream.status,
- statusText: upstream.statusText,
- });
- }),
- ],
- events: input.events,
- });
-}
-
-async function findRemoteSubagentBinding(input: {
- readonly callId: string;
- readonly childSessionId: string;
- readonly childStreamPath: string;
- readonly parentSessionId: string;
- readonly parent: {
- getEventStream(options?: { startIndex?: number }): Promise<ReadableStream<MessageStreamEvent>>;
- getStreamTailIndex(): Promise<number>;
- };
-}): Promise<SubagentCalledStreamEvent | undefined> {
- const tailIndex = await input.parent.getStreamTailIndex();
- if (tailIndex < 0) return undefined;
-
- const events = await input.parent.getEventStream({ startIndex: 0 });
- const reader = events.getReader();
- let binding: SubagentCalledStreamEvent | undefined;
- try {
- for (let index = 0; index <= tailIndex; index += 1) {
- const next = await reader.read();
- if (next.done) break;
- const event = next.value;
- if (
- event.type === "subagent.called" &&
- event.data.sessionId === input.parentSessionId &&
- event.data.callId === input.callId &&
- event.data.childSessionId === input.childSessionId &&
- event.data.childStreamPath === input.childStreamPath &&
- event.data.remote !== undefined
- ) {
- binding = event;
- }
- }
- } finally {
- await reader.cancel().catch(() => {});
- }
- return binding;
-}
-
-function normalizeEveCors(cors: EveChannelCors | undefined): ChannelCors {
- if (cors === undefined || cors === false) {
- return false;
- }
- if (cors === true) {
- return true;
- }
-
- const result: {
- origin?: "*" | "null" | readonly string[];
- methods?: "*" | readonly string[];
- allowHeaders?: "*" | readonly string[];
- exposeHeaders?: "*" | readonly string[];
- credentials?: boolean;
- maxAge?: number | false;
- preflight?: {
- statusCode?: number;
- };
- } = {};
-
- if (cors.origin !== undefined) {
- result.origin = normalizeEveCorsOrigin(cors.origin);
- }
- if (cors.methods !== undefined) {
- result.methods = cors.methods;
- }
- if (cors.allowedHeaders !== undefined) {
- result.allowHeaders = cors.allowedHeaders;
- }
- if (cors.exposedHeaders !== undefined) {
- result.exposeHeaders = cors.exposedHeaders;
- }
- if (cors.credentials !== undefined) {
- result.credentials = cors.credentials;
- }
- if (cors.maxAge !== undefined) {
- result.maxAge = cors.maxAge;
- }
- if (cors.preflightStatus !== undefined) {
- result.preflight = { statusCode: cors.preflightStatus };
- }
-
- return result;
-}
-
-function normalizeEveCorsOrigin(
- origin: NonNullable<EveChannelCorsOptions["origin"]>,
-): "*" | "null" | readonly string[] {
- if (origin === "*" || origin === "null") {
- return origin;
- }
- if (typeof origin === "string") {
- return [origin];
- }
- return origin;
-}
-
-interface OnMessageOutcome {
- readonly auth: SessionAuthContext | null;
- readonly context?: readonly string[];
- readonly title?: string;
-}
-
-async function resolveOnMessage(input: {
- readonly auth: SessionAuthContext | null;
- readonly config: EveChannelInput;
- readonly message: string | UserContent;
- readonly request: Request;
- readonly sessionId?: string;
-}): Promise<OnMessageOutcome | Response> {
- const handler = input.config.onMessage ?? defaultOnMessage;
-
- let result: EveMessageResult;
- try {
- const eve: EveHandle =
- input.sessionId === undefined
- ? { caller: input.auth, request: input.request }
- : { caller: input.auth, request: input.request, sessionId: input.sessionId };
- const ctx: EveMessageContext = { eve };
- result = await handler(ctx, input.message);
- if (result === null || result === undefined) {
- throw new TypeError("eveChannel onMessage must return an auth result.");
- }
- } catch (error) {
- const errorId = logError(log, "onMessage handler failed", error, {
- sessionId: input.sessionId,
- });
- return Response.json(
- { error: "onMessage handler failed.", errorId, ok: false },
- { status: 500 },
- );
- }
-
- return { auth: result.auth, context: result.context, title: result.title };
-}
-
-function defaultOnMessage(ctx: EveMessageContext): EveMessageResult {
- return { auth: defaultEveAuth(ctx) };
-}
-
-interface ParsedCreateBody {
- callback?: SessionCallback;
- capabilities?: SessionCapabilities;
- message: string | UserContent;
- mode?: RunMode;
- context?: readonly string[];
- operationId?: string;
- outputSchema?: JsonObject;
-}
-
-/** Replay-stable identity for one authenticated create operation. */
-async function deriveOperationContinuationToken(input: {
- readonly auth: SessionAuthContext;
- readonly operationId: string;
-}): Promise<string> {
- const identity = JSON.stringify([
- "eve:create-session:v1",
- input.auth.authenticator,
- input.auth.issuer ?? null,
- input.auth.principalType,
- input.auth.principalId,
- input.operationId,
- ]);
- const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(identity));
- const hex = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join(
- "",
- );
- return `eve:op:${hex.slice(0, 32)}`;
-}
-
-function parseCreateBody(payload: Record<string, unknown>): ParsedCreateBody | Response {
- if (payload.inputResponses !== undefined) {
- return Response.json(
- { error: "'inputResponses' is only accepted for an existing session.", ok: false },
- { status: 400 },
- );
- }
- const message = parseMessageField(payload.message);
- if (message instanceof Response) return message;
-
- const context = parseClientContextField(payload.clientContext);
- if (context instanceof Response) return context;
-
- const callback = parseCallbackField(payload.callback);
- if (callback instanceof Response) return callback;
-
- const capabilities = parseCapabilitiesField(payload.capabilities);
- if (capabilities instanceof Response) return capabilities;
-
- const mode = parseModeField(payload.mode);
- if (mode instanceof Response) return mode;
-
- const outputSchema = parseOutputSchemaField(payload.outputSchema);
- if (outputSchema instanceof Response) return outputSchema;
-
- if (message === undefined) {
- return Response.json(
- { error: "Missing or empty 'message' field.", ok: false },
- { status: 400 },
- );
- }
-
- const rawOperationId = payload.operationId;
- if (rawOperationId !== undefined && (typeof rawOperationId !== "string" || !rawOperationId)) {
- return Response.json(
- { error: "Expected 'operationId' to be a non-empty string.", ok: false },
- { status: 400 },
- );
- }
-
- const result: ParsedCreateBody = {
- callback,
- capabilities,
- message,
- mode,
- context,
- outputSchema,
- };
- if (typeof rawOperationId === "string") result.operationId = rawOperationId;
- return result;
-}
-
-interface ParsedSessionMessageBody {
- callback?: SessionCallback;
- message?: string | UserContent;
- inputResponses?: readonly ValidatedInputResponse[];
- context?: readonly string[];
- outputSchema?: JsonObject;
- turnPolicy?: TurnPolicy;
-}
-
-function parseSessionMessageBody(
- payload: Record<string, unknown>,
-): ParsedSessionMessageBody | Response {
- const tokenRejection = rejectSessionContinuationToken(payload);
- if (tokenRejection !== null) return tokenRejection;
-
- const message = parseMessageField(payload.message);
- if (message instanceof Response) return message;
- const callback = parseCallbackField(payload.callback);
- if (callback instanceof Response) return callback;
- const inputResponses = parseInputResponses(payload.inputResponses);
- if (inputResponses instanceof Response) return inputResponses;
- const context = parseClientContextField(payload.clientContext);
- if (context instanceof Response) return context;
- const outputSchema = parseOutputSchemaField(payload.outputSchema);
- if (outputSchema instanceof Response) return outputSchema;
- const turnPolicy = parseTurnPolicyField(payload.turnPolicy);
- if (turnPolicy instanceof Response) return turnPolicy;
-
- if (message === undefined && inputResponses === undefined) {
- return Response.json(
- {
- error: "Expected a non-empty 'message' or a non-empty 'inputResponses' array.",
- ok: false,
- },
- { status: 400 },
- );
- }
-
- if (message !== undefined && inputResponses !== undefined) {
- return Response.json(
- { error: "'message' and 'inputResponses' are mutually exclusive.", ok: false },
- { status: 400 },
- );
- }
-
- return { callback, message, inputResponses, context, outputSchema, turnPolicy };
-}
-
-interface ParsedCancelTurnBody {
- taskId?: string;
- turnId?: string;
-}
-
-async function parseCancelTurnBody(req: Request): Promise<ParsedCancelTurnBody | Response> {
- const payload = await parseOptionalJsonRequest(req);
- if (payload instanceof Response) return payload;
- const tokenRejection = rejectSessionContinuationToken(payload);
- if (tokenRejection !== null) return tokenRejection;
-
- const turnId = payload.turnId;
- const taskId = payload.taskId;
- if (turnId !== undefined && (typeof turnId !== "string" || turnId.length === 0)) {
- return Response.json(
- { error: "Expected 'turnId' to be a non-empty string.", ok: false },
- { status: 400 },
- );
- }
- if (taskId !== undefined && (typeof taskId !== "string" || taskId.length === 0)) {
- return Response.json(
- { error: "Expected 'taskId' to be a non-empty string.", ok: false },
- { status: 400 },
- );
- }
- const result: ParsedCancelTurnBody = {};
- if (typeof taskId === "string") result.taskId = taskId;
- if (typeof turnId === "string") result.turnId = turnId;
- return result;
-}
-
-async function parseJsonRequest(req: Request): Promise<Record<string, unknown> | Response> {
- let payload: unknown;
- try {
- payload = await req.json();
- } catch {
- return Response.json({ error: "Invalid JSON body.", ok: false }, { status: 400 });
- }
- if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
- return Response.json({ error: "Expected a JSON object.", ok: false }, { status: 400 });
- }
- return payload as Record<string, unknown>;
-}
-
-async function parseResetBody(req: Request): Promise<{ readonly reason?: string } | Response> {
- const payload = await parseOptionalJsonRequest(req);
- if (payload instanceof Response) return payload;
- const tokenRejection = rejectSessionContinuationToken(payload);
- if (tokenRejection !== null) return tokenRejection;
- const reason = payload.reason;
- if (reason !== undefined && (typeof reason !== "string" || reason.length === 0)) {
- return Response.json(
- { error: "Expected 'reason' to be a non-empty string.", ok: false },
- { status: 400 },
- );
- }
- return reason === undefined ? {} : { reason };
-}
-
-async function parseSessionControlBody(req: Request): Promise<Record<string, unknown> | Response> {
- const payload = await parseOptionalJsonRequest(req);
- if (payload instanceof Response) return payload;
- return rejectSessionContinuationToken(payload) ?? payload;
-}
-
-async function parseOptionalJsonRequest(req: Request): Promise<Record<string, unknown> | Response> {
- let text: string;
- try {
- text = await req.text();
- } catch {
- return Response.json({ error: "Unreadable request body.", ok: false }, { status: 400 });
- }
- if (text.trim().length === 0) return {};
-
- let payload: unknown;
- try {
- payload = JSON.parse(text);
- } catch {
- return Response.json({ error: "Invalid JSON body.", ok: false }, { status: 400 });
- }
- if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
- return Response.json({ error: "Expected a JSON object.", ok: false }, { status: 400 });
- }
- return payload as Record<string, unknown>;
-}
-
-function rejectSessionContinuationToken(payload: Record<string, unknown>): Response | null {
- return "continuationToken" in payload
- ? Response.json(
- { error: "Session-ID routes do not accept 'continuationToken'.", ok: false },
- { status: 400 },
- )
- : null;
-}
-
-function requireSessionId(params: Readonly<Record<string, string>>): string | Response {
- const sessionId = params.sessionId;
- return sessionId || Response.json({ error: "Missing session id.", ok: false }, { status: 400 });
-}
-
-async function createSessionStreamResponse(request: Request, session: Session): Promise<Response> {
- const startIndex = parseStartIndex(request);
- if (startIndex instanceof Response) return startIndex;
- const includeTailIndex = parseIncludeTailIndex(request);
-
- try {
- const tailIndex = includeTailIndex ? await session.getStreamTailIndex() : undefined;
- const events = await session.getEventStream({ startIndex });
- const headers = new Headers({
- "cache-control": "no-store, no-transform",
- "content-type": EVE_MESSAGE_STREAM_CONTENT_TYPE,
- "x-accel-buffering": "no",
- [EVE_SESSION_ID_HEADER]: session.id,
- [EVE_STREAM_FORMAT_HEADER]: EVE_MESSAGE_STREAM_FORMAT,
- [EVE_STREAM_VERSION_HEADER]: EVE_MESSAGE_STREAM_VERSION,
- });
- if (tailIndex !== undefined) {
- headers.set(EVE_STREAM_TAIL_INDEX_HEADER, String(tailIndex));
- }
- return new Response(
- serializeAsNdjson(events, request.signal, streamEventLimit(startIndex, tailIndex)),
- { headers },
- );
- } catch {
- return Response.json({ error: "Session not found.", ok: false }, { status: 404 });
- }
-}
-
-function parseOutputSchemaField(value: unknown): JsonObject | Response | undefined {
- if (value === undefined) return undefined;
-
- try {
- return parseJsonObject(value);
- } catch {
- return Response.json(
- { error: "Expected 'outputSchema' to be a JSON-serializable object.", ok: false },
- { status: 400 },
- );
- }
-}
-
-function parseCallbackField(value: unknown): SessionCallback | Response | undefined {
- if (value === undefined) return undefined;
- const parsed = parseSessionCallback(value);
- if (parsed.ok) return parsed.callback;
-
- return Response.json({ error: parsed.message, ok: false }, { status: 400 });
-}
-
-function parseCapabilitiesField(value: unknown): SessionCapabilities | Response | undefined {
- if (value === undefined) return undefined;
- if (value === null || typeof value !== "object" || Array.isArray(value)) {
- return Response.json(
- { error: "Expected 'capabilities' to be an object.", ok: false },
- { status: 400 },
- );
- }
-
- const keys = Object.keys(value);
- const requestInput = Reflect.get(value, "requestInput");
- if (
- keys.some((key) => key !== "requestInput") ||
- (requestInput !== undefined && typeof requestInput !== "boolean")
- ) {
- return Response.json(
- { error: "Expected 'capabilities.requestInput' to be a boolean when provided.", ok: false },
- { status: 400 },
- );
- }
-
- return requestInput === undefined ? {} : { requestInput };
-}
-
-function parseModeField(value: unknown): RunMode | Response | undefined {
- if (value === undefined) return undefined;
- if (value === "conversation" || value === "task") return value;
- return Response.json(
- { error: "Expected 'mode' to be either 'conversation' or 'task'.", ok: false },
- { status: 400 },
- );
-}
-
-function parseTurnPolicyField(value: unknown): TurnPolicy | Response | undefined {
- if (value === undefined) return undefined;
- if (value === "queue" || value === "steer") return value;
- return Response.json(
- { error: "Expected 'turnPolicy' to be either 'queue' or 'steer'.", ok: false },
- { status: 400 },
- );
-}
-
-function parseMessageField(value: unknown): string | UserContent | undefined | Response {
- if (value === undefined) return undefined;
- if (typeof value === "string") return value.length > 0 ? value : undefined;
-
- if (!Array.isArray(value)) {
- return Response.json(
- { error: "Expected 'message' to be a string or an array of text/file parts.", ok: false },
- { status: 400 },
- );
- }
-
- if (value.length === 0) return undefined;
-
- const parts: Array<TextPart | FilePart> = [];
- for (const raw of value) {
- const parsed = parseMessagePart(raw);
- if (parsed instanceof Response) return parsed;
- parts.push(parsed);
- }
- return parts;
-}
-
-function parseMessagePart(raw: unknown): TextPart | FilePart | Response {
- if (raw === null || typeof raw !== "object") {
- return Response.json(
- { error: "Expected each message part to be an object.", ok: false },
- { status: 400 },
- );
- }
-
- const part = raw as Record<string, unknown>;
- if (part.type === "text") {
- if (typeof part.text !== "string" || part.text.length === 0) {
- return Response.json(
- { error: "Text parts require a non-empty 'text' string.", ok: false },
- { status: 400 },
- );
- }
- return { type: "text", text: part.text };
- }
-
- if (part.type === "file") {
- if (typeof part.mediaType !== "string" || part.mediaType.length === 0) {
- return Response.json(
- { error: "File parts require a non-empty 'mediaType' string.", ok: false },
- { status: 400 },
- );
- }
- if (typeof part.data !== "string") {
- return Response.json(
- { error: "File parts require a 'data' string (base64, data URL, or URL).", ok: false },
- { status: 400 },
- );
- }
- // Callers must never supply framework-internal refs (`eve-url:`,
- // `eve-sandbox:`, `eve-attachment:`): the staging pipeline trusts the
- // scheme and would reconstitute the string into a privileged sandbox read.
- if (hasInternalRefScheme(part.data)) {
- return Response.json(
- { error: "File part 'data' must not use a framework-internal ref scheme.", ok: false },
- { status: 400 },
- );
- }
- const filePart: FilePart = { type: "file", mediaType: part.mediaType, data: part.data };
- if (typeof part.filename === "string" && part.filename.length > 0) {
- filePart.filename = part.filename;
- }
- return filePart;
- }
-
- return Response.json(
- {
- error: `Unsupported message part type "${String(part.type)}". Use 'text' or 'file'.`,
- ok: false,
- },
- { status: 400 },
- );
-}
-
-function checkUploadPolicy(
- body: ParsedCreateBody | ParsedSessionMessageBody,
- policy: UploadPolicy,
-): Response | null {
- if (!body.message) return null;
- const violations = collectUploadPolicyViolations(body.message, policy);
- if (violations.length === 0) return null;
-
- const [first] = violations;
- if (!first) return null;
-
- const status = first.kind === "too-large" ? 413 : 415;
- return Response.json(
- {
- error: formatUploadPolicyViolation(first),
- ok: false,
- violations: violations.map((v) =>
- v.kind === "too-large"
- ? {
- byteLength: v.byteLength,
- filename: v.filename,
- kind: v.kind,
- limit: v.limit,
- mediaType: v.mediaType,
- }
- : {
- allowedMediaTypes: v.allowedMediaTypes,
- filename: v.filename,
- kind: v.kind,
- mediaType: v.mediaType,
- },
- ),
- },
- { status },
- );
-}
-
-function parseInputResponses(
- value: unknown,
-): readonly ValidatedInputResponse[] | Response | undefined {
- if (value === undefined) return undefined;
- if (!Array.isArray(value) || value.length === 0) {
- return Response.json(
- { error: "Expected 'inputResponses' to be a non-empty array.", ok: false },
- { status: 400 },
- );
- }
- const inputResponses = value.filter(isInputResponse);
- if (inputResponses.length !== value.length) {
- return Response.json(
- {
- error: "Expected every 'inputResponses' entry to match the HITL response schema.",
- ok: false,
- },
- { status: 400 },
- );
- }
- return inputResponses;
-}
-
-function mergeContext(
- existing: readonly string[] | undefined,
- added: readonly string[] | undefined,
-): readonly string[] | undefined {
- if (existing === undefined) return added;
- if (added === undefined) return existing;
- return [...existing, ...added];
-}
-
-const CLIENT_CONTEXT_PREFIX = "Client context:\n";
-
-function parseClientContextField(value: unknown): string[] | Response | undefined {
- if (value === undefined) return undefined;
-
- if (typeof value === "string") {
- return value.length > 0 ? [toClientContextMessage(value)] : undefined;
- }
-
- if (Array.isArray(value)) {
- if (value.length === 0) return undefined;
-
- if (!value.every((entry) => typeof entry === "string" && entry.length > 0)) {
- return Response.json(
- { error: "Expected 'clientContext' array entries to be non-empty strings.", ok: false },
- { status: 400 },
- );
- }
-
- return value.map((entry) => toClientContextMessage(entry));
- }
-
- if (value === null || typeof value !== "object") {
- return Response.json(
- {
- error: "Expected 'clientContext' to be a string, string array, or JSON object.",
- ok: false,
- },
- { status: 400 },
- );
- }
-
- try {
- const json = parseJsonObject(value);
- return [toClientContextMessage(JSON.stringify(json))];
- } catch {
- return Response.json(
- { error: "Expected 'clientContext' to be a JSON-serializable object.", ok: false },
- { status: 400 },
- );
- }
-}
-
-function toClientContextMessage(content: string): string {
- return `${CLIENT_CONTEXT_PREFIX}${content}`;
-}
-
-function parseIncludeTailIndex(request: Request): boolean {
- const raw = new URL(request.url).searchParams.get("includeTailIndex");
- return raw === "1" || raw === "true";
-}
-
-function parseStartIndex(request: Request): number | undefined | Response {
- const raw = new URL(request.url).searchParams.get("startIndex");
- if (raw === null) return undefined;
- const parsed = Number(raw);
- if (!/^-?\d+$/.test(raw) || !Number.isSafeInteger(parsed)) {
- return Response.json(
- { error: "Expected startIndex to be an integer.", ok: false },
- { status: 400 },
- );
- }
- return parsed;
-}
-
-function streamEventLimit(
- startIndex: number | undefined,
- tailIndex: number | undefined,
-): number | undefined {
- if (tailIndex === undefined) return undefined;
- const resolvedStartIndex =
- startIndex === undefined
- ? 0
- : startIndex < 0
- ? Math.max(0, tailIndex + 1 + startIndex)
- : startIndex;
- return Math.max(0, tailIndex - resolvedStartIndex + 1);
-}
-
-function serializeAsNdjson(
- events: ReadableStream<unknown>,
- signal: AbortSignal,
- eventLimit?: number,
-): ReadableStream<Uint8Array> {
- const encoder = new TextEncoder();
- let eventCount = 0;
- const transform = new TransformStream<unknown, Uint8Array>({
- start(controller) {
- controller.enqueue(encoder.encode("\n"));
- if (eventLimit === 0) controller.terminate();
- },
- transform(event, controller) {
- controller.enqueue(encoder.encode(`${JSON.stringify(event)}\n`));
- eventCount += 1;
- if (eventCount === eventLimit) controller.terminate();
- },
- });
- void events.pipeTo(transform.writable, { signal }).catch(() => {});
- return transform.readable;
-}
+export * from "#eve-channel/index.js";
diff --git a/packages/eve/src/public/channels/github/defaults.ts b/packages/eve/src/public/channels/github/defaults.ts
index eacd670a6..44c80aaf3 100644
--- a/packages/eve/src/public/channels/github/defaults.ts
+++ b/packages/eve/src/public/channels/github/defaults.ts
@@ -19,7 +19,7 @@ import type {
} from "#public/channels/github/githubChannel.js";
import { splitGitHubCommentBody } from "#public/channels/github/limits.js";
import type { SessionContext } from "#public/definitions/callback-context.js";
-import type { InputRequest } from "#runtime/input/types.js";
+import type { InputRequest } from "#shared/input.js";
const log = createLogger("github.defaults");
diff --git a/packages/eve/src/public/channels/index.ts b/packages/eve/src/public/channels/index.ts
index b25a89b02..ca42631d7 100644
--- a/packages/eve/src/public/channels/index.ts
+++ b/packages/eve/src/public/channels/index.ts
@@ -1,6 +1,9 @@
export {
defineChannel,
+ disableRoute,
GET,
+ HEAD,
+ OPTIONS,
POST,
PUT,
PATCH,
@@ -23,6 +26,7 @@ export {
type ChannelCors,
type ChannelCorsOptions,
type ChannelDefinition,
+ type DisabledRouteSentinel,
type ChannelContinuationOps,
type ChannelEvents,
type InferChannelMetadata,
@@ -42,6 +46,7 @@ export {
type WebSocketRouteHooks,
type WebSocketUpgradeRequest,
type WebSocketUpgradeResult,
+ isDisabledRouteSentinel,
} from "#public/definitions/channel.js";
export {
createWebSocketUpgradeServer,
diff --git a/packages/eve/src/public/channels/linear/hitl.test.ts b/packages/eve/src/public/channels/linear/hitl.test.ts
index 8c7e0d84a..02d87f2f3 100644
--- a/packages/eve/src/public/channels/linear/hitl.test.ts
+++ b/packages/eve/src/public/channels/linear/hitl.test.ts
@@ -4,7 +4,7 @@ import {
linearInputRequestSignal,
renderLinearInputRequests,
} from "#public/channels/linear/hitl.js";
-import type { InputRequest } from "#runtime/input/types.js";
+import type { InputRequest } from "#shared/input.js";
function makeRequest(overrides: Partial<InputRequest> = {}): InputRequest {
return {
diff --git a/packages/eve/src/public/channels/linear/hitl.ts b/packages/eve/src/public/channels/linear/hitl.ts
index d4c8a08de..20c1b7907 100644
--- a/packages/eve/src/public/channels/linear/hitl.ts
+++ b/packages/eve/src/public/channels/linear/hitl.ts
@@ -1,4 +1,4 @@
-import type { InputRequest } from "#runtime/input/types.js";
+import type { InputRequest } from "#shared/input.js";
import type { JsonObject } from "#shared/json.js";
/** Renders eve input requests as one user-visible Linear elicitation body. */
diff --git a/packages/eve/src/public/channels/linear/linearChannel.test.ts b/packages/eve/src/public/channels/linear/linearChannel.test.ts
index 3a5519616..947fb9ed9 100644
--- a/packages/eve/src/public/channels/linear/linearChannel.test.ts
+++ b/packages/eve/src/public/channels/linear/linearChannel.test.ts
@@ -11,7 +11,7 @@ import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
import { defaultLinearAuth } from "#public/channels/linear/defaults.js";
import { linearChannel, type LinearChannelState } from "#public/channels/linear/linearChannel.js";
import { signLinearWebhookBody } from "#public/channels/linear/verify.js";
-import type { InputRequest } from "#runtime/input/types.js";
+import type { InputRequest } from "#shared/input.js";
const SECRET = "linear-secret";
diff --git a/packages/eve/src/public/channels/mcp.ts b/packages/eve/src/public/channels/mcp.ts
index 685d77566..86a06080f 100644
--- a/packages/eve/src/public/channels/mcp.ts
+++ b/packages/eve/src/public/channels/mcp.ts
@@ -27,7 +27,7 @@ import {
createMcpProtectedResourceMetadata,
createMcpResourceChallenge,
} from "#internal/mcp/protected-resource.js";
-import { inputRequestSchema, inputResponseSchema } from "#runtime/input/types.js";
+import { inputRequestSchema, inputResponseSchema } from "#shared/input.js";
import {
escapeAuthChallengeParameter,
readOAuthResourceOptions,
diff --git a/packages/eve/src/public/channels/slack/action-status.test.ts b/packages/eve/src/public/channels/slack/action-status.test.ts
index c13759003..a6ac59553 100644
--- a/packages/eve/src/public/channels/slack/action-status.test.ts
+++ b/packages/eve/src/public/channels/slack/action-status.test.ts
@@ -4,7 +4,7 @@ import {
describeActionRequest,
describeActionRequests,
} from "#public/channels/slack/action-status.js";
-import type { RuntimeActionRequest } from "#runtime/actions/types.js";
+import type { RuntimeActionRequest } from "#shared/action-types.js";
import type { JsonObject } from "#shared/json.js";
function toolCall(toolName: string, input: JsonObject = {}): RuntimeActionRequest {
diff --git a/packages/eve/src/public/channels/slack/action-status.ts b/packages/eve/src/public/channels/slack/action-status.ts
index ea6ac3cdb..7c07d94a2 100644
--- a/packages/eve/src/public/channels/slack/action-status.ts
+++ b/packages/eve/src/public/channels/slack/action-status.ts
@@ -4,7 +4,7 @@
* label is the action's name plus its most telling argument — `grep useEve`
* or `read_file agent/agent.ts` instead of `Running grep...`.
*/
-import type { RuntimeActionRequest } from "#runtime/actions/types.js";
+import type { RuntimeActionRequest } from "#shared/action-types.js";
/** Argument keys worth surfacing, most telling first, per tool. */
const SALIENT_KEYS: Readonly<Record<string, readonly string[]>> = {
diff --git a/packages/eve/src/public/channels/slack/defaults.ts b/packages/eve/src/public/channels/slack/defaults.ts
index 094d5f0e8..350447786 100644
--- a/packages/eve/src/public/channels/slack/defaults.ts
+++ b/packages/eve/src/public/channels/slack/defaults.ts
@@ -27,7 +27,7 @@ import type {
SlackContext,
SlackMentionResult,
} from "#public/channels/slack/slackChannel.js";
-import type { InputRequest } from "#runtime/input/types.js";
+import type { InputRequest } from "#shared/input.js";
const log = createLogger("slack.defaults");
const REASONING_TYPING_REFRESH_INTERVAL_MS = 5_000;
diff --git a/packages/eve/src/public/channels/slack/hitl.test.ts b/packages/eve/src/public/channels/slack/hitl.test.ts
index c3b135d43..919c83431 100644
--- a/packages/eve/src/public/channels/slack/hitl.test.ts
+++ b/packages/eve/src/public/channels/slack/hitl.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import type { InputRequest } from "#runtime/input/types.js";
+import type { InputRequest } from "#shared/input.js";
import {
buildAnsweredBlocks,
buildFreeformModalView,
diff --git a/packages/eve/src/public/channels/slack/hitl.ts b/packages/eve/src/public/channels/slack/hitl.ts
index a994f8f26..3c377942f 100644
--- a/packages/eve/src/public/channels/slack/hitl.ts
+++ b/packages/eve/src/public/channels/slack/hitl.ts
@@ -23,7 +23,7 @@ import {
type InputRequest,
parseInputResponse,
type ValidatedInputResponse,
-} from "#runtime/input/types.js";
+} from "#shared/input.js";
/**
* Wire-format prefix every framework HITL widget mints onto its
diff --git a/packages/eve/src/public/channels/slack/interactions.ts b/packages/eve/src/public/channels/slack/interactions.ts
index 97b6f2c6f..008848d5a 100644
--- a/packages/eve/src/public/channels/slack/interactions.ts
+++ b/packages/eve/src/public/channels/slack/interactions.ts
@@ -47,7 +47,7 @@ import type {
} from "#public/channels/slack/slackChannel.js";
import type { ChannelFrom, ChannelResolveSession } from "#channel/channel-operations.js";
import { bindSlackSessionOperations } from "#public/channels/slack/session-operations.js";
-import { parseInputResponse } from "#runtime/input/types.js";
+import { parseInputResponse } from "#shared/input.js";
const log = createLogger("slack.interactions");
diff --git a/packages/eve/src/public/channels/slack/session-operations.ts b/packages/eve/src/public/channels/slack/session-operations.ts
index 7ca017337..fc7d0e602 100644
--- a/packages/eve/src/public/channels/slack/session-operations.ts
+++ b/packages/eve/src/public/channels/slack/session-operations.ts
@@ -6,7 +6,7 @@ import type {
ChannelSource,
} from "#channel/channel-operations.js";
import type { SessionAuthContext } from "#channel/types.js";
-import type { InputResponse, StrictInputResponses } from "#runtime/input/types.js";
+import type { InputResponse, StrictInputResponses } from "#shared/input.js";
import type { UserContent } from "ai";
import type { SlackChannelState } from "#public/channels/slack/slackChannel.js";
diff --git a/packages/eve/src/public/channels/slack/slackChannel.test.ts b/packages/eve/src/public/channels/slack/slackChannel.test.ts
index 7819e1e46..57b966256 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.test.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.test.ts
@@ -42,7 +42,7 @@ import {
type SlackEventContext,
} from "#public/channels/slack/slackChannel.js";
import type { SessionContext } from "#public/definitions/callback-context.js";
-import { type InputResponse, parseInputResponses } from "#runtime/input/types.js";
+import { type InputResponse, parseInputResponses } from "#shared/input.js";
function slackRespondTypeChecks(
interaction: SlackInteractionContext,
diff --git a/packages/eve/src/public/channels/slack/slackChannel.ts b/packages/eve/src/public/channels/slack/slackChannel.ts
index ab48fba9e..2424660a4 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.ts
@@ -15,11 +15,7 @@ import type { ChannelContinuationOps } from "#public/definitions/channel.js";
import { createLogger, logError } from "#internal/logging.js";
import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
-import type {
- InputResponse,
- StrictInputResponses,
- ValidatedInputResponse,
-} from "#runtime/input/types.js";
+import type { InputResponse, StrictInputResponses, ValidatedInputResponse } from "#shared/input.js";
import {
buildSlackBinding,
buildSlackWorkspaceHandle,
diff --git a/packages/eve/src/public/channels/teams/hitl.test.ts b/packages/eve/src/public/channels/teams/hitl.test.ts
index 1e4f57922..7f4254e97 100644
--- a/packages/eve/src/public/channels/teams/hitl.test.ts
+++ b/packages/eve/src/public/channels/teams/hitl.test.ts
@@ -12,7 +12,7 @@ import {
TEAMS_HITL_REQUEST_KIND_KEY,
} from "#public/channels/teams/hitl.js";
import { parseTeamsActivity } from "#public/channels/teams/inbound.js";
-import type { InputRequest } from "#runtime/input/types.js";
+import type { InputRequest } from "#shared/input.js";
describe("Teams HITL helpers", () => {
it("renders approval tool input in the card and fallback text", () => {
diff --git a/packages/eve/src/public/channels/teams/hitl.ts b/packages/eve/src/public/channels/teams/hitl.ts
index 28e27fcce..1f09cde73 100644
--- a/packages/eve/src/public/channels/teams/hitl.ts
+++ b/packages/eve/src/public/channels/teams/hitl.ts
@@ -6,7 +6,7 @@ import {
type InputRequest,
parseInputResponse,
type ValidatedInputResponse,
-} from "#runtime/input/types.js";
+} from "#shared/input.js";
import type {
TeamsActivity,
TeamsInvokeActivity,
diff --git a/packages/eve/src/public/channels/telegram/hitl.ts b/packages/eve/src/public/channels/telegram/hitl.ts
index 901e5d60e..192ff72fe 100644
--- a/packages/eve/src/public/channels/telegram/hitl.ts
+++ b/packages/eve/src/public/channels/telegram/hitl.ts
@@ -12,7 +12,7 @@ import {
parseInputResponse,
parseInputResponses,
type ValidatedInputResponse,
-} from "#runtime/input/types.js";
+} from "#shared/input.js";
/** Prefix used in Telegram callback_data values generated by eve. */
export const TELEGRAM_HITL_CALLBACK_PREFIX = "eve:";
diff --git a/packages/eve/src/public/connections/index.ts b/packages/eve/src/public/connections/index.ts
index f5f7f51a7..13597de94 100644
--- a/packages/eve/src/public/connections/index.ts
+++ b/packages/eve/src/public/connections/index.ts
@@ -14,8 +14,8 @@ export type {
NonInteractiveAuthorizationDefinition,
TokenResult,
ToolFilterDefinition,
-} from "#runtime/connections/types.js";
-export { defineInteractiveAuthorization } from "#runtime/connections/types.js";
+} from "#shared/connection-types.js";
+export { defineInteractiveAuthorization } from "#shared/connection-types.js";
export type { JsonValue } from "#public/types/json.js";
export {
defineMcpClientConnection,
diff --git a/packages/eve/src/public/definitions/approval.ts b/packages/eve/src/public/definitions/approval.ts
index 3c1c4a828..cd672c70f 100644
--- a/packages/eve/src/public/definitions/approval.ts
+++ b/packages/eve/src/public/definitions/approval.ts
@@ -2,7 +2,7 @@ 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 "#runtime/connections/types.js";
+import type { TokenResult } from "#shared/connection-types.js";
type ApprovalToolInput<TInput> = TInput extends object ? Readonly<TInput> : TInput;
diff --git a/packages/eve/src/public/definitions/callback-context.ts b/packages/eve/src/public/definitions/callback-context.ts
index 48a4ac156..596ef0a94 100644
--- a/packages/eve/src/public/definitions/callback-context.ts
+++ b/packages/eve/src/public/definitions/callback-context.ts
@@ -1,4 +1,4 @@
-import type { SkillHandle } from "#execution/skills/types.js";
+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";
diff --git a/packages/eve/src/public/definitions/connections/mcp.ts b/packages/eve/src/public/definitions/connections/mcp.ts
index 133ca45bd..b6cc27d27 100644
--- a/packages/eve/src/public/definitions/connections/mcp.ts
+++ b/packages/eve/src/public/definitions/connections/mcp.ts
@@ -2,9 +2,9 @@ import type {
ConnectionAuthDefinition,
HeadersDefinition,
ToolFilterDefinition,
-} from "#runtime/connections/types.js";
+} from "#shared/connection-types.js";
import type { ConnectionToolCallDefinition } from "#public/definitions/connections/tool-call.js";
-import { normalizeAuthorizationSpec } from "#runtime/connections/validate-authorization.js";
+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";
diff --git a/packages/eve/src/public/definitions/connections/openapi.ts b/packages/eve/src/public/definitions/connections/openapi.ts
index 0a97f70f8..bcafeab66 100644
--- a/packages/eve/src/public/definitions/connections/openapi.ts
+++ b/packages/eve/src/public/definitions/connections/openapi.ts
@@ -2,8 +2,8 @@ import type {
ConnectionAuthDefinition,
HeadersDefinition,
ToolFilterDefinition,
-} from "#runtime/connections/types.js";
-import { normalizeAuthorizationSpec } from "#runtime/connections/validate-authorization.js";
+} from "#shared/connection-types.js";
+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";
diff --git a/packages/eve/src/public/definitions/connections/protocol.ts b/packages/eve/src/public/definitions/connections/protocol.ts
index fb319177b..6ad6e8344 100644
--- a/packages/eve/src/public/definitions/connections/protocol.ts
+++ b/packages/eve/src/public/definitions/connections/protocol.ts
@@ -1,4 +1,4 @@
-import type { ConnectionProtocol } from "#runtime/connections/types.js";
+import type { ConnectionProtocol } from "#shared/connection-types.js";
/**
* Cross-instance symbol marking which protocol a connection definition
diff --git a/packages/eve/src/public/definitions/tool.ts b/packages/eve/src/public/definitions/tool.ts
index 9b56184a1..5c4a1bcd2 100644
--- a/packages/eve/src/public/definitions/tool.ts
+++ b/packages/eve/src/public/definitions/tool.ts
@@ -14,7 +14,7 @@ import type {
ConnectionAuthorizationContext,
NonInteractiveAuthorizationDefinition,
TokenResult,
-} from "#runtime/connections/types.js";
+} from "#shared/connection-types.js";
import {
DYNAMIC_SENTINEL_KIND,
TOOL_BRAND,
diff --git a/packages/eve/src/public/instrumentation/provider.ts b/packages/eve/src/public/instrumentation/provider.ts
index 7b154994d..553c75496 100644
--- a/packages/eve/src/public/instrumentation/provider.ts
+++ b/packages/eve/src/public/instrumentation/provider.ts
@@ -1,207 +1 @@
-/**
- * The provider contract authored under `agent/instrumentation/`.
- *
- * Reachable only with `experimental.instrumentationProviders` on. With the flag
- * off nothing discovers that directory, so these types compile but never run.
- */
-
-// Type-only, so nothing couples the public entrypoint to the harness at
-// runtime. The event shapes are eve's own vocabulary; deriving the handler map
-// from the union below is what keeps the public contract from drifting away
-// from the bus that feeds it.
-import type {
- InstrumentationCapture,
- InstrumentationEvent,
-} from "#harness/instrumentation/lifecycle.js";
-import type { JsonValue } from "#public/types/json.js";
-
-export type { JsonValue } from "#public/types/json.js";
-
-export type {
- InstrumentationActionCompletedEvent,
- InstrumentationActionFailedEvent,
- InstrumentationActionKind,
- InstrumentationActionOutcome,
- InstrumentationActionOutput,
- InstrumentationActionStartedEvent,
- InstrumentationAttemptScope,
- InstrumentationCapture,
- InstrumentationChannelDeliveryInput,
- InstrumentationChannelDeliveryOutcome,
- InstrumentationChannelDeliveryRef,
- InstrumentationChannelDeliveryStartedEvent,
- InstrumentationChannelDeliveryTerminalEvent,
- InstrumentationContentPart,
- InstrumentationEvent,
- InstrumentationInputKind,
- InstrumentationInputOption,
- InstrumentationInputOutcome,
- InstrumentationInputRequest,
- InstrumentationInputRequestedEvent,
- InstrumentationInputResolvedEvent,
- InstrumentationInputResponse,
- InstrumentationModelCallCompletedEvent,
- InstrumentationModelCallFailedEvent,
- InstrumentationModelCallStartedEvent,
- InstrumentationModelRef,
- InstrumentationOperationRef,
- InstrumentationParentLineage,
- InstrumentationSessionFailedEvent,
- InstrumentationSessionSettledEvent,
- InstrumentationSessionStartedEvent,
- InstrumentationSessionTransitionEvent,
- InstrumentationStepAttemptMetadataEvent,
- InstrumentationStepAttemptCompletedEvent,
- InstrumentationStepAttemptFailedEvent,
- InstrumentationStepAttemptStartedEvent,
- InstrumentationStepAttemptTerminalEvent,
- InstrumentationToolCallCompletedEvent,
- InstrumentationToolCallFailedEvent,
- InstrumentationToolCallStartedEvent,
- InstrumentationToolOutput,
- InstrumentationTraceContext,
- InstrumentationTurnFailedEvent,
- InstrumentationTurnSettledEvent,
- InstrumentationTurnStartedEvent,
- InstrumentationTurnTerminalEvent,
- InstrumentationUsage,
-} from "#harness/instrumentation/lifecycle.js";
-
-/**
- * Marks a value as having come from `defineInstrumentation` or a built-in
- * factory.
- *
- * It does not say which layout the value belongs to: a provider and a legacy
- * config both carry `events` and `setup`, so no value-level check separates
- * them. The layout decides — `agent/instrumentation.ts` is read as a config and
- * `agent/instrumentation/*.ts` as providers, and the two are mutually exclusive
- * builds. The brand's job is only to catch a default export that never went
- * through eve at all.
- */
-export const PROVIDER = Symbol.for("eve.instrumentation.provider");
-
-/** Marks a slot the author turned off rather than configured. */
-export const DISABLED = Symbol.for("eve.instrumentation.disabled");
-
-/** Where the agent is running when `setup` fires. */
-export type InstrumentationEnvironment = "development" | "preview" | "production";
-
-/** The local eval run this server was started to serve. */
-export interface EvaluationRef {
- readonly runId: string;
-}
-
-/**
- * Passed to {@link InstrumentationProvider.setup} once at server startup,
- * before any event is published.
- */
-export interface ProviderSetupContext {
- /** The agent name declared by `defineAgent`. */
- readonly agentName: string;
- /** Always supplied at runtime; optional for legacy setup-context compatibility. */
- readonly environment?: InstrumentationEnvironment;
- /** Present only when this server was started for a local `eve eval` run. */
- readonly evaluation?: EvaluationRef;
- /** The eve version running the agent. */
- /** Always supplied at runtime; optional for legacy setup-context compatibility. */
- readonly frameworkVersion?: string;
-}
-
-export interface ProviderState {
- get(): JsonValue | undefined;
- /** Stages a JSON value; `undefined` releases this operation's slot. */
- set(value: JsonValue | undefined): void;
-}
-
-export interface ProviderContext {
- readonly state: ProviderState;
-}
-
-/**
- * One event handler.
- *
- * A handler can carry durable JSON state from a start to its terminal through
- * `ctx.state`. eve scopes and releases that state by provider and operation.
- */
-export type Handler<TEvent> = (event: TEvent, ctx: ProviderContext) => void | PromiseLike<void>;
-
-type EventForType<TEvent, TType> = TEvent extends { readonly type: infer TEventType }
- ? TType extends TEventType
- ? TEvent & { readonly type: TType }
- : never
- : never;
-
-/**
- * The events a provider may handle, one optional handler per event type.
- *
- * Derived from the event union rather than written out, so a new event reaches
- * providers the moment the bus can publish it.
- */
-export type ProviderEvents = {
- readonly [TType in InstrumentationEvent["type"]]?: Handler<
- EventForType<InstrumentationEvent, TType>
- >;
-};
-
-/**
- * What an author writes for one file under `agent/instrumentation/`.
- *
- * Setup runs in slot order, but event handlers across authored providers run
- * concurrently and are failure-isolated. Do not coordinate providers through
- * completion order.
- */
-export interface ProviderDefinition {
- /**
- * How much of each event this provider is handed. Defaults to `"metadata"`:
- * structure, identity, usage, and timing, but not what was said.
- *
- * `"content"` adds the prompt, the response, tool arguments, and tool
- * results. Asking is what makes eve build the projection at all, so a
- * directory in which nobody asks never serializes a prompt.
- */
- readonly capture?: InstrumentationCapture;
- readonly events?: ProviderEvents;
- /** Runs once at server startup, before any event is published. */
- readonly setup?: (context: ProviderSetupContext) => void | PromiseLike<void>;
- /** Drains anything buffered. eve calls this before a session goes idle. */
- readonly flush?: () => void | PromiseLike<void>;
- /** Releases resources when the process is going away. */
- readonly shutdown?: () => void | PromiseLike<void>;
-}
-
-/** A {@link ProviderDefinition} that has been through `defineInstrumentation`. */
-export type InstrumentationProvider = ProviderDefinition & {
- readonly [PROVIDER]: true;
-};
-
-/** A slot the author turned off. eve registers nothing for it. */
-export interface InstrumentationDisabled {
- readonly [DISABLED]: true;
-}
-
-/**
- * Turns off the slot the file it is exported from names.
- *
- * Export it as the default of `agent/instrumentation/local.ts` to stop eve
- * spooling local traces, for instance. Omitting the file entirely leaves eve's
- * default in place, which is why turning one off takes a value.
- */
-export function disableInstrumentation(): InstrumentationDisabled {
- return { [DISABLED]: true };
-}
-
-export function isInstrumentationProvider(value: unknown): value is InstrumentationProvider {
- return (
- typeof value === "object" &&
- value !== null &&
- (value as Partial<InstrumentationProvider>)[PROVIDER] === true
- );
-}
-
-export function isInstrumentationDisabled(value: unknown): value is InstrumentationDisabled {
- return (
- typeof value === "object" &&
- value !== null &&
- (value as Partial<InstrumentationDisabled>)[DISABLED] === true
- );
-}
+export * from "#instrumentation/provider.js";
diff --git a/packages/eve/src/public/next/index.integration.test.ts b/packages/eve/src/public/next/index.integration.test.ts
index a4bc5d168..c136bcadf 100644
--- a/packages/eve/src/public/next/index.integration.test.ts
+++ b/packages/eve/src/public/next/index.integration.test.ts
@@ -553,7 +553,7 @@ describe("withEve Vercel config", () => {
vi.stubEnv("NODE_ENV", "development");
vi.stubGlobal(
"fetch",
- vi.fn(async () => new Response(null, { status: 200 })),
+ vi.fn(async () => Response.json({ revision: "rev-1" })),
);
await mkdir(join(resolvedAppRoot, ".eve"), {
recursive: true,
@@ -575,9 +575,10 @@ describe("withEve Vercel config", () => {
const config = await resolveConfig(withEve<TestConfig>({}));
const rewrites = await config.rewrites?.();
- expect(fetch).toHaveBeenCalledWith("http://127.0.0.1:49152/eve/v1/health", {
- signal: expect.any(AbortSignal),
- });
+ expect(fetch).toHaveBeenCalledWith(
+ new URL("/eve/v1/dev/runtime-artifacts", "http://127.0.0.1:49152"),
+ { redirect: "error", signal: expect.any(AbortSignal) },
+ );
expect(getBeforeFiles(rewrites)).toContainEqual({
destination: "http://127.0.0.1:49152/eve/v1/:path+",
source: "/eve/v1/:path+",
diff --git a/packages/eve/src/public/next/server.ts b/packages/eve/src/public/next/server.ts
index bafddc44f..16751f3bf 100644
--- a/packages/eve/src/public/next/server.ts
+++ b/packages/eve/src/public/next/server.ts
@@ -4,12 +4,13 @@ import { mkdir, open, readFile, rm, stat, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { resolvePackageRoot } from "#internal/application/package.js";
-import { EVE_ROUTE_PREFIX } from "#protocol/routes.js";
+import { readDevelopmentRuntimeArtifactsRevision } from "#services/dev-client/runtime-artifacts.js";
const EVE_BASE_URL_ENV = "EVE_BASE_URL";
const DEFAULT_SERVER_READY_TIMEOUT_MS = 180_000;
const DEV_SERVER_REGISTRY_TIMEOUT_MS = 180_000;
const DEV_SERVER_REGISTRY_POLL_MS = 100;
+const DEV_SERVER_READINESS_TIMEOUT_MS = 1_000;
const DEV_SERVER_STALE_LOCK_MS = 30_000;
const EVE_CACHE_DIRECTORY_NAME = ".eve";
const EVE_NEXT_DEV_SERVER_FILE_NAME = "next-dev-server.json";
@@ -49,10 +50,6 @@ function getGlobalState(): EveNextGlobalState {
return globalWithState[globalStateSymbol];
}
-function joinRoutePrefix(prefix: string, path: string): string {
- return `${prefix.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`;
-}
-
function normalizeOrigin(origin: string): string {
return new URL(origin).origin;
}
@@ -120,25 +117,6 @@ function normalizeDevServerRegistry(value: unknown): EveDevServerRegistry | unde
}
}
-async function isEveServerHealthy(origin: string): Promise<boolean> {
- const controller = new AbortController();
- const timeout = setTimeout(() => {
- controller.abort();
- }, 1_000);
-
- try {
- const response = await fetch(joinRoutePrefix(origin, `${EVE_ROUTE_PREFIX}/health`), {
- signal: controller.signal,
- });
-
- return response.ok;
- } catch {
- return false;
- } finally {
- clearTimeout(timeout);
- }
-}
-
async function readUsableEveDevServerRegistry(appRoot: string): Promise<string | undefined> {
try {
const registry = normalizeDevServerRegistry(
@@ -149,7 +127,12 @@ async function readUsableEveDevServerRegistry(appRoot: string): Promise<string |
return undefined;
}
- if (!(await isEveServerHealthy(registry.origin))) {
+ if (
+ (await readDevelopmentRuntimeArtifactsRevision({
+ serverUrl: registry.origin,
+ timeoutMs: DEV_SERVER_READINESS_TIMEOUT_MS,
+ })) === undefined
+ ) {
return undefined;
}
diff --git a/packages/eve/src/public/nuxt/dev-server.integration.test.ts b/packages/eve/src/public/nuxt/dev-server.integration.test.ts
index 1c371c91e..e3896c4ee 100644
--- a/packages/eve/src/public/nuxt/dev-server.integration.test.ts
+++ b/packages/eve/src/public/nuxt/dev-server.integration.test.ts
@@ -25,9 +25,9 @@ afterEach(() => {
});
describe("resolveSharedEveDevServer", () => {
- it("reuses a healthy registered server instead of spawning", async () => {
+ it("reuses a ready registered server instead of spawning", async () => {
const appRoot = await createTempAppRoot();
- const fetchMock = vi.fn(async () => new Response(null, { status: 200 }));
+ const fetchMock = vi.fn(async () => Response.json({ revision: "rev-1" }));
vi.stubGlobal("fetch", fetchMock);
await writeRegistry(appRoot, {
@@ -42,8 +42,9 @@ describe("resolveSharedEveDevServer", () => {
expect(handle).toEqual({ origin: "http://127.0.0.1:49152" });
expect(handle.process).toBeUndefined();
expect(process.env[EVE_BASE_URL_ENV]).toBe("http://127.0.0.1:49152");
- expect(fetchMock).toHaveBeenCalledWith("http://127.0.0.1:49152/eve/v1/health", {
- signal: expect.any(AbortSignal),
- });
+ expect(fetchMock).toHaveBeenCalledWith(
+ new URL("/eve/v1/dev/runtime-artifacts", "http://127.0.0.1:49152"),
+ { redirect: "error", signal: expect.any(AbortSignal) },
+ );
});
});
diff --git a/packages/eve/src/public/nuxt/dev-server.ts b/packages/eve/src/public/nuxt/dev-server.ts
index e0d78cb4a..17abb633c 100644
--- a/packages/eve/src/public/nuxt/dev-server.ts
+++ b/packages/eve/src/public/nuxt/dev-server.ts
@@ -3,15 +3,16 @@ import { mkdir, open, readFile, rm, stat, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { resolvePackageRoot } from "#internal/application/package.js";
-import { EVE_ROUTE_PREFIX } from "#protocol/routes.js";
+import { readDevelopmentRuntimeArtifactsRevision } from "#services/dev-client/runtime-artifacts.js";
-import { joinRoutePrefix, normalizeOrigin } from "./routing.js";
+import { normalizeOrigin } from "./routing.js";
export const EVE_BASE_URL_ENV = "EVE_BASE_URL";
const DEFAULT_SERVER_READY_TIMEOUT_MS = 30_000;
const DEV_SERVER_REGISTRY_TIMEOUT_MS = 30_000;
const DEV_SERVER_REGISTRY_POLL_MS = 100;
+const DEV_SERVER_READINESS_TIMEOUT_MS = 1_000;
const DEV_SERVER_STALE_LOCK_MS = 30_000;
const EVE_CACHE_DIRECTORY_NAME = ".eve";
const EVE_NUXT_DEV_SERVER_FILE_NAME = "nuxt-dev-server.json";
@@ -80,28 +81,19 @@ export function normalizeDevServerRegistry(value: unknown): EveDevServerRegistry
}
}
-async function isEveServerHealthy(origin: string): Promise<boolean> {
- const controller = new AbortController();
- const timeout = setTimeout(() => controller.abort(), 1_000);
- try {
- const response = await fetch(joinRoutePrefix(origin, `${EVE_ROUTE_PREFIX}/health`), {
- signal: controller.signal,
- });
- return response.ok;
- } catch {
- return false;
- } finally {
- clearTimeout(timeout);
- }
-}
-
async function readUsableEveDevServerRegistry(appRoot: string): Promise<string | undefined> {
try {
const registry = normalizeDevServerRegistry(
JSON.parse(await readFile(resolveEveDevServerRegistryPath(appRoot), "utf8")) as unknown,
);
if (registry === undefined || registry.appRoot !== appRoot) return undefined;
- if (!(await isEveServerHealthy(registry.origin))) return undefined;
+ if (
+ (await readDevelopmentRuntimeArtifactsRevision({
+ serverUrl: registry.origin,
+ timeoutMs: DEV_SERVER_READINESS_TIMEOUT_MS,
+ })) === undefined
+ )
+ return undefined;
return registry.origin;
} catch (error) {
if (isNodeErrorWithCode(error, "ENOENT")) return undefined;
diff --git a/packages/eve/src/public/sandbox/backends/default.ts b/packages/eve/src/public/sandbox/backends/default.ts
index 54ef9faea..1ee3b252d 100644
--- a/packages/eve/src/public/sandbox/backends/default.ts
+++ b/packages/eve/src/public/sandbox/backends/default.ts
@@ -1,88 +1 @@
-import {
- isLinuxDockerDaemonAvailableSync,
- isMicrosandboxPlatformSupported,
-} from "#execution/sandbox/bindings/local.js";
-import { lazyBackend } from "#execution/sandbox/lazy-backend.js";
-import type { SandboxBackend } from "#public/definitions/sandbox-backend.js";
-import { docker } from "#public/sandbox/backends/docker.js";
-import type { DockerSandboxCreateOptions } from "#public/sandbox/docker-sandbox.js";
-import { justbash } from "#public/sandbox/backends/just-bash.js";
-import type { JustBashSandboxCreateOptions } from "#public/sandbox/just-bash-sandbox.js";
-import { microsandbox } from "#public/sandbox/backends/microsandbox.js";
-import type { MicrosandboxSandboxCreateOptions } from "#public/sandbox/microsandbox-sandbox.js";
-import { vercel } from "#public/sandbox/backends/vercel.js";
-import type { VercelSandboxCreateOptions } from "#public/sandbox/vercel-sandbox.js";
-
-/**
- * Input to {@link defaultSandbox}: a separate options bag per inner
- * backend. The framework picks one backend at runtime based on
- * availability and passes it the matching bag; the others are ignored.
- */
-export interface DefaultSandboxOptions {
- readonly docker?: DockerSandboxCreateOptions;
- readonly justBash?: JustBashSandboxCreateOptions;
- readonly microsandbox?: MicrosandboxSandboxCreateOptions;
- readonly vercel?: VercelSandboxCreateOptions;
-}
-
-/**
- * Availability probes behind {@link defaultSandbox}'s selection chain.
- * Injectable so selection logic is testable without touching the host.
- */
-export interface DefaultSandboxProbes {
- readonly isDeployedOnVercel: () => boolean;
- readonly isDockerAvailable: () => boolean;
- readonly isMicrosandboxSupported: () => boolean;
-}
-
-// Wrapped in arrows (not captured by reference) deliberately: this
-// module participates in an import cycle through the runtime resolver,
-// so the probe imports may still be uninitialized live bindings when
-// this object literal evaluates. Accessing them at call time is safe.
-const PRODUCTION_PROBES: DefaultSandboxProbes = {
- isDeployedOnVercel: () => Boolean(process.env.VERCEL),
- isDockerAvailable: () => isLinuxDockerDaemonAvailableSync(),
- isMicrosandboxSupported: () => isMicrosandboxPlatformSupported(),
-};
-
-/**
- * Constructs an availability-aware sandbox backend. On first use it
- * picks the best backend the host supports, in priority order:
- *
- * 1. **Vercel Sandbox** when deploying on Vercel (`process.env.VERCEL`
- * is set) — local container/VM runtimes cannot run there.
- * 2. **Docker** when a Linux-container Docker daemon is reachable.
- * 3. **microsandbox** when the host supports it (macOS on Apple
- * Silicon, or glibc Linux with KVM); `eve dev` auto-installs the
- * package into the project.
- * 4. **just-bash** as the dependency-free fallback; `eve dev`
- * auto-installs the package into the project.
- *
- * The selection is cached for the process lifetime. To pin a backend
- * unconditionally, configure its factory directly (`docker()`,
- * `microsandbox()`, `justbash()`,
- * `vercel()`).
- */
-export function defaultSandbox(opts?: DefaultSandboxOptions): SandboxBackend {
- return lazyBackend(() => selectDefaultSandbox(opts, PRODUCTION_PROBES));
-}
-
-/**
- * The selection chain behind {@link defaultSandbox}. Internal —
- * exported for tests, which inject probes.
- */
-export function selectDefaultSandbox(
- opts: DefaultSandboxOptions | undefined,
- probes: DefaultSandboxProbes,
-): SandboxBackend {
- if (probes.isDeployedOnVercel()) {
- return vercel(opts?.vercel);
- }
- if (probes.isDockerAvailable()) {
- return docker(opts?.docker);
- }
- if (probes.isMicrosandboxSupported()) {
- return microsandbox(opts?.microsandbox);
- }
- return justbash(opts?.justBash);
-}
+export * from "#sandbox/backends/default.js";
diff --git a/packages/eve/src/public/sandbox/backends/docker.ts b/packages/eve/src/public/sandbox/backends/docker.ts
index 967b33480..42e38faeb 100644
--- a/packages/eve/src/public/sandbox/backends/docker.ts
+++ b/packages/eve/src/public/sandbox/backends/docker.ts
@@ -1,18 +1 @@
-import { createDockerSandboxBackend } from "#execution/sandbox/bindings/local.js";
-import type { SandboxBackend } from "#public/definitions/sandbox-backend.js";
-import type { DockerSandboxCreateOptions } from "#public/sandbox/docker-sandbox.js";
-
-/**
- * Constructs the Docker sandbox backend: the workspace runs inside a
- * real Linux container driven through the Docker CLI, using the
- * official Ubuntu 26.04 image by default.
- *
- * Requires a running Docker-compatible daemon reachable through a
- * `docker` CLI (Docker Desktop, OrbStack, Colima, Podman via its
- * docker-compatible CLI, …; override the binary with `EVE_DOCKER_PATH`).
- * Configuring this backend pins it unconditionally — when you want
- * fallback behavior, use `defaultBackend()` instead.
- */
-export function docker(opts?: DockerSandboxCreateOptions): SandboxBackend {
- return createDockerSandboxBackend({ createOptions: opts });
-}
+export * from "#sandbox/backends/docker.js";
diff --git a/packages/eve/src/public/sandbox/backends/just-bash.ts b/packages/eve/src/public/sandbox/backends/just-bash.ts
index 3a93d9e4a..b49338eba 100644
--- a/packages/eve/src/public/sandbox/backends/just-bash.ts
+++ b/packages/eve/src/public/sandbox/backends/just-bash.ts
@@ -1,21 +1 @@
-import { createJustBashSandboxBackend } from "#execution/sandbox/bindings/local.js";
-import type { SandboxBackend } from "#public/definitions/sandbox-backend.js";
-import type { JustBashSandboxCreateOptions } from "#public/sandbox/just-bash-sandbox.js";
-
-/**
- * Constructs the just-bash sandbox backend: a pure-JS bash interpreter
- * over a virtual filesystem stored under `.eve/sandbox-cache/`. It
- * needs no daemon or VM, but commands run in a simulated shell — no
- * real binaries (`git`, `node`, package managers) and no network
- * isolation.
- *
- * The `just-bash` package is not bundled with eve. When it is missing,
- * `eve dev` installs it into the application automatically (disable
- * with `autoInstall: false`); production processes fail with an
- * actionable install error instead. Configuring this backend pins it
- * unconditionally — when you want fallback behavior, use
- * `defaultBackend()` instead.
- */
-export function justbash(opts?: JustBashSandboxCreateOptions): SandboxBackend {
- return createJustBashSandboxBackend({ createOptions: opts });
-}
+export * from "#sandbox/backends/just-bash.js";
diff --git a/packages/eve/src/public/sandbox/backends/microsandbox.ts b/packages/eve/src/public/sandbox/backends/microsandbox.ts
index 31fd8cc5b..24940ec8f 100644
--- a/packages/eve/src/public/sandbox/backends/microsandbox.ts
+++ b/packages/eve/src/public/sandbox/backends/microsandbox.ts
@@ -1,27 +1 @@
-import { createMicrosandboxSandboxBackend } from "#execution/sandbox/bindings/local.js";
-import type { SandboxBackend } from "#public/definitions/sandbox-backend.js";
-import type {
- MicrosandboxBootstrapUseOptions,
- MicrosandboxSandboxCreateOptions,
- MicrosandboxSessionUseOptions,
-} from "#public/sandbox/microsandbox-sandbox.js";
-
-/**
- * Constructs the microsandbox sandbox backend: lightweight local VMs
- * via [microsandbox](https://www.npmjs.com/package/microsandbox) with
- * snapshot-backed templates and a firewall capable of domain-level
- * network policies and credential brokering.
- *
- * Supported hosts: macOS on Apple Silicon, or Linux (glibc) with KVM
- * enabled. The `microsandbox` package is not bundled with eve. When it
- * (or its VM runtime) is missing, `eve dev` installs both
- * automatically (disable with `setup: { autoInstall: false }`);
- * production processes fail with actionable errors instead.
- * Configuring this backend pins it unconditionally — when you want
- * fallback behavior, use `defaultBackend()` instead.
- */
-export function microsandbox(
- opts?: MicrosandboxSandboxCreateOptions,
-): SandboxBackend<MicrosandboxBootstrapUseOptions, MicrosandboxSessionUseOptions> {
- return createMicrosandboxSandboxBackend({ createOptions: opts });
-}
+export * from "#sandbox/backends/microsandbox.js";
diff --git a/packages/eve/src/public/sandbox/backends/vercel.ts b/packages/eve/src/public/sandbox/backends/vercel.ts
index 717f19bb7..63a1b231a 100644
--- a/packages/eve/src/public/sandbox/backends/vercel.ts
+++ b/packages/eve/src/public/sandbox/backends/vercel.ts
@@ -1,44 +1 @@
-import { createVercelSandbox } from "#execution/sandbox/bindings/vercel.js";
-import type { SandboxBackend } from "#public/definitions/sandbox-backend.js";
-import type {
- VercelSandboxBootstrapUseOptions,
- VercelSandboxOptions,
- VercelSandboxSessionUseOptions,
-} from "#public/sandbox/vercel-sandbox.js";
-
-/**
- * Constructs the [Vercel Sandbox](https://vercel.com/docs/sandbox)
- * backend. Configuring this backend pins it unconditionally —
- * including for local development, where it creates real hosted
- * sandboxes (requires Vercel credentials).
- *
- * The optional provider creation fields are forwarded to Vercel Sandbox creation
- * for every fresh sandbox the framework creates (template at prewarm,
- * session at first-time create). On resume (`Sandbox.get`), no create
- * happens, so opts are not re-applied. `networkPolicy` is applied after
- * framework-owned base setup for fresh templates and template-less
- * sessions, before authored bootstrap code runs.
- *
- * `opts.source`, if supplied, is used only on the template create:
- * the author's snapshot, git revision, or tarball becomes the base
- * layer of the template. Bootstrap, seed files, and framework setup
- * still run on top, and every session derives from the resulting
- * eve-owned snapshot. `source` is stripped from session creates so the
- * framework's snapshot always wins.
- *
- * `bootstrap({ use })` applies its options to the template via
- * `sandbox.update(...)`; those settings persist into the snapshot.
- * `onSession({ use })` applies its options to the live session via the
- * SDK's `update` under the hood, overriding any overlapping field
- * from `opts`. `sessionCreateOptions`, when provided, is resolved only
- * when creating a fresh live session and can attach session-specific Drives.
- */
-export function vercel(
- opts?: VercelSandboxOptions,
-): SandboxBackend<VercelSandboxBootstrapUseOptions, VercelSandboxSessionUseOptions> {
- const { sessionCreateOptions, ...createOptions } = opts ?? {};
- return createVercelSandbox({
- createOptions,
- resolveSessionCreateOptions: sessionCreateOptions,
- });
-}
+export * from "#sandbox/backends/vercel.js";
diff --git a/packages/eve/src/public/skills/index.ts b/packages/eve/src/public/skills/index.ts
index 2b6f078a7..4e2224a75 100644
--- a/packages/eve/src/public/skills/index.ts
+++ b/packages/eve/src/public/skills/index.ts
@@ -2,7 +2,7 @@
* Skill authoring helpers and runtime accessors.
*/
-export type { SkillFile, SkillHandle } from "#execution/skills/types.js";
+export type { SkillFile, SkillHandle } from "#shared/skill-types.js";
export {
defineSkill,
type NamedSkillDefinition,
diff --git a/packages/eve/src/public/sveltekit/dev-server.integration.test.ts b/packages/eve/src/public/sveltekit/dev-server.integration.test.ts
index 231b21ba6..00ed8d6e6 100644
--- a/packages/eve/src/public/sveltekit/dev-server.integration.test.ts
+++ b/packages/eve/src/public/sveltekit/dev-server.integration.test.ts
@@ -25,9 +25,9 @@ afterEach(() => {
});
describe("resolveSharedEveDevServer", () => {
- it("reuses a healthy registered server instead of spawning", async () => {
+ it("reuses a ready registered server instead of spawning", async () => {
const appRoot = await createTempAppRoot();
- const fetchMock = vi.fn(async () => new Response(null, { status: 200 }));
+ const fetchMock = vi.fn(async () => Response.json({ revision: "rev-1" }));
vi.stubGlobal("fetch", fetchMock);
await writeRegistry(appRoot, {
@@ -42,8 +42,9 @@ describe("resolveSharedEveDevServer", () => {
expect(handle).toEqual({ origin: "http://127.0.0.1:49152" });
expect(handle.process).toBeUndefined();
expect(process.env[EVE_BASE_URL_ENV]).toBe("http://127.0.0.1:49152");
- expect(fetchMock).toHaveBeenCalledWith("http://127.0.0.1:49152/eve/v1/health", {
- signal: expect.any(AbortSignal),
- });
+ expect(fetchMock).toHaveBeenCalledWith(
+ new URL("/eve/v1/dev/runtime-artifacts", "http://127.0.0.1:49152"),
+ { redirect: "error", signal: expect.any(AbortSignal) },
+ );
});
});
diff --git a/packages/eve/src/public/sveltekit/dev-server.ts b/packages/eve/src/public/sveltekit/dev-server.ts
index 3c8c2376c..135f463f2 100644
--- a/packages/eve/src/public/sveltekit/dev-server.ts
+++ b/packages/eve/src/public/sveltekit/dev-server.ts
@@ -3,15 +3,16 @@ import { mkdir, open, readFile, rm, stat, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { resolvePackageRoot } from "#internal/application/package.js";
-import { EVE_ROUTE_PREFIX } from "#protocol/routes.js";
+import { readDevelopmentRuntimeArtifactsRevision } from "#services/dev-client/runtime-artifacts.js";
-import { joinRoutePrefix, normalizeOrigin } from "./routing.js";
+import { normalizeOrigin } from "./routing.js";
export const EVE_BASE_URL_ENV = "EVE_BASE_URL";
const DEFAULT_SERVER_READY_TIMEOUT_MS = 30_000;
const DEV_SERVER_REGISTRY_TIMEOUT_MS = 30_000;
const DEV_SERVER_REGISTRY_POLL_MS = 100;
+const DEV_SERVER_READINESS_TIMEOUT_MS = 1_000;
const DEV_SERVER_STALE_LOCK_MS = 30_000;
const EVE_CACHE_DIRECTORY_NAME = ".eve";
const EVE_SVELTEKIT_DEV_SERVER_FILE_NAME = "sveltekit-dev-server.json";
@@ -80,28 +81,19 @@ export function normalizeDevServerRegistry(value: unknown): EveDevServerRegistry
}
}
-async function isEveServerHealthy(origin: string): Promise<boolean> {
- const controller = new AbortController();
- const timeout = setTimeout(() => controller.abort(), 1_000);
- try {
- const response = await fetch(joinRoutePrefix(origin, `${EVE_ROUTE_PREFIX}/health`), {
- signal: controller.signal,
- });
- return response.ok;
- } catch {
- return false;
- } finally {
- clearTimeout(timeout);
- }
-}
-
async function readUsableEveDevServerRegistry(appRoot: string): Promise<string | undefined> {
try {
const registry = normalizeDevServerRegistry(
JSON.parse(await readFile(resolveEveDevServerRegistryPath(appRoot), "utf8")) as unknown,
);
if (registry === undefined || registry.appRoot !== appRoot) return undefined;
- if (!(await isEveServerHealthy(registry.origin))) return undefined;
+ if (
+ (await readDevelopmentRuntimeArtifactsRevision({
+ serverUrl: registry.origin,
+ timeoutMs: DEV_SERVER_READINESS_TIMEOUT_MS,
+ })) === undefined
+ )
+ return undefined;
return registry.origin;
} catch (error) {
if (isNodeErrorWithCode(error, "ENOENT")) return undefined;
diff --git a/packages/eve/src/public/tool-result-narrowing.test.ts b/packages/eve/src/public/tool-result-narrowing.test.ts
index 44b513bba..dcbf62712 100644
--- a/packages/eve/src/public/tool-result-narrowing.test.ts
+++ b/packages/eve/src/public/tool-result-narrowing.test.ts
@@ -1,7 +1,7 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { z } from "#compiled/zod/index.js";
-import type { RuntimeActionResult } from "#runtime/actions/types.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 {
diff --git a/packages/eve/src/public/tool-result-narrowing.ts b/packages/eve/src/public/tool-result-narrowing.ts
index af72d5422..2f7d41eb6 100644
--- a/packages/eve/src/public/tool-result-narrowing.ts
+++ b/packages/eve/src/public/tool-result-narrowing.ts
@@ -1,4 +1,4 @@
-import type { RuntimeActionResult } from "#runtime/actions/types.js";
+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";
diff --git a/packages/eve/src/public/tools/agent.ts b/packages/eve/src/public/tools/agent.ts
new file mode 100644
index 000000000..17fe8ece0
--- /dev/null
+++ b/packages/eve/src/public/tools/agent.ts
@@ -0,0 +1,13 @@
+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/runtime/framework-tools/ask-question.test.ts b/packages/eve/src/public/tools/ask-question.test.ts
similarity index 88%
rename from packages/eve/src/runtime/framework-tools/ask-question.test.ts
rename to packages/eve/src/public/tools/ask-question.test.ts
index 571f9afd0..6919c3842 100644
--- a/packages/eve/src/runtime/framework-tools/ask-question.test.ts
+++ b/packages/eve/src/public/tools/ask-question.test.ts
@@ -1,9 +1,6 @@
import { describe, expect, it } from "vitest";
-import {
- ASK_QUESTION_INPUT_SCHEMA,
- ASK_QUESTION_TOOL_DEFINITION,
-} from "#runtime/framework-tools/ask-question.js";
+import { ASK_QUESTION_INPUT_SCHEMA, askQuestion } from "#public/tools/ask-question.js";
import { serializeInputSchema } from "#shared/tool-schema.js";
describe("ASK_QUESTION_INPUT_SCHEMA", () => {
@@ -52,6 +49,6 @@ describe("ASK_QUESTION_INPUT_SCHEMA", () => {
required: ["prompt"],
type: "object",
});
- expect(ASK_QUESTION_TOOL_DEFINITION.inputSchema).toBe(ASK_QUESTION_INPUT_SCHEMA);
+ expect(askQuestion.inputSchema).toBe(ASK_QUESTION_INPUT_SCHEMA);
});
});
diff --git a/packages/eve/src/public/tools/ask-question.ts b/packages/eve/src/public/tools/ask-question.ts
new file mode 100644
index 000000000..7a5935e5d
--- /dev/null
+++ b/packages/eve/src/public/tools/ask-question.ts
@@ -0,0 +1,30 @@
+import { z } from "#compiled/zod/index.js";
+import { defineTool } from "#public/definitions/tool.js";
+import { inputRequestSchema } from "#shared/input.js";
+
+export const ASK_QUESTION_INPUT_SCHEMA = inputRequestSchema.omit({
+ action: true,
+ display: true,
+ kind: true,
+ requestId: true,
+});
+export const ASK_QUESTION_OUTPUT_SCHEMA = z
+ .object({
+ optionId: z.string().optional(),
+ status: z.enum(["answered", "ignored"]),
+ text: z.string().optional(),
+ })
+ .strict();
+
+/** Canonical PR 1 source definition; durable execution remains in the harness. */
+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.",
+ inputSchema: ASK_QUESTION_INPUT_SCHEMA,
+ outputSchema: ASK_QUESTION_OUTPUT_SCHEMA,
+ execute() {
+ throw new Error("ask_question is handled by eve's durable input dispatcher.");
+ },
+});
+
+export default askQuestion;
diff --git a/packages/eve/src/public/tools/bash.ts b/packages/eve/src/public/tools/bash.ts
new file mode 100644
index 000000000..458822281
--- /dev/null
+++ b/packages/eve/src/public/tools/bash.ts
@@ -0,0 +1,2 @@
+export { default } from "#tools/bash.js";
+export * from "#tools/bash.js";
diff --git a/packages/eve/src/public/tools/connection-search.ts b/packages/eve/src/public/tools/connection-search.ts
new file mode 100644
index 000000000..51345e200
--- /dev/null
+++ b/packages/eve/src/public/tools/connection-search.ts
@@ -0,0 +1,2 @@
+export { default } from "#tools/connection-search.js";
+export * from "#tools/connection-search.js";
diff --git a/packages/eve/src/public/tools/defaults.ts b/packages/eve/src/public/tools/defaults.ts
deleted file mode 100644
index 137ef4042..000000000
--- a/packages/eve/src/public/tools/defaults.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-/**
- * Framework-provided tool definitions exposed as plain {@link ToolDefinition}
- * values so authors can spread, wrap, or patch them inside their own
- * `agent/tools/*.ts` files.
- */
-import { BASH_TOOL_DEFINITION } from "#runtime/framework-tools/bash.js";
-import { GLOB_TOOL_DEFINITION } from "#runtime/framework-tools/glob.js";
-import { GREP_TOOL_DEFINITION } from "#runtime/framework-tools/grep.js";
-import { READ_FILE_TOOL_DEFINITION } from "#runtime/framework-tools/read-file.js";
-import { SKILL_TOOL_DEFINITION } from "#runtime/framework-tools/skill.js";
-import { TODO_TOOL_DEFINITION } from "#runtime/framework-tools/todo.js";
-import { WEB_FETCH_TOOL_DEFINITION } from "#runtime/framework-tools/web-fetch.js";
-import { WRITE_FILE_TOOL_DEFINITION } from "#runtime/framework-tools/write-file.js";
-import type { ToolDefinition } from "#public/definitions/tool.js";
-import { toPublicToolDefinition } from "#public/tools/internal.js";
-
-export type { ToolDefinition };
-
-/**
- * Framework-provided shell execution tool. Spread or wrap to customize.
- */
-export const bash: ToolDefinition = toPublicToolDefinition(BASH_TOOL_DEFINITION);
-
-/**
- * Framework-provided file search tool. Finds files by glob pattern. Spread
- * or wrap to customize.
- */
-export const glob: ToolDefinition = toPublicToolDefinition(GLOB_TOOL_DEFINITION);
-
-/**
- * Framework-provided content search tool. Searches file contents by regex
- * pattern. Spread or wrap to customize.
- */
-export const grep: ToolDefinition = toPublicToolDefinition(GREP_TOOL_DEFINITION);
-
-/**
- * Framework-provided file reader tool (`read_file`). Spread or wrap to
- * customize. The framework resets the durable read-before-write stamps on
- * context compaction automatically, regardless of how the reader is defined.
- */
-export const readFile: ToolDefinition = toPublicToolDefinition(READ_FILE_TOOL_DEFINITION);
-
-/**
- * Framework-provided file writer tool. Spread or wrap to customize.
- * Enforces read-before-write for existing files and stale-read detection.
- */
-export const writeFile: ToolDefinition = toPublicToolDefinition(WRITE_FILE_TOOL_DEFINITION);
-
-/**
- * Framework-provided HTTP fetch tool. Spread or wrap to customize.
- */
-export const webFetch: ToolDefinition = toPublicToolDefinition(WEB_FETCH_TOOL_DEFINITION);
-
-/**
- * Framework-provided durable todo list tool. Spreading the default keeps its
- * closure-bound state behavior: the executor still reads and writes the
- * framework's internal todo state. Replace with a fully custom executor (and
- * your own `ContextKey`) if you need different state semantics.
- */
-export const todo: ToolDefinition = toPublicToolDefinition(TODO_TOOL_DEFINITION);
-
-/**
- * Framework-provided skill loading tool (`load_skill`). Returns a named
- * authored skill's instructions directly; dynamic skills remain sandbox-backed.
- * It is only useful when the agent declares skills: with no skills available the
- * framework does not surface skill descriptions to the model, so the model has
- * nothing to load.
- */
-export const loadSkill: ToolDefinition = toPublicToolDefinition(SKILL_TOOL_DEFINITION);
diff --git a/packages/eve/src/public/tools/define-bash-tool.ts b/packages/eve/src/public/tools/define-bash-tool.ts
index b30c10c83..160f4237f 100644
--- a/packages/eve/src/public/tools/define-bash-tool.ts
+++ b/packages/eve/src/public/tools/define-bash-tool.ts
@@ -1,34 +1 @@
-import { type BashInput, executeBashOnSandbox } from "#execution/sandbox/bash-tool.js";
-import { BASH_INPUT_SCHEMA, BASH_OUTPUT_SCHEMA } from "#runtime/framework-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,
- };
-}
+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.ts
index 31969527c..b7d86a316 100644
--- a/packages/eve/src/public/tools/define-glob-tool.ts
+++ b/packages/eve/src/public/tools/define-glob-tool.ts
@@ -1,35 +1 @@
-import { executeGlobOnSandbox, type GlobInput } from "#execution/sandbox/glob-tool.js";
-import { GLOB_INPUT_SCHEMA, GLOB_OUTPUT_SCHEMA } from "#runtime/framework-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,
- };
-}
+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.ts
index e3f435c2b..b44a6e26b 100644
--- a/packages/eve/src/public/tools/define-grep-tool.ts
+++ b/packages/eve/src/public/tools/define-grep-tool.ts
@@ -1,35 +1 @@
-import { executeGrepOnSandbox, type GrepInput } from "#execution/sandbox/grep-tool.js";
-import { GREP_INPUT_SCHEMA, GREP_OUTPUT_SCHEMA } from "#runtime/framework-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,
- };
-}
+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.ts
index 718ab8773..13de98acb 100644
--- a/packages/eve/src/public/tools/define-read-file-tool.ts
+++ b/packages/eve/src/public/tools/define-read-file-tool.ts
@@ -1,37 +1 @@
-import { executeReadFileOnSandbox, type ReadFileInput } from "#execution/sandbox/read-file-tool.js";
-import {
- READ_FILE_INPUT_SCHEMA,
- READ_FILE_OUTPUT_SCHEMA,
-} from "#runtime/framework-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,
- };
-}
+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.ts
index e4e56444b..f80e01040 100644
--- a/packages/eve/src/public/tools/define-write-file-tool.ts
+++ b/packages/eve/src/public/tools/define-write-file-tool.ts
@@ -1,41 +1 @@
-import {
- executeWriteFileOnSandbox,
- type WriteFileInput,
-} from "#execution/sandbox/write-file-tool.js";
-import {
- WRITE_FILE_INPUT_SCHEMA,
- WRITE_FILE_OUTPUT_SCHEMA,
-} from "#runtime/framework-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,
- };
-}
+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.ts
new file mode 100644
index 000000000..277304d60
--- /dev/null
+++ b/packages/eve/src/public/tools/glob.ts
@@ -0,0 +1,2 @@
+export { default } from "#tools/glob.js";
+export * from "#tools/glob.js";
diff --git a/packages/eve/src/public/tools/grep.ts b/packages/eve/src/public/tools/grep.ts
new file mode 100644
index 000000000..e4b0743fc
--- /dev/null
+++ b/packages/eve/src/public/tools/grep.ts
@@ -0,0 +1,2 @@
+export { default } from "#tools/grep.js";
+export * from "#tools/grep.js";
diff --git a/packages/eve/src/public/tools/internal.ts b/packages/eve/src/public/tools/internal.ts
deleted file mode 100644
index 46a4e222b..000000000
--- a/packages/eve/src/public/tools/internal.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import type { ResolvedToolDefinition } from "#runtime/types.js";
-import type { ToolDefinition } from "#public/definitions/tool.js";
-
-/**
- * Converter that strips internal identity fields from a framework
- * {@link ResolvedToolDefinition} so it can be re-exported as a public
- * {@link ToolDefinition}.
- *
- * Framework tools have the internal `(input, options) => output` signature.
- * The public {@link ToolDefinition.execute} expects `(input, ctx)`.
- * This wrapper bridges the gap — the public `ctx` is mapped back onto the
- * internal execute options.
- */
-export function toPublicToolDefinition(definition: ResolvedToolDefinition): ToolDefinition {
- if (!definition.execute) {
- throw new Error(`Tool "${definition.name}" is client-side and cannot be re-exported publicly.`);
- }
-
- const internalExecute = definition.execute;
- const publicDefinition: ToolDefinition = {
- description: definition.description,
- execute: (input, ctx) =>
- internalExecute(input, {
- abortSignal: ctx.abortSignal,
- // The public context carries no model history, so the bridged
- // options cannot reproduce the AI SDK's `messages`.
- messages: [],
- toolCallId: ctx.callId,
- }),
- inputSchema: definition.inputSchema ?? {},
- outputSchema: definition.outputSchema,
- };
-
- if (definition.approval !== undefined) {
- publicDefinition.approval = definition.approval;
- }
-
- return publicDefinition;
-}
diff --git a/packages/eve/src/public/tools/load-skill.ts b/packages/eve/src/public/tools/load-skill.ts
new file mode 100644
index 000000000..9d35f74e9
--- /dev/null
+++ b/packages/eve/src/public/tools/load-skill.ts
@@ -0,0 +1,2 @@
+export { default } from "#tools/load-skill.js";
+export * from "#tools/load-skill.js";
diff --git a/packages/eve/src/public/tools/read-file.ts b/packages/eve/src/public/tools/read-file.ts
new file mode 100644
index 000000000..bd05bdd50
--- /dev/null
+++ b/packages/eve/src/public/tools/read-file.ts
@@ -0,0 +1,2 @@
+export { default } from "#tools/read-file.js";
+export * from "#tools/read-file.js";
diff --git a/packages/eve/src/public/tools/sleep/index.ts b/packages/eve/src/public/tools/sleep/index.ts
index d11fc1642..52867824a 100644
--- a/packages/eve/src/public/tools/sleep/index.ts
+++ b/packages/eve/src/public/tools/sleep/index.ts
@@ -1,34 +1 @@
-import { defineTool, type ToolDefinition } from "#public/definitions/tool.js";
-import {
- executeSleepTool,
- SLEEP_INPUT_SCHEMA,
- SLEEP_OUTPUT_SCHEMA,
- SLEEP_TOOL_DESCRIPTION,
- type SleepToolInput,
- type SleepToolOutput,
-} from "#runtime/framework-tools/sleep.js";
-
-export type { SleepToolInput, SleepToolOutput };
-
-/**
- * Defines eve's opt-in durable `sleep` tool.
- *
- * Export it from `agent/tools/sleep.ts`:
- *
- * ```ts
- * import { sleep } from "eve/tools/sleep";
- *
- * export default sleep();
- * ```
- *
- * Calls pause the durable turn workflow rather than holding an application
- * runtime open with an in-process timer.
- */
-export function sleep(): ToolDefinition<SleepToolInput, SleepToolOutput> {
- return defineTool({
- description: SLEEP_TOOL_DESCRIPTION,
- execute: executeSleepTool,
- inputSchema: SLEEP_INPUT_SCHEMA,
- outputSchema: SLEEP_OUTPUT_SCHEMA,
- });
-}
+export * from "#tools/sleep.js";
diff --git a/packages/eve/src/public/tools/task-cancel.ts b/packages/eve/src/public/tools/task-cancel.ts
new file mode 100644
index 000000000..54f4f6334
--- /dev/null
+++ b/packages/eve/src/public/tools/task-cancel.ts
@@ -0,0 +1,15 @@
+import { defineTool } from "#public/definitions/tool.js";
+import { TASK_CANCEL_INPUT_SCHEMA, TASK_VIEWS_OUTPUT_SCHEMA } from "#shared/task-tool.js";
+
+/** Canonical PR 1 source definition; durable execution remains in the harness. */
+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.",
+ inputSchema: TASK_CANCEL_INPUT_SCHEMA,
+ outputSchema: TASK_VIEWS_OUTPUT_SCHEMA,
+ execute() {
+ throw new Error("task_cancel is handled by eve's durable dispatch step.");
+ },
+});
+
+export default taskCancel;
diff --git a/packages/eve/src/public/tools/task-update.ts b/packages/eve/src/public/tools/task-update.ts
new file mode 100644
index 000000000..8ca8d7d33
--- /dev/null
+++ b/packages/eve/src/public/tools/task-update.ts
@@ -0,0 +1,14 @@
+import { defineTool } from "#public/definitions/tool.js";
+import { TASK_UPDATE_INPUT_SCHEMA } from "#shared/task-tool.js";
+
+/** Canonical PR 1 source definition; durable execution remains in the harness. */
+export const taskUpdate = defineTool({
+ description:
+ "Briefly tell the parent agent what this background task is currently doing. Report activity, not preliminary findings or results.",
+ inputSchema: TASK_UPDATE_INPUT_SCHEMA,
+ execute() {
+ throw new Error("task_update is handled by eve's durable dispatch step.");
+ },
+});
+
+export default taskUpdate;
diff --git a/packages/eve/src/public/tools/todo.ts b/packages/eve/src/public/tools/todo.ts
new file mode 100644
index 000000000..e526f0206
--- /dev/null
+++ b/packages/eve/src/public/tools/todo.ts
@@ -0,0 +1,2 @@
+export { default } from "#tools/todo.js";
+export * from "#tools/todo.js";
diff --git a/packages/eve/src/public/tools/web-fetch.ts b/packages/eve/src/public/tools/web-fetch.ts
new file mode 100644
index 000000000..ac44ce55f
--- /dev/null
+++ b/packages/eve/src/public/tools/web-fetch.ts
@@ -0,0 +1,2 @@
+export { default } from "#tools/web-fetch.js";
+export * from "#tools/web-fetch.js";
diff --git a/packages/eve/src/public/tools/write-file.ts b/packages/eve/src/public/tools/write-file.ts
new file mode 100644
index 000000000..f45071009
--- /dev/null
+++ b/packages/eve/src/public/tools/write-file.ts
@@ -0,0 +1,2 @@
+export { default } from "#tools/write-file.js";
+export * from "#tools/write-file.js";
diff --git a/packages/eve/src/runtime/actions/keys.ts b/packages/eve/src/runtime/actions/keys.ts
index 4413a15df..0e593b3e1 100644
--- a/packages/eve/src/runtime/actions/keys.ts
+++ b/packages/eve/src/runtime/actions/keys.ts
@@ -1,4 +1,4 @@
-import type { RuntimeActionRequest, RuntimeActionResult } from "#runtime/actions/types.js";
+import type { RuntimeActionRequest, RuntimeActionResult } from "#shared/action-types.js";
/**
* Returns the stable match key used to pair one pending runtime action request
diff --git a/packages/eve/src/runtime/actions/results.ts b/packages/eve/src/runtime/actions/results.ts
index bd507c685..d4ca86ade 100644
--- a/packages/eve/src/runtime/actions/results.ts
+++ b/packages/eve/src/runtime/actions/results.ts
@@ -1,5 +1,5 @@
import { getRuntimeActionResultKey } from "#runtime/actions/keys.js";
-import type { RuntimeActionResult } from "#runtime/actions/types.js";
+import type { RuntimeActionResult } from "#shared/action-types.js";
/** Returns results in pending-key order once every requested action has completed. */
export function resolveRuntimeActionResultsForKeys<TResult extends RuntimeActionResult>(input: {
diff --git a/packages/eve/src/runtime/agent/bootstrap.test.ts b/packages/eve/src/runtime/agent/bootstrap.test.ts
index 3c8feecdd..106f4f658 100644
--- a/packages/eve/src/runtime/agent/bootstrap.test.ts
+++ b/packages/eve/src/runtime/agent/bootstrap.test.ts
@@ -1,17 +1,32 @@
import { describe, expect, it } from "vitest";
import { createResolvedRuntimeTurnAgent } from "#runtime/agent/bootstrap.js";
-import { AGENT_TOOL_NAME } from "#runtime/framework-tools/agent.js";
+import { AGENT_TOOL_NAME } from "#shared/agent-tool.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";
+
+const APPLICATION_OWNER = { kind: "application" } as const;
+
+function createFrameworkAgentTool(): PreparedRuntimeTool {
+ return {
+ description: "Message a persistent agent.",
+ inputSchema: null,
+ kind: "authored-tool",
+ logicalPath: `tools/${AGENT_TOOL_NAME}.ts`,
+ name: AGENT_TOOL_NAME,
+ owner: { feature: "agent-messaging", kind: "framework" },
+ sourceId: `framework:tools/${AGENT_TOOL_NAME}.ts`,
+ };
+}
function createResolvedAgentForTest(overrides: Partial<ResolvedAgent> = {}): ResolvedAgent {
const agent: Partial<ResolvedAgent> = {
config: { name: "test-agent" } as ResolvedAgent["config"],
connections: [],
- disabledFrameworkTools: [],
instructions: [],
skills: [],
+ workspaceSpec: { rootEntries: [] },
...overrides,
};
return agent as ResolvedAgent;
@@ -26,6 +41,7 @@ describe("createResolvedRuntimeTurnAgent agent-messaging gating", () => {
content: "System policy.",
logicalPath: "instructions/system.ts",
name: "instructions/system",
+ owner: APPLICATION_OWNER,
role: "system",
sourceId: "instructions/system.ts",
sourceKind: "module",
@@ -34,6 +50,7 @@ describe("createResolvedRuntimeTurnAgent agent-messaging gating", () => {
content: " Pinned user context. ",
logicalPath: "instructions/user.ts",
name: "instructions/user",
+ owner: APPLICATION_OWNER,
role: "user",
sourceId: "instructions/user.ts",
sourceKind: "module",
@@ -42,6 +59,7 @@ describe("createResolvedRuntimeTurnAgent agent-messaging gating", () => {
content: " \n ",
logicalPath: "instructions/empty.ts",
name: "instructions/empty",
+ owner: APPLICATION_OWNER,
role: "user",
sourceId: "instructions/empty.ts",
sourceKind: "module",
@@ -49,7 +67,7 @@ describe("createResolvedRuntimeTurnAgent agent-messaging gating", () => {
],
}),
nodeId: ROOT_RUNTIME_AGENT_NODE_ID,
- tools: [],
+ tools: [createFrameworkAgentTool()],
});
expect(turnAgent.initialMessages).toEqual([{ content: "Pinned user context.", role: "user" }]);
@@ -67,7 +85,7 @@ describe("createResolvedRuntimeTurnAgent agent-messaging gating", () => {
} as ResolvedAgent["config"],
}),
nodeId: ROOT_RUNTIME_AGENT_NODE_ID,
- tools: [],
+ tools: [createFrameworkAgentTool()],
});
expect(turnAgent.instructions).toContainEqual(expect.stringContaining("Pass `agentId`"));
@@ -93,7 +111,7 @@ describe("createResolvedRuntimeTurnAgent agent-messaging gating", () => {
} as ResolvedAgent["config"],
}),
nodeId: ROOT_RUNTIME_AGENT_NODE_ID,
- tools: [],
+ tools: [createFrameworkAgentTool()],
});
expect(turnAgent.instructions).toContainEqual(expect.stringContaining("availability=busy"));
@@ -116,6 +134,7 @@ describe("createResolvedRuntimeTurnAgent agent-messaging gating", () => {
kind: "authored-tool",
logicalPath: `tools/${AGENT_TOOL_NAME}.ts`,
name: AGENT_TOOL_NAME,
+ owner: APPLICATION_OWNER,
sourceId: `tools/${AGENT_TOOL_NAME}.ts`,
},
],
@@ -124,15 +143,14 @@ describe("createResolvedRuntimeTurnAgent agent-messaging gating", () => {
expect(turnAgent.instructions).not.toContainEqual(expect.stringContaining("Pass `agentId`"));
});
- it("omits the messaging instruction when the root disables the framework agent tool", () => {
+ it("omits the messaging instruction when no agent tool was compiled", () => {
const turnAgent = createResolvedRuntimeTurnAgent({
agent: createResolvedAgentForTest({
config: {
experimental: { subagentPersistentSessions: true },
name: "test-agent",
} as ResolvedAgent["config"],
- disabledFrameworkTools: [AGENT_TOOL_NAME],
- } as Partial<ResolvedAgent>),
+ }),
nodeId: ROOT_RUNTIME_AGENT_NODE_ID,
tools: [],
});
diff --git a/packages/eve/src/runtime/agent/bootstrap.ts b/packages/eve/src/runtime/agent/bootstrap.ts
index de456584a..c9a6c4f94 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, isImplicitAgentToolAvailable } from "#runtime/framework-tools/agent.js";
+import { AGENT_TOOL_NAME } from "#shared/agent-tool.js";
import { composeRuntimeBasePrompt } from "#runtime/prompt/compose.js";
import type { PreparedRuntimeTool } from "#runtime/sessions/turn.js";
import type { ResolvedAgent, ResolvedAgentDefinition } from "#runtime/types.js";
@@ -94,16 +94,12 @@ export function createResolvedRuntimeTurnAgent(input: {
const subagentDeclaredTool = input.tools.some(
(tool) => tool.kind === "subagent" || tool.kind === "remote",
);
- // The framework `agent` tool is injected after graph resolution, so
- // declared tools alone under-count. isImplicitAgentToolAvailable is the
- // same predicate node-step uses for the injection itself — including the
- // authored-tool shadowing leg, so instructions never advertise a tool an
- // authored "agent" tool has replaced.
- const subagentImplicitRootTool = isImplicitAgentToolAvailable({
- disabledFrameworkTools: agent.disabledFrameworkTools,
- hasAuthoredAgentTool: input.tools.some((tool) => tool.name === AGENT_TOOL_NAME),
- nodeId: input.nodeId,
- });
+ const subagentFrameworkRootTool = input.tools.some(
+ (tool) =>
+ tool.kind === "authored-tool" &&
+ tool.owner.kind === "framework" &&
+ tool.name === AGENT_TOOL_NAME,
+ );
const base: RuntimeTurnAgentBase = {
availableSkills: agent.skills.map((skill) => ({
description: skill.description,
@@ -119,9 +115,9 @@ export function createResolvedRuntimeTurnAgent(input: {
persistentSubagentSessions:
config?.experimental?.tasks === true ||
config?.experimental?.subagentPersistentSessions === true,
- subagentsAvailable: subagentDeclaredTool || subagentImplicitRootTool,
+ subagentsAvailable: subagentDeclaredTool || subagentFrameworkRootTool,
tasksEnabled: config?.experimental?.tasks === true,
- toolsAvailable: input.tools.length > 0 || subagentImplicitRootTool,
+ toolsAvailable: input.tools.length > 0,
workspaceSpec: agent.workspaceSpec,
}),
compactionModel: config?.compaction?.model,
diff --git a/packages/eve/src/runtime/agent/mock-model-adapter.ts b/packages/eve/src/runtime/agent/mock-model-adapter.ts
index fc3c2bcd0..8930b347b 100644
--- a/packages/eve/src/runtime/agent/mock-model-adapter.ts
+++ b/packages/eve/src/runtime/agent/mock-model-adapter.ts
@@ -31,7 +31,7 @@ import {
getAvailableSkills,
} from "#runtime/agent/mock-model-skill-selection.js";
import { createJsonSchemaSample } from "#runtime/agent/mock-structured-output.js";
-import { FINAL_OUTPUT_TOOL_NAME } from "#runtime/framework-tools/final-output.js";
+import { FINAL_OUTPUT_TOOL_NAME } from "#harness/final-output.js";
import { LOAD_SKILL_TOOL_NAME } from "#runtime/skills/fragment-context.js";
const MOCK_RUNTIME_MODEL_PROVIDER = "eve-runtime-mock";
diff --git a/packages/eve/src/runtime/cache-key.scenario.test.ts b/packages/eve/src/runtime/cache-key.scenario.test.ts
index 4ffee5cc0..01372e180 100644
--- a/packages/eve/src/runtime/cache-key.scenario.test.ts
+++ b/packages/eve/src/runtime/cache-key.scenario.test.ts
@@ -98,6 +98,10 @@ async function writeCompileMetadata(input: {
`${JSON.stringify(
{
compile: {
+ manifest: {
+ path: ".eve/compile/compiled-agent-manifest.json",
+ sha256: "compiled-manifest-hash",
+ },
moduleMap: {
path: ".eve/compile/module-map.mjs",
sha256: "module-map-hash",
diff --git a/packages/eve/src/runtime/connections/authorization-tokens.ts b/packages/eve/src/runtime/connections/authorization-tokens.ts
index 3126d9fac..cfae84f94 100644
--- a/packages/eve/src/runtime/connections/authorization-tokens.ts
+++ b/packages/eve/src/runtime/connections/authorization-tokens.ts
@@ -15,7 +15,7 @@
import type { AlsContext, ContextContainer } from "#context/container.js";
import { ContextKey } from "#context/key.js";
-import type { TokenResult } from "#runtime/connections/types.js";
+import type { TokenResult } from "#shared/connection-types.js";
/**
* Inner map of `principalKey` → {@link TokenResult} for one connection.
diff --git a/packages/eve/src/runtime/connections/callback-route.test.ts b/packages/eve/src/runtime/connections/callback-route.test.ts
index f1ad95155..dcd4a9f8c 100644
--- a/packages/eve/src/runtime/connections/callback-route.test.ts
+++ b/packages/eve/src/runtime/connections/callback-route.test.ts
@@ -1,17 +1,11 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
-import {
- EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,
- EVE_LEGACY_CONNECTION_CALLBACK_ROUTE_PATTERN,
- createEveConnectionCallbackRoutePath,
-} from "#protocol/routes.js";
+import { createEveConnectionCallbackRoutePath } from "#protocol/routes.js";
import type { RouteContext } from "#public/definitions/channel.js";
import {
- getConnectionCallbackChannelDefinitions,
- getConnectionCallbackChannelNames,
handleConnectionCallbackRequest,
- HTTP_CONNECTION_CALLBACK_CHANNEL_NAME_PREFIX,
-} from "#runtime/connections/callback-route.js";
+ handleLegacyConnectionCallbackRequest,
+} from "#execution/connections/callback-route.js";
const resumeHookMock = vi.fn();
@@ -27,44 +21,6 @@ function buildRouteContext(params: Readonly<Record<string, string>>): RouteConte
};
}
-describe("getConnectionCallbackChannelDefinitions", () => {
- it("registers GET and POST entries at the framework callback route pattern", () => {
- const definitions = getConnectionCallbackChannelDefinitions();
- expect(definitions).toHaveLength(4);
- const methods = definitions.map((d) => d.method);
- expect(methods).toEqual(expect.arrayContaining(["GET", "POST"]));
- for (const def of definitions) {
- expect([
- EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,
- EVE_LEGACY_CONNECTION_CALLBACK_ROUTE_PATTERN,
- ]).toContain(def.urlPath);
- expect(def.name.startsWith(HTTP_CONNECTION_CALLBACK_CHANNEL_NAME_PREFIX)).toBe(true);
- expect(def.name).not.toContain(".well-known");
- expect(def.sourceKind).toBe("module");
- if (def.urlPath === EVE_CONNECTION_CALLBACK_ROUTE_PATTERN) {
- expect(def.fetch).toBe(handleConnectionCallbackRequest);
- }
- }
- });
-
- it("uses unique logical names per (method, urlPath) pair", () => {
- const definitions = getConnectionCallbackChannelDefinitions();
- const names = definitions.map((d) => d.name);
- expect(new Set(names).size).toBe(names.length);
- });
-});
-
-describe("getConnectionCallbackChannelNames", () => {
- it("returns the same names as getConnectionCallbackChannelDefinitions", () => {
- const definitions = getConnectionCallbackChannelDefinitions();
- const names = getConnectionCallbackChannelNames();
- expect(names.size).toBe(definitions.length);
- for (const def of definitions) {
- expect(names.has(def.name)).toBe(true);
- }
- });
-});
-
describe("handleConnectionCallbackRequest", () => {
beforeEach(() => {
resumeHookMock.mockReset();
@@ -140,14 +96,7 @@ describe("handleConnectionCallbackRequest", () => {
it("keeps pre-attempt callback URLs resumable for pinned workflows", async () => {
resumeHookMock.mockResolvedValueOnce(undefined);
- const legacy = getConnectionCallbackChannelDefinitions().find(
- (definition) =>
- definition.method === "GET" &&
- definition.urlPath === EVE_LEGACY_CONNECTION_CALLBACK_ROUTE_PATTERN,
- );
- if (legacy?.fetch === undefined) throw new Error("Missing legacy callback route.");
-
- const response = await legacy.fetch(
+ const response = await handleLegacyConnectionCallbackRequest(
new Request("https://app.example.com/eve/v1/connections/linear/callback/tok123?code=abc"),
buildRouteContext({ name: "linear", token: "tok123" }),
);
diff --git a/packages/eve/src/runtime/connections/define-interactive-authorization.test.ts b/packages/eve/src/runtime/connections/define-interactive-authorization.test.ts
index 4fa8d5b24..d33a6b82f 100644
--- a/packages/eve/src/runtime/connections/define-interactive-authorization.test.ts
+++ b/packages/eve/src/runtime/connections/define-interactive-authorization.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { defineInteractiveAuthorization } from "#runtime/connections/types.js";
+import { defineInteractiveAuthorization } from "#shared/connection-types.js";
describe("defineInteractiveAuthorization", () => {
it("sets principalType to user", () => {
diff --git a/packages/eve/src/runtime/connections/mcp-client.ts b/packages/eve/src/runtime/connections/mcp-client.ts
index 8bc006c0e..f3c616f50 100644
--- a/packages/eve/src/runtime/connections/mcp-client.ts
+++ b/packages/eve/src/runtime/connections/mcp-client.ts
@@ -20,7 +20,7 @@ import type {
HeadersDefinition,
HeaderValue,
ToolFilterDefinition,
-} from "#runtime/connections/types.js";
+} from "#shared/connection-types.js";
interface McpToolCache {
readonly metadata: readonly ConnectionToolMetadata[];
diff --git a/packages/eve/src/runtime/connections/openapi-client.ts b/packages/eve/src/runtime/connections/openapi-client.ts
index 7748ae9df..ced4a779e 100644
--- a/packages/eve/src/runtime/connections/openapi-client.ts
+++ b/packages/eve/src/runtime/connections/openapi-client.ts
@@ -28,7 +28,7 @@ import type {
ConnectionClient,
ConnectionToolExecuteOptions,
ConnectionToolMetadata,
-} from "#runtime/connections/types.js";
+} from "#shared/connection-types.js";
import { isObject } from "#shared/guards.js";
import { toInputSchema, type ToolSchema } from "#shared/tool-schema.js";
import { isLoopbackHostname } from "#shared/network-address.js";
diff --git a/packages/eve/src/runtime/connections/principal.test.ts b/packages/eve/src/runtime/connections/principal.test.ts
index 219cc72e9..d72e47fea 100644
--- a/packages/eve/src/runtime/connections/principal.test.ts
+++ b/packages/eve/src/runtime/connections/principal.test.ts
@@ -7,7 +7,7 @@ import {
isConnectionAuthorizationFailedError,
} from "#public/connections/errors.js";
import { principalKey, resolveConnectionPrincipal } from "#runtime/connections/principal.js";
-import type { AuthorizationDefinition } from "#runtime/connections/types.js";
+import type { AuthorizationDefinition } from "#shared/connection-types.js";
function ctxWithAuth(current: SessionAuthContext | null): ContextContainer {
const ctx = new ContextContainer();
diff --git a/packages/eve/src/runtime/connections/principal.ts b/packages/eve/src/runtime/connections/principal.ts
index c63bc9d45..51caf4625 100644
--- a/packages/eve/src/runtime/connections/principal.ts
+++ b/packages/eve/src/runtime/connections/principal.ts
@@ -13,7 +13,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 type { AuthorizationDefinition, ConnectionPrincipal } from "#runtime/connections/types.js";
+import type { AuthorizationDefinition, ConnectionPrincipal } from "#shared/connection-types.js";
/**
* Stable string key identifying one principal within a connection's
diff --git a/packages/eve/src/runtime/connections/registry-types.ts b/packages/eve/src/runtime/connections/registry-types.ts
new file mode 100644
index 000000000..e3f4a29ce
--- /dev/null
+++ b/packages/eve/src/runtime/connections/registry-types.ts
@@ -0,0 +1,12 @@
+import type { Approval } from "#public/definitions/approval.js";
+import type { ConnectionClient } from "#shared/connection-types.js";
+import type { ResolvedConnectionDefinition } from "#runtime/types.js";
+
+/** Per-session container mapping compiled connection names to live clients. */
+export interface ConnectionRegistry {
+ dispose(): Promise<void>;
+ getClient(connectionName: string): ConnectionClient;
+ getConnectionApproval(connectionName: string): Approval | undefined;
+ getConnectionNames(): readonly string[];
+ getConnections(): readonly ResolvedConnectionDefinition[];
+}
diff --git a/packages/eve/src/runtime/connections/registry.ts b/packages/eve/src/runtime/connections/registry.ts
index 71637fd8d..f19b73b78 100644
--- a/packages/eve/src/runtime/connections/registry.ts
+++ b/packages/eve/src/runtime/connections/registry.ts
@@ -2,7 +2,8 @@ import type { Approval } from "#public/definitions/approval.js";
import type { ResolvedConnectionDefinition } from "#runtime/types.js";
import { McpConnectionClient } from "#runtime/connections/mcp-client.js";
import { OpenApiConnectionClient } from "#runtime/connections/openapi-client.js";
-import type { ConnectionClient, ConnectionRegistry } from "#runtime/connections/types.js";
+import type { ConnectionClient } from "#shared/connection-types.js";
+import type { ConnectionRegistry } from "#runtime/connections/registry-types.js";
/**
* Per-session container mapping connection names to lazily-initialized
diff --git a/packages/eve/src/runtime/connections/resolve-authorization.ts b/packages/eve/src/runtime/connections/resolve-authorization.ts
index 02839d1cb..bfbe83942 100644
--- a/packages/eve/src/runtime/connections/resolve-authorization.ts
+++ b/packages/eve/src/runtime/connections/resolve-authorization.ts
@@ -3,8 +3,8 @@ import { type AlsContext, ContextContainer, contextStorage } from "#context/cont
import { ContextKey } from "#context/key.js";
import type { SessionContext } from "#public/definitions/callback-context.js";
import type { ResolvedConnectionDefinition } from "#runtime/types.js";
-import type { AuthorizationDefinition } from "#runtime/connections/types.js";
-import { normalizeAuthorizationSpec } from "#runtime/connections/validate-authorization.js";
+import type { AuthorizationDefinition } from "#shared/connection-types.js";
+import { normalizeAuthorizationSpec } from "#shared/validate-authorization.js";
type ResolvedAuthorization = Readonly<AuthorizationDefinition> | undefined;
type AuthorizationResolverCache = Map<ResolvedConnectionDefinition, Promise<ResolvedAuthorization>>;
diff --git a/packages/eve/src/runtime/connections/scoped-authorization.test.ts b/packages/eve/src/runtime/connections/scoped-authorization.test.ts
index b37654fbd..6ca148fb6 100644
--- a/packages/eve/src/runtime/connections/scoped-authorization.test.ts
+++ b/packages/eve/src/runtime/connections/scoped-authorization.test.ts
@@ -4,7 +4,7 @@ import {
resolveAuthorizationCallbackUrl,
stampChallengeDisplayName,
} from "#runtime/connections/scoped-authorization.js";
-import type { AuthorizationDefinition, TokenResult } from "#runtime/connections/types.js";
+import type { AuthorizationDefinition, TokenResult } from "#shared/connection-types.js";
function interactiveAuth(
input: { displayName?: string; connector?: string } = {},
diff --git a/packages/eve/src/runtime/connections/scoped-authorization.ts b/packages/eve/src/runtime/connections/scoped-authorization.ts
index c8dad53e0..a473aaf80 100644
--- a/packages/eve/src/runtime/connections/scoped-authorization.ts
+++ b/packages/eve/src/runtime/connections/scoped-authorization.ts
@@ -36,7 +36,7 @@ import {
type InteractiveAuthorizationDefinition,
supportsInteractiveAuthorization,
type TokenResult,
-} from "#runtime/connections/types.js";
+} from "#shared/connection-types.js";
const LOCAL_HTTP_VERCEL_CONNECT_HOSTNAMES: ReadonlySet<string> = new Set(["127.0.0.1", "[::1]"]);
diff --git a/packages/eve/src/runtime/connections/validate-authorization.test.ts b/packages/eve/src/runtime/connections/validate-authorization.test.ts
index 53f3c1ea3..203db0f53 100644
--- a/packages/eve/src/runtime/connections/validate-authorization.test.ts
+++ b/packages/eve/src/runtime/connections/validate-authorization.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest";
import {
normalizeAuthorizationSpec,
validateAuthorizationSpec,
-} from "#runtime/connections/validate-authorization.js";
+} from "#shared/validate-authorization.js";
const getToken = async () => ({ token: "abc" });
const startAuthorization = async () => ({
diff --git a/packages/eve/src/runtime/framework-channels/index.test.ts b/packages/eve/src/runtime/framework-channels/index.test.ts
deleted file mode 100644
index 5d4407775..000000000
--- a/packages/eve/src/runtime/framework-channels/index.test.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import type { AuthFn } from "#public/channels/auth.js";
-import type { EveChannelInput } from "#public/channels/eve.js";
-import { afterEach, describe, expect, it, vi } from "vitest";
-
-const mocks = vi.hoisted(() => ({
- localDev: vi.fn(),
- placeholderAuth: vi.fn(),
- vercelOidc: vi.fn(),
-}));
-
-let capturedAuth: EveChannelInput["auth"] | undefined;
-
-vi.mock("#public/channels/auth.js", async (importOriginal) => ({
- ...(await importOriginal<typeof import("#public/channels/auth.js")>()),
- localDev: mocks.localDev,
- placeholderAuth: mocks.placeholderAuth,
- vercelOidc: mocks.vercelOidc,
-}));
-
-vi.mock("#public/channels/eve.js", () => ({
- eveChannel(input: EveChannelInput) {
- capturedAuth = input.auth;
- return { adapter: {}, routes: [] };
- },
-}));
-
-import { getFrameworkChannelDefinitions } from "./index.js";
-
-afterEach(() => {
- capturedAuth = undefined;
- mocks.localDev.mockReset();
- mocks.placeholderAuth.mockReset();
- mocks.vercelOidc.mockReset();
-});
-
-describe("framework eve channel auth", () => {
- it("checks Vercel OIDC, then local dev, then the fail-closed placeholder", () => {
- const vercelAuth: AuthFn<Request> = () => null;
- const local: AuthFn<Request> = () => null;
- const placeholder: AuthFn<Request> = () => null;
- mocks.vercelOidc.mockReturnValue(vercelAuth);
- mocks.localDev.mockReturnValue(local);
- mocks.placeholderAuth.mockReturnValue(placeholder);
-
- getFrameworkChannelDefinitions();
-
- expect(capturedAuth).toEqual([vercelAuth, local, placeholder]);
- expect(mocks.vercelOidc).toHaveBeenCalledWith();
- expect(mocks.localDev).toHaveBeenCalledWith();
- expect(mocks.placeholderAuth).toHaveBeenCalledWith();
- });
-});
diff --git a/packages/eve/src/runtime/framework-channels/index.ts b/packages/eve/src/runtime/framework-channels/index.ts
deleted file mode 100644
index 0b9e9ab3a..000000000
--- a/packages/eve/src/runtime/framework-channels/index.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import { localDev, placeholderAuth, vercelOidc } from "#public/channels/auth.js";
-import { eveChannel } from "#public/channels/eve.js";
-import type { CompiledChannel } from "#channel/compiled-channel.js";
-import { isHttpRouteDefinition } from "#channel/routes.js";
-import {
- getConnectionCallbackChannelDefinitions,
- getConnectionCallbackChannelNames,
-} from "#runtime/connections/callback-route.js";
-import {
- getSessionCallbackChannelDefinitions,
- getSessionCallbackChannelNames,
-} from "#runtime/session-callback-route.js";
-import type { ResolvedChannelDefinition } from "#runtime/types.js";
-import {
- getTaskInputResponseChannelDefinitions,
- getTaskInputResponseChannelNames,
-} from "#runtime/task-input-response-route.js";
-
-const EVE_CHANNEL_NAME = "eve";
-
-/**
- * Framework default for the eve channel.
- */
-export function getFrameworkChannelDefinitions(): readonly ResolvedChannelDefinition[] {
- const compiled = eveChannel({
- auth: [vercelOidc(), localDev(), placeholderAuth()],
- }) as CompiledChannel;
-
- const result: ResolvedChannelDefinition[] = [];
-
- for (const route of compiled.routes) {
- if (!isHttpRouteDefinition(route)) {
- continue;
- }
- result.push({
- name: EVE_CHANNEL_NAME,
- method: route.method.toUpperCase() as "GET" | "POST",
- urlPath: route.path,
- cors: compiled.cors,
- fetch: async (req: Request, ctx: any) => route.handler(req, ctx),
- handler: route.handler,
- adapter: compiled.adapter,
- turnPolicy: compiled.turnPolicy,
- logicalPath: `framework://channels/${route.path}`,
- sourceId: `eve:framework:${route.method.toLowerCase()}-${route.path}`,
- sourceKind: "module",
- });
- }
-
- result.push(
- ...getConnectionCallbackChannelDefinitions(),
- ...getSessionCallbackChannelDefinitions(),
- ...getTaskInputResponseChannelDefinitions(),
- );
-
- return result;
-}
-
-export function getAllFrameworkChannelNames(): ReadonlySet<string> {
- return new Set([
- EVE_CHANNEL_NAME,
- ...getConnectionCallbackChannelNames(),
- ...getSessionCallbackChannelNames(),
- ...getTaskInputResponseChannelNames(),
- ]);
-}
diff --git a/packages/eve/src/runtime/framework-tools/agent.ts b/packages/eve/src/runtime/framework-tools/agent.ts
deleted file mode 100644
index 8681309e9..000000000
--- a/packages/eve/src/runtime/framework-tools/agent.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-import { ROOT_RUNTIME_AGENT_NODE_ID } from "#runtime/graph.js";
-import { SUBAGENT_TOOL_INPUT_SCHEMA } from "#runtime/subagents/registry.js";
-import type { ResolvedToolDefinition } from "#runtime/types.js";
-
-/**
- * Stable model-visible name for the root-only agent delegation tool.
- */
-export const AGENT_TOOL_NAME = "agent";
-
-/**
- * Model-facing instructions for the root-only agent delegation tool.
- */
-export const AGENT_TOOL_DESCRIPTION = [
- "Delegate a focused subtask to a fresh copy of yourself.",
- "Use it to isolate complex work or split a large task into independent pieces.",
- "Issue multiple `agent` calls in one response to run a small fixed set in parallel.",
- "Each child has fresh history and state but shares your tools and sandbox, so include essential context in `message` and give parallel writers non-overlapping scopes.",
-].join(" ");
-
-/**
- * Whether one node receives the implicit built-in `agent` tool.
- *
- * Single source of truth for the injection predicate: node-step uses it to
- * decide whether to add the tool, and prompt bootstrap uses it to decide
- * whether agent-messaging instructions may reference the tool. The
- * `hasAuthoredAgentTool` leg matters because an authored tool named "agent"
- * shadows the framework tool — instructions must not advertise a tool the
- * model cannot call.
- */
-export function isImplicitAgentToolAvailable(input: {
- readonly disabledFrameworkTools: readonly string[];
- readonly hasAuthoredAgentTool: boolean;
- /** Undefined when the caller prepares a turn without a graph node (never root). */
- readonly nodeId: string | undefined;
-}): boolean {
- return (
- input.nodeId === ROOT_RUNTIME_AGENT_NODE_ID &&
- !input.disabledFrameworkTools.includes(AGENT_TOOL_NAME) &&
- !input.hasAuthoredAgentTool
- );
-}
-
-/**
- * Shared metadata for the root-only agent delegation tool.
- */
-export const AGENT_TOOL_DEFINITION: ResolvedToolDefinition = {
- description: AGENT_TOOL_DESCRIPTION,
- inputSchema: SUBAGENT_TOOL_INPUT_SCHEMA,
- logicalPath: "eve:framework/agent",
- name: AGENT_TOOL_NAME,
- sourceId: "eve:agent-tool",
- sourceKind: "module",
-};
diff --git a/packages/eve/src/runtime/framework-tools/ask-question.ts b/packages/eve/src/runtime/framework-tools/ask-question.ts
deleted file mode 100644
index 0b3377dad..000000000
--- a/packages/eve/src/runtime/framework-tools/ask-question.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { z } from "#compiled/zod/index.js";
-
-import { inputRequestSchema } from "#runtime/input/types.js";
-import type { ResolvedToolDefinition } from "#runtime/types.js";
-
-/**
- * Stable model-visible name for the framework question tool.
- */
-export const ASK_QUESTION_TOOL_NAME = "ask_question";
-
-export const ASK_QUESTION_INPUT_SCHEMA = inputRequestSchema.omit({
- action: true,
- display: true,
- kind: true,
- requestId: true,
-});
-export const ASK_QUESTION_OUTPUT_SCHEMA = z
- .object({
- optionId: z.string().optional(),
- status: z.enum(["answered", "ignored"]),
- text: z.string().optional(),
- })
- .strict();
-
-/**
- * Root-only framework tool that lets the agent request structured user input.
- *
- * This is a client-side tool (as indicated by it not having an `execute` method). It requires user input
- * and therefore cannot be autonomously executed by the runtime.
- */
-export const ASK_QUESTION_TOOL_DEFINITION: ResolvedToolDefinition = {
- 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.",
- inputSchema: ASK_QUESTION_INPUT_SCHEMA,
- logicalPath: "eve:framework/ask-question",
- name: ASK_QUESTION_TOOL_NAME,
- outputSchema: ASK_QUESTION_OUTPUT_SCHEMA,
- sourceId: "eve:ask-question-tool",
- sourceKind: "module",
-};
diff --git a/packages/eve/src/runtime/framework-tools/index.test.ts b/packages/eve/src/runtime/framework-tools/index.test.ts
deleted file mode 100644
index 848ea2520..000000000
--- a/packages/eve/src/runtime/framework-tools/index.test.ts
+++ /dev/null
@@ -1,92 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import {
- getAllFrameworkToolDefinitions,
- getAllFrameworkToolNames,
- getFrameworkDynamicToolResolvers,
- getFrameworkToolDefinitions,
- getOptInFrameworkToolNames,
-} from "#runtime/framework-tools/index.js";
-import { isToolSchema } from "#shared/tool-schema.js";
-
-describe("framework-tools/index", () => {
- it("returns every known framework tool name regardless of config", () => {
- const names = getAllFrameworkToolNames();
- expect(names.has("bash")).toBe(true);
- expect(names.has("read_file")).toBe(true);
- expect(names.has("write_file")).toBe(true);
- expect(names.has("glob")).toBe(true);
- expect(names.has("grep")).toBe(true);
- expect(names.has("web_fetch")).toBe(true);
- expect(names.has("web_search")).toBe(true);
- expect(names.has("todo")).toBe(true);
- expect(names.has("load_skill")).toBe(true);
- expect(names.has("ask_question")).toBe(true);
- expect(names.has("agent")).toBe(true);
- expect(names.has("task_update")).toBe(true);
- expect(names.has("task_sleep")).toBe(false);
- expect(names.has("task_send")).toBe(false);
- // connection_search is now a dynamic tool resolver, not a framework tool
- expect(names.has("connection_search")).toBe(false);
- });
-
- it("contains every framework tool exactly once", () => {
- const tools = getAllFrameworkToolDefinitions();
- const names = tools.map((tool) => tool.name);
-
- expect(new Set(names).size).toBe(names.length);
- for (const tool of tools) {
- expect(tool.name).toBeTypeOf("string");
- expect(tool.name.length).toBeGreaterThan(0);
- }
-
- expect(names).toContain("agent");
- const defaultNames = getFrameworkToolDefinitions().map((tool) => tool.name);
- expect(defaultNames).not.toContain("agent");
- expect(defaultNames).not.toContain("glob");
- expect(defaultNames).not.toContain("grep");
- });
-
- it("identifies framework tools that require explicit authoring", () => {
- expect([...getOptInFrameworkToolNames()].sort()).toEqual(["glob", "grep"]);
- });
-
- it("does not direct default tools to opt-in tools", () => {
- const readFile = getFrameworkToolDefinitions().find((tool) => tool.name === "read_file");
-
- expect(readFile?.description).not.toMatch(/\b(?:glob|grep)\b/u);
- });
-
- it("uses one validated runtime schema for every framework-defined input", () => {
- for (const tool of getAllFrameworkToolDefinitions()) {
- if (tool.inputSchema !== null) {
- expect(isToolSchema(tool.inputSchema), `${tool.name} has a validated input schema`).toBe(
- true,
- );
- }
- }
- });
-
- it("declares an output schema for every statically shaped registered tool", () => {
- const tools = getFrameworkToolDefinitions();
- for (const tool of tools) {
- if (tool.name === "web_search") {
- expect(tool.outputSchema).toBeUndefined();
- continue;
- }
-
- expect(tool.outputSchema, `${tool.name} has outputSchema`).toBeDefined();
- }
- });
-
- it("registers connection search through the framework dynamic tool registry", () => {
- expect(getFrameworkDynamicToolResolvers()).toMatchObject([
- {
- eventNames: ["step.started"],
- logicalPath: "eve:framework/connection-search-dynamic",
- slug: "connection",
- sourceId: "eve:connection-search-dynamic",
- },
- ]);
- });
-});
diff --git a/packages/eve/src/runtime/framework-tools/index.ts b/packages/eve/src/runtime/framework-tools/index.ts
deleted file mode 100644
index 1fb08685e..000000000
--- a/packages/eve/src/runtime/framework-tools/index.ts
+++ /dev/null
@@ -1,131 +0,0 @@
-import { AGENT_TOOL_DEFINITION } from "#runtime/framework-tools/agent.js";
-import { ASK_QUESTION_TOOL_DEFINITION } from "#runtime/framework-tools/ask-question.js";
-import { BASH_TOOL_DEFINITION } from "#runtime/framework-tools/bash.js";
-import { GLOB_TOOL_DEFINITION } from "#runtime/framework-tools/glob.js";
-import { GREP_TOOL_DEFINITION } from "#runtime/framework-tools/grep.js";
-import { READ_FILE_TOOL_DEFINITION } from "#runtime/framework-tools/read-file.js";
-import {
- createSkillToolDefinition,
- SKILL_TOOL_DEFINITION,
-} from "#runtime/framework-tools/skill.js";
-import { TASK_TOOL_DEFINITIONS } from "#runtime/framework-tools/tasks.js";
-import { TODO_TOOL_DEFINITION } from "#runtime/framework-tools/todo.js";
-import { WEB_FETCH_TOOL_DEFINITION } from "#runtime/framework-tools/web-fetch.js";
-import { WEB_SEARCH_TOOL_DEFINITION } from "#runtime/framework-tools/web-search.js";
-import { WRITE_FILE_TOOL_DEFINITION } from "#runtime/framework-tools/write-file.js";
-import connectionSearchDynamicDefinition from "#runtime/framework-tools/connection-search-dynamic.js";
-import { resolveLoadedDynamicToolDefinition } from "#runtime/resolve-dynamic-tool.js";
-
-export { ConnectionRegistryKey } from "#context/providers/connection-key.js";
-export type { ReadFileStamp, ReadFileState } from "#runtime/framework-tools/file-state.js";
-export { ReadFileStateKey } from "#runtime/framework-tools/file-state.js";
-export type { TodoItem, TodoState } from "#runtime/framework-tools/todo.js";
-export { TodoStateKey } from "#runtime/framework-tools/todo.js";
-
-import type {
- ResolvedDynamicToolResolver,
- ResolvedSkillDefinition,
- ResolvedToolDefinition,
-} from "#runtime/types.js";
-import type { DynamicSentinel } from "#shared/dynamic-tool-definition.js";
-
-interface FrameworkDynamicToolDefinition {
- readonly definition: DynamicSentinel;
- readonly logicalPath: string;
- readonly slug: string;
- readonly sourceId: string;
-}
-
-const REGISTERED_FRAMEWORK_DYNAMIC_TOOLS: readonly FrameworkDynamicToolDefinition[] = [
- {
- definition: connectionSearchDynamicDefinition,
- logicalPath: "eve:framework/connection-search-dynamic",
- slug: "connection",
- sourceId: "eve:connection-search-dynamic",
- },
-];
-
-const REGISTERED_FRAMEWORK_TOOLS: readonly ResolvedToolDefinition[] = [
- ASK_QUESTION_TOOL_DEFINITION,
- BASH_TOOL_DEFINITION,
- READ_FILE_TOOL_DEFINITION,
- WRITE_FILE_TOOL_DEFINITION,
- TODO_TOOL_DEFINITION,
- WEB_FETCH_TOOL_DEFINITION,
- WEB_SEARCH_TOOL_DEFINITION,
- SKILL_TOOL_DEFINITION,
-];
-
-const OPT_IN_FRAMEWORK_TOOLS: readonly ResolvedToolDefinition[] = [
- GLOB_TOOL_DEFINITION,
- GREP_TOOL_DEFINITION,
-];
-
-const ALL_FRAMEWORK_TOOLS: readonly ResolvedToolDefinition[] = [
- ...REGISTERED_FRAMEWORK_TOOLS,
- ...OPT_IN_FRAMEWORK_TOOLS,
- AGENT_TOOL_DEFINITION,
- ...TASK_TOOL_DEFINITIONS,
-];
-
-/**
- * Returns framework-owned tool definitions registered in the tool registry
- * alongside authored tools during graph resolution.
- *
- * `connection_search` is no longer in this list. The graph resolution path
- * registers it as a framework dynamic tool resolver.
- */
-export function getFrameworkToolDefinitions(config?: {
- readonly authoredSkills?: readonly ResolvedSkillDefinition[];
-}): readonly ResolvedToolDefinition[] {
- const authoredSkills = config?.authoredSkills;
- if (authoredSkills === undefined) return REGISTERED_FRAMEWORK_TOOLS;
-
- return REGISTERED_FRAMEWORK_TOOLS.map((definition) =>
- definition.name === SKILL_TOOL_DEFINITION.name
- ? createSkillToolDefinition(authoredSkills)
- : definition,
- );
-}
-
-/**
- * Returns framework-owned dynamic tool resolvers.
- * Framework definitions use the public `defineDynamic()` contract and enter
- * the same loaded-definition resolver path as authored dynamic tools.
- */
-export function getFrameworkDynamicToolResolvers(): readonly ResolvedDynamicToolResolver[] {
- return REGISTERED_FRAMEWORK_DYNAMIC_TOOLS.map((entry) =>
- resolveLoadedDynamicToolDefinition(entry.definition, {
- logicalPath: entry.logicalPath,
- slug: entry.slug,
- sourceId: entry.sourceId,
- sourceKind: "module",
- }),
- );
-}
-
-/**
- * Returns every static framework-owned tool definition, including tools such
- * as `agent` that the runtime does not register in the tool registry.
- */
-export function getAllFrameworkToolDefinitions(): readonly ResolvedToolDefinition[] {
- return ALL_FRAMEWORK_TOOLS;
-}
-
-/** Returns framework tools that authors must explicitly add to an agent. */
-export function getOptInFrameworkToolNames(): ReadonlySet<string> {
- return new Set(OPT_IN_FRAMEWORK_TOOLS.map((definition) => definition.name));
-}
-
-/**
- * Returns the names of every framework-provided tool the framework knows
- * about, regardless of whether the current agent gates any of them on
- * runtime configuration.
- *
- * Used by the graph resolver to validate `disableTool(name)` arguments —
- * disabling a name that does not match any known framework tool is treated
- * as an authoring error rather than silently dropping the request.
- */
-export function getAllFrameworkToolNames(): ReadonlySet<string> {
- return new Set(ALL_FRAMEWORK_TOOLS.map((definition) => definition.name));
-}
diff --git a/packages/eve/src/runtime/framework-tools/tasks.ts b/packages/eve/src/runtime/framework-tools/tasks.ts
deleted file mode 100644
index d06e741da..000000000
--- a/packages/eve/src/runtime/framework-tools/tasks.ts
+++ /dev/null
@@ -1,154 +0,0 @@
-import { z } from "#compiled/zod/index.js";
-
-import type { HarnessToolDefinition } from "#harness/execute-tool.js";
-import type { ResolvedToolDefinition } from "#runtime/types.js";
-
-/**
- * Framework task tools for `experimental.tasks`.
- *
- * With the flag on, subagent calls return a task receipt instead of
- * blocking the parent turn; these tools coordinate that delegated work.
- * `task_cancel` and `task_update` are execute-less runtime actions —
- * they need durable session state and world access, so the runtime-action
- * dispatch step executes them.
- */
-
-export const TASK_CANCEL_TOOL_NAME = "task_cancel";
-export const TASK_UPDATE_TOOL_NAME = "task_update";
-
-/** Every model-visible task tool name, for gating and dispatch matching. */
-export const TASK_TOOL_NAMES: ReadonlySet<string> = new Set([
- TASK_CANCEL_TOOL_NAME,
- TASK_UPDATE_TOOL_NAME,
-]);
-
-/** Task-control tools executed by the runtime-action dispatch step. */
-export const TASK_CONTROL_TOOL_NAMES: ReadonlySet<string> = new Set([
- TASK_CANCEL_TOOL_NAME,
- TASK_UPDATE_TOOL_NAME,
-]);
-
-const TASK_IDS_SCHEMA = z
- .array(z.string().min(1))
- .min(1)
- .describe("Task ids from earlier subagent task receipts.");
-
-export const TASK_CANCEL_INPUT_SCHEMA = z.strictObject({ taskIds: TASK_IDS_SCHEMA });
-
-export const TASK_UPDATE_INPUT_SCHEMA = z.strictObject({
- message: z.string().min(1).describe("Brief description of what this task is currently doing."),
-});
-
-const TASK_VIEW_SCHEMA = z.object({
- inputRequests: z.array(z.unknown()).optional(),
- lastOutput: z
- .object({
- data: z.unknown(),
- type: z.enum(["result", "error"]),
- })
- .optional(),
- metadata: z.union([
- z.object({
- agentId: z.string(),
- kind: z.literal("subagent"),
- mode: z.enum(["local", "remote"]),
- name: z.string(),
- }),
- z.object({
- data: z.record(z.string(), z.unknown()).optional(),
- kind: z.string(),
- name: z.string(),
- }),
- ]),
- status: z.enum(["working", "input_required", "completed", "failed", "cancelled"]),
- taskId: z.string(),
-});
-
-export const TASK_VIEWS_OUTPUT_SCHEMA = z.object({
- tasks: z.array(TASK_VIEW_SCHEMA),
-});
-
-export const SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA = z.strictObject({
- agentId: z.string(),
- status: z.literal("working"),
- taskId: z.string(),
-});
-
-const TASK_CANCEL_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.";
-
-const TASK_UPDATE_DESCRIPTION =
- "Briefly tell the parent agent what this background task is currently doing. " +
- "Report activity, not preliminary findings or results.";
-
-/**
- * Builds the harness definitions injected when the root agent enables
- * `experimental.tasks`. Follows the implicit `agent` tool pattern:
- * inline definitions, no registry entry, session-shape hiding in
- * advertised-tools, and re-validation at dispatch.
- */
-export function createTaskToolHarnessDefinitions(): readonly HarnessToolDefinition[] {
- return [
- {
- description: TASK_CANCEL_DESCRIPTION,
- inputSchema: TASK_CANCEL_INPUT_SCHEMA,
- name: TASK_CANCEL_TOOL_NAME,
- outputSchema: TASK_VIEWS_OUTPUT_SCHEMA,
- runtimeAction: { kind: "task-control" },
- },
- {
- description: TASK_UPDATE_DESCRIPTION,
- inputSchema: TASK_UPDATE_INPUT_SCHEMA,
- name: TASK_UPDATE_TOOL_NAME,
- runtimeAction: { kind: "task-control" },
- },
- ];
-}
-
-/**
- * Whether one node's sessions receive the task tools.
- *
- * Mirrors `isImplicitAgentToolAvailable`: the compile step already
- * rejects `experimental.tasks` on subagents, authored tools with the
- * same name shadow the framework tool, and `disableTool(name)` removes
- * individual tools. Root-node self-delegated children share this node's
- * config, so advertised-tools uses caller/session shape to expose only
- * `task_update` to delegated task children.
- */
-export function isTaskToolAvailable(input: {
- readonly disabledFrameworkTools: readonly string[];
- readonly hasAuthoredTool: boolean;
- readonly tasksEnabled: boolean;
- readonly toolName: string;
-}): boolean {
- return (
- input.tasksEnabled &&
- !input.disabledFrameworkTools.includes(input.toolName) &&
- !input.hasAuthoredTool
- );
-}
-
-function createResolvedTaskToolStub(input: {
- readonly description: string;
- readonly name: string;
-}): ResolvedToolDefinition {
- return {
- description: input.description,
- inputSchema: null,
- logicalPath: `eve:framework/${input.name}`,
- name: input.name,
- sourceId: `eve:${input.name}-tool`,
- sourceKind: "module",
- };
-}
-
-/**
- * Registry-shaped metadata for the task tools. Not registered in the
- * tool registry (the harness injects the real definitions per node);
- * these entries exist so `disableTool(name)` validates the names.
- */
-export const TASK_TOOL_DEFINITIONS: readonly ResolvedToolDefinition[] = [
- createResolvedTaskToolStub({ description: TASK_CANCEL_DESCRIPTION, name: TASK_CANCEL_TOOL_NAME }),
- createResolvedTaskToolStub({ description: TASK_UPDATE_DESCRIPTION, name: TASK_UPDATE_TOOL_NAME }),
-];
diff --git a/packages/eve/src/runtime/input/types.test.ts b/packages/eve/src/runtime/input/types.test.ts
index a35006034..5eaa783b4 100644
--- a/packages/eve/src/runtime/input/types.test.ts
+++ b/packages/eve/src/runtime/input/types.test.ts
@@ -5,7 +5,7 @@ import {
inputResponseSchema,
isInputRequest,
isInputResponse,
-} from "#runtime/input/types.js";
+} from "#shared/input.js";
describe("inputRequestSchema", () => {
it("accepts a confirmation request (approval)", () => {
diff --git a/packages/eve/src/runtime/loaders/bundled-artifacts.test.ts b/packages/eve/src/runtime/loaders/bundled-artifacts.test.ts
index a53e8ed37..5a43647a5 100644
--- a/packages/eve/src/runtime/loaders/bundled-artifacts.test.ts
+++ b/packages/eve/src/runtime/loaders/bundled-artifacts.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { createCompiledAgentManifest } from "#compiler/manifest.js";
+import { compileFromMemory } from "#compiler/compile-from-memory.js";
import {
readBundledCompiledArtifacts,
withBundledCompiledArtifacts,
@@ -13,16 +13,11 @@ import {
describe("withBundledCompiledArtifacts", () => {
it("installs artifacts only for the scoped runtime session", async () => {
- const manifest = createCompiledAgentManifest({
+ const { manifest, moduleMap } = await compileFromMemory({
agentRoot: "/tmp/app/agent",
appRoot: "/tmp/app",
- config: {
- model: {
- id: "openai/gpt-5-mini",
- routing: { kind: "gateway", target: "openai" },
- },
- name: "test-agent",
- },
+ model: "openai/gpt-5.4",
+ name: "test-agent",
});
await withRuntimeSession(createRuntimeSession("outer"), async () => {
@@ -31,9 +26,7 @@ describe("withBundledCompiledArtifacts", () => {
const inner = await withBundledCompiledArtifacts(
{
manifest,
- moduleMap: {
- nodes: {},
- },
+ moduleMap,
sessionId: "inner",
},
() => ({
diff --git a/packages/eve/src/runtime/loaders/compile-metadata.ts b/packages/eve/src/runtime/loaders/compile-metadata.ts
index d4f5b02f5..998bfc3e6 100644
--- a/packages/eve/src/runtime/loaders/compile-metadata.ts
+++ b/packages/eve/src/runtime/loaders/compile-metadata.ts
@@ -20,6 +20,7 @@ const compileMetadataSchema: z.ZodType<CompileMetadata> = z
.object({
compile: z
.object({
+ manifest: compileArtifactDigestSchema,
moduleMap: compileArtifactDigestSchema,
})
.strict(),
diff --git a/packages/eve/src/runtime/loaders/manifest.ts b/packages/eve/src/runtime/loaders/manifest.ts
index 4a4d216bc..2eb59a882 100644
--- a/packages/eve/src/runtime/loaders/manifest.ts
+++ b/packages/eve/src/runtime/loaders/manifest.ts
@@ -1,4 +1,5 @@
import { type CompiledAgentManifest, compiledAgentManifestSchema } from "#compiler/manifest.js";
+import { validateCompiledAgentManifest } from "#compiler/validate-artifact.js";
import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
import { formatValidationError } from "#runtime/validation.js";
import { resolveRuntimeCompilerArtifactPaths } from "#runtime/loaders/artifact-paths.js";
@@ -77,6 +78,14 @@ function parseCompiledManifest(value: unknown, manifestPath: string): CompiledAg
);
}
+ try {
+ validateCompiledAgentManifest(parsed.data);
+ } catch (error) {
+ throw new LoadCompiledManifestError(
+ `Expected "${manifestPath}" to contain a semantically valid compiled eve agent manifest. ${formatLoadErrorMessage(error)}`,
+ manifestPath,
+ );
+ }
return parsed.data;
}
diff --git a/packages/eve/src/runtime/prompt/compose.ts b/packages/eve/src/runtime/prompt/compose.ts
index 3b496e5f2..618c623a8 100644
--- a/packages/eve/src/runtime/prompt/compose.ts
+++ b/packages/eve/src/runtime/prompt/compose.ts
@@ -65,12 +65,7 @@ function createInstructionsPromptBlocks(
}
const only = systemInstructions.length === 1 ? systemInstructions[0] : undefined;
- const name =
- only !== undefined &&
- !only.sourceId.startsWith("ext:") &&
- !only.sourceId.startsWith("ext-override:")
- ? only.name
- : "instructions";
+ const name = only !== undefined && only.owner.kind !== "extension" ? only.name : "instructions";
const content = systemInstructions
.map((entry) => entry.content)
.join("\n\n")
diff --git a/packages/eve/src/runtime/resolve-agent-graph.ts b/packages/eve/src/runtime/resolve-agent-graph.ts
index 32d4ac813..46d03e3c7 100644
--- a/packages/eve/src/runtime/resolve-agent-graph.ts
+++ b/packages/eve/src/runtime/resolve-agent-graph.ts
@@ -7,18 +7,10 @@ import type {
} from "#compiler/manifest.js";
import { ROOT_COMPILED_AGENT_NODE_ID } from "#compiler/manifest.js";
import type { CompiledModuleMap } from "#compiler/module-map.js";
+import { validateCompiledModuleMap } from "#compiler/validate-artifact.js";
import type { HeadersValue } from "#client/types.js";
import { expectObjectRecord } from "#internal/authored-module.js";
import { createResolvedRuntimeTurnAgent } from "#runtime/agent/bootstrap.js";
-import {
- getAllFrameworkChannelNames,
- getFrameworkChannelDefinitions,
-} from "#runtime/framework-channels/index.js";
-import {
- getAllFrameworkToolNames,
- getFrameworkDynamicToolResolvers,
- getFrameworkToolDefinitions,
-} from "#runtime/framework-tools/index.js";
import { type ResolvedAgentGraphBundle, ROOT_RUNTIME_AGENT_NODE_ID } from "#runtime/graph.js";
import { createRuntimeHookRegistry } from "#runtime/hooks/registry.js";
import { resolveAgent } from "#runtime/resolve-agent.js";
@@ -31,7 +23,6 @@ import { createRuntimeToolRegistry } from "#runtime/tools/registry.js";
import { WORKFLOW_TOOL_NAME } from "#shared/workflow-sandbox.js";
import { createWorkspacePromptSection } from "#runtime/workspace/spec.js";
import type {
- ResolvedChannelDefinition,
ResolvedDynamicSubagentDefinition,
ResolvedRuntimeDelegationNode,
ResolvedRuntimeRemoteAgentNode,
@@ -88,6 +79,7 @@ class ResolveRuntimeAgentGraphError extends Error {
export async function resolveRuntimeAgentGraph(
input: ResolveRuntimeAgentGraphInput,
): Promise<ResolvedAgentGraphBundle> {
+ validateCompiledModuleMap(input.manifest, input.moduleMap);
const nodesByNodeId = new Map<string, ResolvedAgentGraphBundle["root"]>();
const childNodeIdsByParentNodeId = createChildNodeIdsByParentNodeId(input.manifest);
const subagentNodesById = new Map(
@@ -143,82 +135,15 @@ async function resolveRuntimeAgentNode(
moduleMap: input.moduleMap,
nodeId: input.nodeId,
});
- const frameworkTools = getFrameworkToolDefinitions({
- authoredSkills: agent.skills,
- });
- const frameworkToolNames = new Set(frameworkTools.map((t) => t.name));
- const allFrameworkToolNames = getAllFrameworkToolNames();
-
- // Authored tools whose filename slug matches a framework default replace
- // it. Authored disable sentinels (whose target is also taken from the
- // file's slug) remove a framework default. Both interactions happen here,
- // before the registry is built, so the duplicate-name guard inside
- // `createRuntimeToolRegistry` keeps doing its job for authored-vs-authored
- // collisions.
- const authoredToolNames = new Set(agent.tools.map((tool) => tool.name));
-
- for (const disabledName of agent.disabledFrameworkTools) {
- if (!allFrameworkToolNames.has(disabledName)) {
- throw new ResolveRuntimeAgentGraphError(
- `agent/tools/${disabledName}.ts exports disableTool() but "${disabledName}" is not a framework tool. ` +
- `Rename the file to one of: ${[...allFrameworkToolNames].sort().join(", ")}.`,
- {
- nodeId,
- sourceId: input.sourceId,
- },
- );
- }
- }
-
- const disabledFrameworkTools = new Set(agent.disabledFrameworkTools);
- const activeFrameworkTools = frameworkTools.filter(
- (tool) => !authoredToolNames.has(tool.name) && !disabledFrameworkTools.has(tool.name),
- );
-
const toolRegistry = await createRuntimeToolRegistry(
+ { tools: agent.tools },
{
- tools: [...activeFrameworkTools, ...agent.tools],
- },
- {
- reservedToolNames: [
- WORKFLOW_TOOL_NAME,
- ...(frameworkToolNames.has(LOAD_SKILL_TOOL_NAME) ||
- authoredToolNames.has(LOAD_SKILL_TOOL_NAME)
- ? []
- : [LOAD_SKILL_TOOL_NAME]),
- ],
+ reservedToolNames: [WORKFLOW_TOOL_NAME],
},
);
- // Authored channels override framework defaults by matching logical name;
- // disable sentinels remove framework defaults with the same name.
- const authoredChannelNames = new Set(agent.channels.map((channel) => channel.name));
- const allFrameworkChannelNames = getAllFrameworkChannelNames();
-
- for (const disabledName of agent.disabledFrameworkChannels) {
- if (!allFrameworkChannelNames.has(disabledName)) {
- throw new ResolveRuntimeAgentGraphError(
- `agent/channels/${disabledName}.ts exports disableRoute() but "${disabledName}" is not a framework channel. ` +
- `Rename the file to one of: ${[...allFrameworkChannelNames].sort().join(", ")}.`,
- {
- nodeId,
- sourceId: input.sourceId,
- },
- );
- }
- }
-
- const disabledFrameworkChannels = new Set(agent.disabledFrameworkChannels);
- const activeFrameworkChannels = getFrameworkChannelDefinitions().filter(
- (channel) =>
- !authoredChannelNames.has(channel.name) && !disabledFrameworkChannels.has(channel.name),
- );
- const channels: readonly ResolvedChannelDefinition[] = [
- ...activeFrameworkChannels,
- ...agent.channels,
- ];
const sandboxRegistry = createRuntimeSandboxRegistry({
- authoredSandbox: agent.sandbox,
+ sandbox: agent.sandbox,
workspaceResourceRoot: agent.workspaceResourceRoot,
});
const subagentRegistry = createRuntimeSubagentRegistry({
@@ -238,22 +163,17 @@ async function resolveRuntimeAgentNode(
subagentNodesById: input.subagentNodesById,
}),
});
- const resolvedAgent = {
- ...agent,
- dynamicToolResolvers: [...agent.dynamicToolResolvers, ...getFrameworkDynamicToolResolvers()],
- };
-
const node: ResolvedAgentGraphBundle["root"] = {
- agent: resolvedAgent,
- channels,
- hookRegistry: createRuntimeHookRegistry(resolvedAgent.hooks),
+ agent,
+ channels: agent.channels,
+ hookRegistry: createRuntimeHookRegistry(agent.hooks),
nodeId,
sandboxRegistry,
sourceId: input.sourceId,
subagentRegistry,
toolRegistry,
turnAgent: createResolvedRuntimeTurnAgent({
- agent: resolvedAgent,
+ agent,
id: input.agentId,
nodeId,
tools: [...toolRegistry.preparedTools, ...subagentRegistry.preparedTools],
@@ -470,7 +390,7 @@ function attachInheritedSandboxWorkspaceResources(input: {
readonly nodesByNodeId: ReadonlyMap<string, ResolvedAgentGraphBundle["root"]>;
}): void {
const parentNodeIdByChildNodeId = new Map(
- input.manifest.subagentEdges.map((edge) => [edge.childNodeId, edge.parentNodeId]),
+ input.manifest.subagents.map((subagent) => [subagent.nodeId, subagent.parentNodeId]),
);
for (const [nodeId, node] of input.nodesByNodeId) {
@@ -539,15 +459,15 @@ function createChildNodeIdsByParentNodeId(
): ReadonlyMap<string, readonly string[]> {
const childNodeIdsByParentNodeId = new Map<string, string[]>();
- for (const edge of manifest.subagentEdges) {
- const existing = childNodeIdsByParentNodeId.get(edge.parentNodeId);
+ for (const subagent of manifest.subagents) {
+ const existing = childNodeIdsByParentNodeId.get(subagent.parentNodeId);
if (existing === undefined) {
- childNodeIdsByParentNodeId.set(edge.parentNodeId, [edge.childNodeId]);
+ childNodeIdsByParentNodeId.set(subagent.parentNodeId, [subagent.nodeId]);
continue;
}
- existing.push(edge.childNodeId);
+ existing.push(subagent.nodeId);
}
return childNodeIdsByParentNodeId;
diff --git a/packages/eve/src/runtime/resolve-agent.ts b/packages/eve/src/runtime/resolve-agent.ts
index d307163e7..f1dde857a 100644
--- a/packages/eve/src/runtime/resolve-agent.ts
+++ b/packages/eve/src/runtime/resolve-agent.ts
@@ -3,6 +3,7 @@ import type {
CompiledAgentResources,
CompiledInstructionsDefinition,
} from "#compiler/manifest.js";
+import type { AgentSourceOwner } from "#compiler/source-graph.js";
import type { CompiledModuleMap } from "#compiler/module-map.js";
import { resolveChannelDefinition } from "#runtime/resolve-channel.js";
@@ -41,6 +42,7 @@ export interface ResolveAgentInput {
export async function resolveAgent(input: ResolveAgentInput): Promise<ResolvedAgent> {
const resolvedSkills = input.manifest.skills.map((skill) => ({
...skill,
+ owner: requireCompiledSourceOwner(input.manifest, skill),
metadata:
skill.metadata === undefined
? undefined
@@ -48,24 +50,19 @@ export async function resolveAgent(input: ResolveAgentInput): Promise<ResolvedAg
...skill.metadata,
},
})) satisfies ResolvedSkillDefinition[];
- // Disabled channel entries (kind === "disabled") are filtered out here
- // and surfaced separately on `ResolvedAgent.disabledFrameworkChannels`
- // so the graph resolver can remove the corresponding framework defaults.
- const resolvedChannels: ResolvedChannelDefinition[] = [];
- const disabledFrameworkChannels: string[] = [];
-
- for (const channelEntry of input.manifest.channels) {
- if (channelEntry.kind === "disabled") {
- disabledFrameworkChannels.push(channelEntry.name);
- continue;
- }
- resolvedChannels.push(
- await resolveChannelDefinition(channelEntry, input.moduleMap, input.nodeId),
- );
- }
+ const resolvedChannels: ResolvedChannelDefinition[] = await Promise.all(
+ input.manifest.channelRoutes.effective.map((channelEntry) =>
+ resolveChannelDefinition(channelEntry, input.moduleMap, input.nodeId),
+ ),
+ );
const resolvedTools = await Promise.all(
input.manifest.tools.map((toolDefinition) =>
- resolveToolDefinition(toolDefinition, input.moduleMap, input.nodeId),
+ resolveToolDefinition(
+ toolDefinition,
+ input.moduleMap,
+ input.nodeId,
+ requireBindingOwner(input.manifest, toolDefinition.sourceId),
+ ),
),
);
const resolvedDynamicInstructionsResolvers = await Promise.all(
@@ -96,17 +93,18 @@ export async function resolveAgent(input: ResolveAgentInput): Promise<ResolvedAg
resolveConnectionDefinition(connectionDefinition, input.moduleMap, input.nodeId),
),
);
- const authoredSandbox =
- input.manifest.sandbox === null
- ? null
- : await resolveSandboxDefinition(input.manifest.sandbox, input.moduleMap, input.nodeId);
- const instructions = input.manifest.instructions.map(createResolvedInstructionsDefinition);
+ const authoredSandbox = await resolveSandboxDefinition(
+ input.manifest.sandbox,
+ input.moduleMap,
+ input.nodeId,
+ );
+ const instructions = input.manifest.instructions.map((definition) =>
+ createResolvedInstructionsDefinition(input.manifest, definition),
+ );
const workspaceResourceRoot = input.manifest.workspaceResourceRoot;
const resolvedAgent: ResolvedAgent = {
channels: resolvedChannels,
connections: resolvedConnections,
- disabledFrameworkChannels,
- disabledFrameworkTools: [...input.manifest.disabledFrameworkTools],
workflowTool:
input.manifest.workflowTool === undefined
? undefined
@@ -134,12 +132,23 @@ export async function resolveAgent(input: ResolveAgentInput): Promise<ResolvedAg
: resolvedAgent;
}
+function requireBindingOwner(
+ manifest: CompiledAgentNodeManifest | CompiledAgentResources,
+ sourceId: string,
+) {
+ const binding = manifest.bindings[sourceId];
+ if (binding === undefined) throw new Error(`Compiled source "${sourceId}" has no binding.`);
+ return binding.owner;
+}
+
function createResolvedInstructionsDefinition(
+ manifest: CompiledAgentNodeManifest | CompiledAgentResources,
instructions: CompiledInstructionsDefinition,
): ResolvedInstructionsDefinition {
return {
content: instructions.content,
name: instructions.name,
+ owner: requireCompiledSourceOwner(manifest, instructions),
logicalPath: instructions.logicalPath,
role: instructions.role,
sourceId: instructions.sourceId,
@@ -147,6 +156,20 @@ function createResolvedInstructionsDefinition(
};
}
+function requireCompiledSourceOwner(
+ manifest: CompiledAgentNodeManifest | CompiledAgentResources,
+ source: {
+ readonly owner?: AgentSourceOwner;
+ readonly sourceId: string;
+ },
+): AgentSourceOwner {
+ const owner = manifest.bindings[source.sourceId]?.owner ?? source.owner;
+ if (owner === undefined) {
+ throw new Error(`Compiled source "${source.sourceId}" has no owner.`);
+ }
+ return owner;
+}
+
function createResolvedAgentConfig(
manifest: CompiledAgentNodeManifest,
): NonNullable<ResolvedAgent["config"]> {
diff --git a/packages/eve/src/runtime/resolve-connection.test.ts b/packages/eve/src/runtime/resolve-connection.test.ts
index c183b31df..712873543 100644
--- a/packages/eve/src/runtime/resolve-connection.test.ts
+++ b/packages/eve/src/runtime/resolve-connection.test.ts
@@ -7,7 +7,7 @@ import {
import type { CompiledModuleMap } from "#compiler/module-map.js";
import type { ConnectionToolCallDefinition } from "#public/definitions/connections/tool-call.js";
import { resolveConnectionDefinition } from "#runtime/resolve-connection.js";
-import type { ConnectionAuthResolver, HeadersDefinition } from "#runtime/connections/types.js";
+import type { ConnectionAuthResolver, HeadersDefinition } from "#shared/connection-types.js";
describe("resolveConnectionDefinition", () => {
it("preserves live MCP callbacks for request-time resolution", async () => {
diff --git a/packages/eve/src/runtime/resolve-connection.ts b/packages/eve/src/runtime/resolve-connection.ts
index beaa42d18..ed95ccb7e 100644
--- a/packages/eve/src/runtime/resolve-connection.ts
+++ b/packages/eve/src/runtime/resolve-connection.ts
@@ -8,8 +8,8 @@ import type {
ConnectionAuthResolver,
HeadersDefinition,
ToolFilterDefinition,
-} from "#runtime/connections/types.js";
-import { normalizeAuthorizationSpec } from "#runtime/connections/validate-authorization.js";
+} from "#shared/connection-types.js";
+import { normalizeAuthorizationSpec } from "#shared/validate-authorization.js";
import { loadResolvedModuleExport, ResolveAgentError } from "#runtime/resolve-helpers.js";
import type { ResolvedConnectionDefinition } from "#runtime/types.js";
diff --git a/packages/eve/src/runtime/resolve-hook.test.ts b/packages/eve/src/runtime/resolve-hook.test.ts
index aa15b0721..8abf050e5 100644
--- a/packages/eve/src/runtime/resolve-hook.test.ts
+++ b/packages/eve/src/runtime/resolve-hook.test.ts
@@ -23,6 +23,7 @@ function buildModuleMap(sourceId: string, moduleNamespace: unknown): CompiledMod
function buildDefinition(input: { readonly slug: string }): CompiledHookDefinition {
return {
+ eventNames: [],
exportName: undefined,
logicalPath: `agent/hooks/${input.slug}.ts`,
slug: input.slug,
diff --git a/packages/eve/src/runtime/resolve-tool.ts b/packages/eve/src/runtime/resolve-tool.ts
index 29bfc4826..f88774e5c 100644
--- a/packages/eve/src/runtime/resolve-tool.ts
+++ b/packages/eve/src/runtime/resolve-tool.ts
@@ -7,6 +7,7 @@ import { isToolSchema, toInputSchema, toOutputSchema } from "#shared/tool-schema
import { toErrorMessage } from "#shared/errors.js";
import { loadResolvedModuleExport, ResolveAgentError } from "#runtime/resolve-helpers.js";
import type { ResolvedToolDefinition } from "#runtime/types.js";
+import type { AgentSourceOwner } from "#compiler/source-graph.js";
/**
* Resolves one compiled authored tool into a runtime-owned definition
@@ -21,7 +22,20 @@ export async function resolveToolDefinition(
definition: CompiledToolDefinition,
moduleMap: CompiledModuleMap,
nodeId: string | undefined,
+ owner: AgentSourceOwner,
): Promise<ResolvedToolDefinition> {
+ if (!definition.hasExecute) {
+ return {
+ description: definition.description,
+ inputSchema: toInputSchema(definition.inputSchema),
+ logicalPath: definition.logicalPath,
+ name: definition.name,
+ outputSchema: toOutputSchema(definition.outputSchema),
+ owner,
+ sourceId: definition.sourceId,
+ sourceKind: "module",
+ };
+ }
try {
const resolvedExportValue = await loadResolvedModuleExport({
definition,
@@ -38,6 +52,7 @@ export async function resolveToolDefinition(
kind: "tool",
logicalPath: definition.logicalPath,
name: definition.name,
+ owner,
} as const;
const sourceKey = `tool-source:${definition.sourceId}`;
@@ -48,7 +63,7 @@ export async function resolveToolDefinition(
const execute = expectFunction(
resolvedRecord.execute,
describe(definition, "to provide an execute function"),
- ) as ResolvedToolDefinition["execute"];
+ ) as NonNullable<ResolvedToolDefinition["execute"]>;
const inputSchema = isToolSchema(resolvedRecord.inputSchema)
? resolvedRecord.inputSchema
: toInputSchema(definition.inputSchema);
@@ -64,6 +79,7 @@ export async function resolveToolDefinition(
inputSchema,
logicalPath: definition.logicalPath,
name: definition.name,
+ owner,
outputSchema,
sourceId: definition.sourceId,
sourceKind: "module",
diff --git a/packages/eve/src/runtime/sandbox/keys.test.ts b/packages/eve/src/runtime/sandbox/keys.test.ts
index 1fe110db6..2621ad785 100644
--- a/packages/eve/src/runtime/sandbox/keys.test.ts
+++ b/packages/eve/src/runtime/sandbox/keys.test.ts
@@ -6,7 +6,7 @@ import {
COMPILE_METADATA_VERSION,
type CompileMetadata,
} from "#compiler/artifacts.js";
-import { createCompiledAgentManifest } from "#compiler/manifest.js";
+import { compileFromMemory } from "#compiler/compile-from-memory.js";
import { resolveInstalledPackageInfo } from "#internal/application/package.js";
import { createFakeVercelOidcToken } from "#internal/testing/vercel-oidc-token.js";
import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
@@ -23,6 +23,7 @@ const CONTENT_HASH = "a".repeat(64);
function createMetadataFixture(generatorVersion: string): CompileMetadata {
return {
compile: {
+ manifest: { path: ".eve/compile/agent-manifest.json", sha256: "a".repeat(64) },
moduleMap: { path: ".eve/compile/module-map.mjs", sha256: "b".repeat(64) },
},
discovery: {
@@ -61,20 +62,18 @@ async function deriveTemplateKey(): Promise<string | null> {
});
}
-function withBundledMetadata<T>(
+async function withBundledMetadata<T>(
metadata: CompileMetadata | undefined,
fn: () => Promise<T>,
): Promise<T> {
- const manifest = createCompiledAgentManifest({
+ const { manifest, moduleMap } = await compileFromMemory({
agentRoot: "/virtual/app/agent",
appRoot: "/virtual/app",
- config: {
- model: { id: "openai/gpt-5-mini", routing: { kind: "gateway", target: "openai" } },
- name: "keys-test-agent",
- },
+ model: "openai/gpt-5.4",
+ name: "keys-test-agent",
});
- return withBundledCompiledArtifacts({ manifest, metadata, moduleMap: { nodes: {} } }, fn);
+ return await withBundledCompiledArtifacts({ manifest, metadata, moduleMap }, fn);
}
async function deriveSessionKey(input?: {
diff --git a/packages/eve/src/runtime/sandbox/registry.test.ts b/packages/eve/src/runtime/sandbox/registry.test.ts
index 01d932f56..c5b2e6ec8 100644
--- a/packages/eve/src/runtime/sandbox/registry.test.ts
+++ b/packages/eve/src/runtime/sandbox/registry.test.ts
@@ -15,7 +15,7 @@ describe("createRuntimeSandboxRegistry", () => {
it("allows an empty child to inherit its parent sandbox", () => {
expect(
createRuntimeSandboxRegistry({
- authoredSandbox: inheritedDefinition,
+ sandbox: inheritedDefinition,
workspaceResourceRoot: { logicalPath: "", rootEntries: [] },
}),
).toMatchObject({
@@ -26,7 +26,7 @@ describe("createRuntimeSandboxRegistry", () => {
it("rejects child workspace resources when inheriting the parent sandbox", () => {
expect(() =>
createRuntimeSandboxRegistry({
- authoredSandbox: inheritedDefinition,
+ sandbox: inheritedDefinition,
workspaceResourceRoot: {
contentHash: "child-content",
logicalPath: "workspace-resources/foo",
diff --git a/packages/eve/src/runtime/sandbox/registry.ts b/packages/eve/src/runtime/sandbox/registry.ts
index 8ffb851af..b5ee3b5fa 100644
--- a/packages/eve/src/runtime/sandbox/registry.ts
+++ b/packages/eve/src/runtime/sandbox/registry.ts
@@ -1,5 +1,4 @@
import type { CompiledWorkspaceResourceRoot } from "#compiler/manifest.js";
-import { defaultSandbox } from "#public/sandbox/backends/default.js";
import type { ResolvedSandboxDefinition } from "#runtime/types.js";
/**
@@ -9,8 +8,6 @@ import type { ResolvedSandboxDefinition } from "#runtime/types.js";
* to distinguish the shared framework sandbox from per-node authored
* overrides.
*/
-export const DEFAULT_SANDBOX_SOURCE_ID = "eve:default-sandbox";
-
/**
* Resolved sandbox tracked by the runtime-owned registry.
*
@@ -40,9 +37,8 @@ export interface RuntimeRegisteredSandbox {
* startup path.
*
* Every agent owns exactly one sandbox, so the registry is just a
- * single record. When the author provides a `sandbox.<ext>` (or
- * `sandbox/sandbox.<ext>`) override, that authored definition replaces
- * the framework default. Production always populates it; tests that
+ * single record populated from the selected compiled sandbox source.
+ * Production always populates it; tests that
* need a `null` sandbox cast through `as RuntimeSandboxRegistry`.
*/
export interface RuntimeSandboxRegistry {
@@ -50,15 +46,13 @@ export interface RuntimeSandboxRegistry {
}
/**
- * Builds the runtime-owned registry for one resolved authored agent's
- * sandbox, preferring the authored override and falling back to the
- * framework default.
+ * Builds the runtime-owned registry for one selected compiled sandbox.
*/
export function createRuntimeSandboxRegistry(input: {
- readonly authoredSandbox: ResolvedSandboxDefinition | null;
+ readonly sandbox: ResolvedSandboxDefinition;
readonly workspaceResourceRoot: CompiledWorkspaceResourceRoot;
}): RuntimeSandboxRegistry {
- const definition = input.authoredSandbox ?? createFrameworkSandboxDefinition();
+ const definition = input.sandbox;
if (
definition.inheritsParent === true &&
(input.workspaceResourceRoot.contentHash !== undefined ||
@@ -75,23 +69,3 @@ export function createRuntimeSandboxRegistry(input: {
},
};
}
-
-/**
- * Builds the framework default sandbox definition used when no agent
- * authored override is present.
- *
- * The `backend` is resolved through {@link defaultSandbox} on each
- * call so the framework default picks up the same environment-aware
- * fallback as authored sandboxes that omit `backend` (`vercel()`
- * on hosted Vercel, then Docker, microsandbox, or just-bash by availability). Implemented as
- * a factory rather than a constant so the environment is read at
- * graph-resolution time rather than at module-load time.
- */
-export function createFrameworkSandboxDefinition(): ResolvedSandboxDefinition {
- return {
- backend: defaultSandbox(),
- logicalPath: "eve:framework/default-sandbox",
- sourceId: DEFAULT_SANDBOX_SOURCE_ID,
- sourceKind: "module",
- };
-}
diff --git a/packages/eve/src/runtime/session-callback-route.test.ts b/packages/eve/src/runtime/session-callback-route.test.ts
index c2150b515..f830af783 100644
--- a/packages/eve/src/runtime/session-callback-route.test.ts
+++ b/packages/eve/src/runtime/session-callback-route.test.ts
@@ -1,13 +1,7 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { EVE_CALLBACK_ROUTE_PATTERN } from "#protocol/routes.js";
import type { RouteContext } from "#public/definitions/channel.js";
-import {
- getSessionCallbackChannelDefinitions,
- getSessionCallbackChannelNames,
- handleSessionCallbackRequest,
- HTTP_SESSION_CALLBACK_CHANNEL_NAME_PREFIX,
-} from "#runtime/session-callback-route.js";
+import { handleSessionCallbackRequest } from "#execution/session-callback-route.js";
const resumeHookMock = vi.fn();
const TASK_ID = "task_1";
@@ -22,22 +16,6 @@ describe("session callback route", () => {
resumeHookMock.mockReset();
});
- it("registers the POST framework callback route", () => {
- expect(getSessionCallbackChannelDefinitions()).toEqual([
- expect.objectContaining({
- method: "POST",
- name: `${HTTP_SESSION_CALLBACK_CHANNEL_NAME_PREFIX}/post`,
- urlPath: EVE_CALLBACK_ROUTE_PATTERN,
- }),
- ]);
- });
-
- it("uses route-aligned logical names for disableRoute", () => {
- const names = getSessionCallbackChannelNames();
- expect(names).toEqual(new Set([`${HTTP_SESSION_CALLBACK_CHANNEL_NAME_PREFIX}/post`]));
- expect([...names].some((name) => name.startsWith(".well-known/"))).toBe(false);
- });
-
it("forwards remote task turn-start identity to the task hook", async () => {
resumeHookMock.mockResolvedValue(undefined);
const response = await handleSessionCallbackRequest(
diff --git a/packages/eve/src/runtime/sessions/turn.ts b/packages/eve/src/runtime/sessions/turn.ts
index 288818aa1..f3644111c 100644
--- a/packages/eve/src/runtime/sessions/turn.ts
+++ b/packages/eve/src/runtime/sessions/turn.ts
@@ -1,6 +1,7 @@
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 { AgentSourceOwner } from "#compiler/source-graph.js";
/**
* Serializable authored tool descriptor prepared by the runtime for one
@@ -10,6 +11,7 @@ export type PreparedRuntimeAuthoredTool = Readonly<
InternalToolDefinition &
SourceRef & {
kind: "authored-tool";
+ owner: AgentSourceOwner;
}
>;
diff --git a/packages/eve/src/runtime/skills/sandbox-access.ts b/packages/eve/src/runtime/skills/sandbox-access.ts
index 1bb965075..7314f5bc5 100644
--- a/packages/eve/src/runtime/skills/sandbox-access.ts
+++ b/packages/eve/src/runtime/skills/sandbox-access.ts
@@ -1,6 +1,6 @@
import type { SandboxSession } from "#public/definitions/sandbox.js";
import type { SandboxAccess } from "#sandbox/state.js";
-import type { SkillHandle } from "#execution/skills/types.js";
+import type { SkillHandle } from "#shared/skill-types.js";
import { resolveSandboxSkillReadPaths } from "#shared/skill-paths.js";
const FRONTMATTER_PATTERN = /^---\r?\n[\s\S]*?\r?\n---\r?\n?/;
diff --git a/packages/eve/src/runtime/subagents/registry.ts b/packages/eve/src/runtime/subagents/registry.ts
index 8a3f58df9..282c25476 100644
--- a/packages/eve/src/runtime/subagents/registry.ts
+++ b/packages/eve/src/runtime/subagents/registry.ts
@@ -1,5 +1,3 @@
-import { z } from "#compiled/zod/index.js";
-
import { RuntimeRegistry, RuntimeRegistryError } from "#internal/runtime-registry.js";
import type { PreparedRuntimeDelegationTool } from "#runtime/sessions/turn.js";
import type {
@@ -8,6 +6,10 @@ import type {
} from "#runtime/types.js";
import type { JsonObject } from "#shared/json.js";
import { serializeInputSchema } from "#shared/tool-schema.js";
+import {
+ PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA,
+ SUBAGENT_TOOL_INPUT_SCHEMA,
+} from "#shared/agent-tool.js";
/**
* One runtime-owned subagent tracked by the prepared registry.
@@ -38,35 +40,6 @@ export interface RuntimeSubagentRegistry {
* Stable input schema lowered onto every subagent tool. Subagents always
* accept one free-form `message` string from the parent agent.
*/
-export const SUBAGENT_TOOL_INPUT_SCHEMA = z.strictObject({
- message: z
- .string()
- .describe(
- "The message to send to the subagent. Provide all context the subagent needs to complete the task; the subagent does not see the parent's history.",
- ),
- outputSchema: z
- .looseObject({})
- .describe(
- "Only provide a non-empty JSON Schema when the caller explicitly requests structured output; otherwise omit this field. The subagent must match a provided schema, and that structured output becomes the tool result.",
- )
- .optional(),
-});
-
-/**
- * Extended subagent tool input schema for agents that opt into
- * `experimental.subagentPersistentSessions`: adds the `agentId` field the
- * model uses to continue a previous delegation.
- */
-export const PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA = SUBAGENT_TOOL_INPUT_SCHEMA.extend({
- agentId: z
- .string()
- .nullable()
- .describe(
- "Only pass this to continue a previous delegation: the id of an agent from the <agents> list. To start a new agent — the common case — omit this field entirely (or pass null or an empty string).",
- )
- .optional(),
-});
-
const SUBAGENT_TOOL_INPUT_JSON_SCHEMA = serializeInputSchema(SUBAGENT_TOOL_INPUT_SCHEMA);
const PERSISTENT_SUBAGENT_TOOL_INPUT_JSON_SCHEMA = serializeInputSchema(
diff --git a/packages/eve/src/runtime/task-input-response-route.test.ts b/packages/eve/src/runtime/task-input-response-route.test.ts
index 632b33773..20ca5bb94 100644
--- a/packages/eve/src/runtime/task-input-response-route.test.ts
+++ b/packages/eve/src/runtime/task-input-response-route.test.ts
@@ -1,12 +1,8 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { sessionInboxWire } from "#execution/wire/session-inbox-encoder.js";
-import { EVE_TASK_INPUT_ROUTE_PATTERN } from "#protocol/routes.js";
import type { RouteContext } from "#public/definitions/channel.js";
-import {
- getTaskInputResponseChannelDefinitions,
- handleTaskInputResponseRequest,
-} from "#runtime/task-input-response-route.js";
+import { handleTaskInputResponseRequest } from "#execution/task-input-response-route.js";
const resumeHookMock = vi.fn();
const getHookByTokenMock = vi.fn();
@@ -31,12 +27,6 @@ describe("task input response capability", () => {
resumeHookMock.mockReset();
});
- it("registers one capability-scoped POST route", () => {
- expect(getTaskInputResponseChannelDefinitions()).toEqual([
- expect.objectContaining({ method: "POST", urlPath: EVE_TASK_INPUT_ROUTE_PATTERN }),
- ]);
- });
-
it("resumes only the addressed child input batch", async () => {
resumeHookMock.mockResolvedValue(undefined);
const response = await handleTaskInputResponseRequest(
diff --git a/packages/eve/src/runtime/tools/registry.ts b/packages/eve/src/runtime/tools/registry.ts
index 5495ee112..2f038661c 100644
--- a/packages/eve/src/runtime/tools/registry.ts
+++ b/packages/eve/src/runtime/tools/registry.ts
@@ -79,6 +79,7 @@ async function createPreparedRuntimeTool(
kind: "authored-tool",
logicalPath: definition.logicalPath,
name: definition.name,
+ owner: definition.owner,
outputSchema: serializeOutputSchema(definition.outputSchema),
sourceId: definition.sourceId,
};
diff --git a/packages/eve/src/runtime/types.ts b/packages/eve/src/runtime/types.ts
index 3b7f87e80..1c9ce0d0b 100644
--- a/packages/eve/src/runtime/types.ts
+++ b/packages/eve/src/runtime/types.ts
@@ -17,7 +17,7 @@ import type {
ConnectionProtocol,
HeadersDefinition,
ToolFilterDefinition,
-} from "#runtime/connections/types.js";
+} from "#shared/connection-types.js";
import type { OpenAPISpecSource } from "#public/definitions/connections/openapi.js";
import type { CompiledWorkspaceResourceRoot } from "#compiler/manifest.js";
import type { WorkspaceRuntimeSpec } from "#runtime/workspace/types.js";
@@ -38,6 +38,7 @@ 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 { AgentSourceOwner } from "#compiler/source-graph.js";
/**
* Runtime-owned source ref describing one additive config module import.
@@ -56,6 +57,7 @@ export type ResolvedInstructionsDefinition = Readonly<
SourceRef & {
content: string;
name: string;
+ owner: AgentSourceOwner;
role: "system" | "user";
} & (Omit<MarkdownSourceRef<undefined>, "definition"> | ModuleSourceRef)
>;
@@ -127,7 +129,7 @@ export interface ResolvedConnectionDefinition extends ResolvedModuleSourceRef {
*
* The resolved `backend` is non-optional: every sandbox in the runtime
* graph carries a concrete SandboxBackend value, even when the
- * authored definition omits `backend`. The unauthored case is filled
+ * authored definition omits `backend`. The omitted field is filled
* in by `defaultSandbox()` (which itself selects between
* `vercel()`, `docker()`, `microsandbox()`, and `justbash()` based on the current
* environment).
@@ -150,8 +152,7 @@ export type ResolvedSandboxDefinition = ResolvedModuleSourceRef & {
};
/**
- * Runtime-owned tool definition resolved from a compiled module map or
- * declared by the framework catalog.
+ * Runtime-owned tool definition resolved from the selected compiled source graph.
* A tool without `execute` is surfaced to the client and never executed by eve.
*/
export type ResolvedToolDefinition = Readonly<
@@ -161,6 +162,7 @@ export type ResolvedToolDefinition = Readonly<
>
> &
ResolvedModuleSourceRef & {
+ readonly owner: AgentSourceOwner;
/**
* Validated runtime input schema. Compiled and durable JSON Schemas are
* rehydrated before entering this runtime-owned definition.
@@ -406,20 +408,6 @@ export interface ResolvedAgent {
readonly channels: readonly ResolvedChannelDefinition[];
readonly config?: ResolvedAgentDefinition;
readonly connections: readonly ResolvedConnectionDefinition[];
- /**
- * Logical names of framework-provided channels the author opted out of by
- * exporting `disableRoute()` from a file in `agent/channels/`. Each
- * entry is the slash-joined slug path of one such file. The graph
- * resolver uses this list to filter the framework default channel set.
- */
- readonly disabledFrameworkChannels: readonly string[];
- /**
- * Names of framework-provided tools the author opted out of by exporting
- * `disableTool()` from a file in `agent/tools/`. Each entry is the
- * filename slug of one such file. The graph resolver uses this list to
- * filter the framework default tool set.
- */
- readonly disabledFrameworkTools: readonly string[];
/**
* Configuration for the experimental framework `Workflow` orchestration
* tool. Present when an authored tool module exports
@@ -440,11 +428,7 @@ export interface ResolvedAgent {
* declare one.
*/
readonly instructions: readonly ResolvedInstructionsDefinition[];
- /**
- * Authored sandbox override for this agent, when one exists. `null`
- * means the agent uses the framework default sandbox unchanged.
- */
- readonly sandbox: ResolvedSandboxDefinition | null;
+ readonly sandbox: ResolvedSandboxDefinition;
/**
* Byte-free descriptor for the compiled workspace resource tree owned
* by this agent's graph node. The prewarm orchestrator resolves the
diff --git a/packages/eve/src/sandbox/backends/default.ts b/packages/eve/src/sandbox/backends/default.ts
new file mode 100644
index 000000000..97cb66227
--- /dev/null
+++ b/packages/eve/src/sandbox/backends/default.ts
@@ -0,0 +1,88 @@
+import {
+ isLinuxDockerDaemonAvailableSync,
+ isMicrosandboxPlatformSupported,
+} from "#execution/sandbox/bindings/local.js";
+import { lazyBackend } from "#execution/sandbox/lazy-backend.js";
+import type { SandboxBackend } from "#public/definitions/sandbox-backend.js";
+import { docker } from "#sandbox/backends/docker.js";
+import type { DockerSandboxCreateOptions } from "#public/sandbox/docker-sandbox.js";
+import { justbash } from "#sandbox/backends/just-bash.js";
+import type { JustBashSandboxCreateOptions } from "#public/sandbox/just-bash-sandbox.js";
+import { microsandbox } from "#sandbox/backends/microsandbox.js";
+import type { MicrosandboxSandboxCreateOptions } from "#public/sandbox/microsandbox-sandbox.js";
+import { vercel } from "#sandbox/backends/vercel.js";
+import type { VercelSandboxCreateOptions } from "#public/sandbox/vercel-sandbox.js";
+
+/**
+ * Input to {@link defaultSandbox}: a separate options bag per inner
+ * backend. The framework picks one backend at runtime based on
+ * availability and passes it the matching bag; the others are ignored.
+ */
+export interface DefaultSandboxOptions {
+ readonly docker?: DockerSandboxCreateOptions;
+ readonly justBash?: JustBashSandboxCreateOptions;
+ readonly microsandbox?: MicrosandboxSandboxCreateOptions;
+ readonly vercel?: VercelSandboxCreateOptions;
+}
+
+/**
+ * Availability probes behind {@link defaultSandbox}'s selection chain.
+ * Injectable so selection logic is testable without touching the host.
+ */
+export interface DefaultSandboxProbes {
+ readonly isDeployedOnVercel: () => boolean;
+ readonly isDockerAvailable: () => boolean;
+ readonly isMicrosandboxSupported: () => boolean;
+}
+
+// Wrapped in arrows (not captured by reference) deliberately: this
+// module participates in an import cycle through the runtime resolver,
+// so the probe imports may still be uninitialized live bindings when
+// this object literal evaluates. Accessing them at call time is safe.
+const PRODUCTION_PROBES: DefaultSandboxProbes = {
+ isDeployedOnVercel: () => Boolean(process.env.VERCEL),
+ isDockerAvailable: () => isLinuxDockerDaemonAvailableSync(),
+ isMicrosandboxSupported: () => isMicrosandboxPlatformSupported(),
+};
+
+/**
+ * Constructs an availability-aware sandbox backend. On first use it
+ * picks the best backend the host supports, in priority order:
+ *
+ * 1. **Vercel Sandbox** when deploying on Vercel (`process.env.VERCEL`
+ * is set) — local container/VM runtimes cannot run there.
+ * 2. **Docker** when a Linux-container Docker daemon is reachable.
+ * 3. **microsandbox** when the host supports it (macOS on Apple
+ * Silicon, or glibc Linux with KVM); `eve dev` auto-installs the
+ * package into the project.
+ * 4. **just-bash** as the dependency-free fallback; `eve dev`
+ * auto-installs the package into the project.
+ *
+ * The selection is cached for the process lifetime. To pin a backend
+ * unconditionally, configure its factory directly (`docker()`,
+ * `microsandbox()`, `justbash()`,
+ * `vercel()`).
+ */
+export function defaultSandbox(opts?: DefaultSandboxOptions): SandboxBackend {
+ return lazyBackend(() => selectDefaultSandbox(opts, PRODUCTION_PROBES));
+}
+
+/**
+ * The selection chain behind {@link defaultSandbox}. Internal —
+ * exported for tests, which inject probes.
+ */
+export function selectDefaultSandbox(
+ opts: DefaultSandboxOptions | undefined,
+ probes: DefaultSandboxProbes,
+): SandboxBackend {
+ if (probes.isDeployedOnVercel()) {
+ return vercel(opts?.vercel);
+ }
+ if (probes.isDockerAvailable()) {
+ return docker(opts?.docker);
+ }
+ if (probes.isMicrosandboxSupported()) {
+ return microsandbox(opts?.microsandbox);
+ }
+ return justbash(opts?.justBash);
+}
diff --git a/packages/eve/src/sandbox/backends/docker.ts b/packages/eve/src/sandbox/backends/docker.ts
new file mode 100644
index 000000000..6fbbcbb3e
--- /dev/null
+++ b/packages/eve/src/sandbox/backends/docker.ts
@@ -0,0 +1,19 @@
+import { createDockerSandboxBackend } from "#execution/sandbox/bindings/local.js";
+
+import type { SandboxBackend } from "#public/definitions/sandbox-backend.js";
+import type { DockerSandboxCreateOptions } from "#public/sandbox/docker-sandbox.js";
+
+/**
+ * Constructs the Docker sandbox backend: the workspace runs inside a
+ * real Linux container driven through the Docker CLI, using the
+ * official Ubuntu 26.04 image by default.
+ *
+ * Requires a running Docker-compatible daemon reachable through a
+ * `docker` CLI (Docker Desktop, OrbStack, Colima, Podman via its
+ * docker-compatible CLI, …; override the binary with `EVE_DOCKER_PATH`).
+ * Configuring this backend pins it unconditionally — when you want
+ * fallback behavior, use `defaultBackend()` instead.
+ */
+export function docker(opts?: DockerSandboxCreateOptions): SandboxBackend {
+ return createDockerSandboxBackend({ createOptions: opts });
+}
diff --git a/packages/eve/src/sandbox/backends/just-bash.ts b/packages/eve/src/sandbox/backends/just-bash.ts
new file mode 100644
index 000000000..8f773f329
--- /dev/null
+++ b/packages/eve/src/sandbox/backends/just-bash.ts
@@ -0,0 +1,22 @@
+import { createJustBashSandboxBackend } from "#execution/sandbox/bindings/local.js";
+
+import type { SandboxBackend } from "#public/definitions/sandbox-backend.js";
+import type { JustBashSandboxCreateOptions } from "#public/sandbox/just-bash-sandbox.js";
+
+/**
+ * Constructs the just-bash sandbox backend: a pure-JS bash interpreter
+ * over a virtual filesystem stored under `.eve/sandbox-cache/`. It
+ * needs no daemon or VM, but commands run in a simulated shell — no
+ * real binaries (`git`, `node`, package managers) and no network
+ * isolation.
+ *
+ * The `just-bash` package is not bundled with eve. When it is missing,
+ * `eve dev` installs it into the application automatically (disable
+ * with `autoInstall: false`); production processes fail with an
+ * actionable install error instead. Configuring this backend pins it
+ * unconditionally — when you want fallback behavior, use
+ * `defaultBackend()` instead.
+ */
+export function justbash(opts?: JustBashSandboxCreateOptions): SandboxBackend {
+ return createJustBashSandboxBackend({ createOptions: opts });
+}
diff --git a/packages/eve/src/sandbox/backends/microsandbox.ts b/packages/eve/src/sandbox/backends/microsandbox.ts
new file mode 100644
index 000000000..019a979f6
--- /dev/null
+++ b/packages/eve/src/sandbox/backends/microsandbox.ts
@@ -0,0 +1,28 @@
+import { createMicrosandboxSandboxBackend } from "#execution/sandbox/bindings/local.js";
+
+import type { SandboxBackend } from "#public/definitions/sandbox-backend.js";
+import type {
+ MicrosandboxBootstrapUseOptions,
+ MicrosandboxSandboxCreateOptions,
+ MicrosandboxSessionUseOptions,
+} from "#public/sandbox/microsandbox-sandbox.js";
+
+/**
+ * Constructs the microsandbox sandbox backend: lightweight local VMs
+ * via [microsandbox](https://www.npmjs.com/package/microsandbox) with
+ * snapshot-backed templates and a firewall capable of domain-level
+ * network policies and credential brokering.
+ *
+ * Supported hosts: macOS on Apple Silicon, or Linux (glibc) with KVM
+ * enabled. The `microsandbox` package is not bundled with eve. When it
+ * (or its VM runtime) is missing, `eve dev` installs both
+ * automatically (disable with `setup: { autoInstall: false }`);
+ * production processes fail with actionable errors instead.
+ * Configuring this backend pins it unconditionally — when you want
+ * fallback behavior, use `defaultBackend()` instead.
+ */
+export function microsandbox(
+ opts?: MicrosandboxSandboxCreateOptions,
+): SandboxBackend<MicrosandboxBootstrapUseOptions, MicrosandboxSessionUseOptions> {
+ return createMicrosandboxSandboxBackend({ createOptions: opts });
+}
diff --git a/packages/eve/src/sandbox/backends/vercel.ts b/packages/eve/src/sandbox/backends/vercel.ts
new file mode 100644
index 000000000..b659a6091
--- /dev/null
+++ b/packages/eve/src/sandbox/backends/vercel.ts
@@ -0,0 +1,45 @@
+import { createVercelSandbox } from "#execution/sandbox/bindings/vercel.js";
+
+import type { SandboxBackend } from "#public/definitions/sandbox-backend.js";
+import type {
+ VercelSandboxBootstrapUseOptions,
+ VercelSandboxOptions,
+ VercelSandboxSessionUseOptions,
+} from "#public/sandbox/vercel-sandbox.js";
+
+/**
+ * Constructs the [Vercel Sandbox](https://vercel.com/docs/sandbox)
+ * backend. Configuring this backend pins it unconditionally —
+ * including for local development, where it creates real hosted
+ * sandboxes (requires Vercel credentials).
+ *
+ * The optional provider creation fields are forwarded to Vercel Sandbox creation
+ * for every fresh sandbox the framework creates (template at prewarm,
+ * session at first-time create). On resume (`Sandbox.get`), no create
+ * happens, so opts are not re-applied. `networkPolicy` is applied after
+ * framework-owned base setup for fresh templates and template-less
+ * sessions, before authored bootstrap code runs.
+ *
+ * `opts.source`, if supplied, is used only on the template create:
+ * the author's snapshot, git revision, or tarball becomes the base
+ * layer of the template. Bootstrap, seed files, and framework setup
+ * still run on top, and every session derives from the resulting
+ * eve-owned snapshot. `source` is stripped from session creates so the
+ * framework's snapshot always wins.
+ *
+ * `bootstrap({ use })` applies its options to the template via
+ * `sandbox.update(...)`; those settings persist into the snapshot.
+ * `onSession({ use })` applies its options to the live session via the
+ * SDK's `update` under the hood, overriding any overlapping field
+ * from `opts`. `sessionCreateOptions`, when provided, is resolved only
+ * when creating a fresh live session and can attach session-specific Drives.
+ */
+export function vercel(
+ opts?: VercelSandboxOptions,
+): SandboxBackend<VercelSandboxBootstrapUseOptions, VercelSandboxSessionUseOptions> {
+ const { sessionCreateOptions, ...createOptions } = opts ?? {};
+ return createVercelSandbox({
+ createOptions,
+ resolveSessionCreateOptions: sessionCreateOptions,
+ });
+}
diff --git a/packages/eve/src/services/dev-client.ts b/packages/eve/src/services/dev-client.ts
index 5a4aa35e8..405390169 100644
--- a/packages/eve/src/services/dev-client.ts
+++ b/packages/eve/src/services/dev-client.ts
@@ -1,5 +1,5 @@
import type { UserContent } from "ai";
-import type { InputResponse } from "#runtime/input/types.js";
+import type { InputResponse } from "#shared/input.js";
import { isLocalDevelopmentServerUrl } from "#services/dev-client/local-host.js";
import {
readDevelopmentRuntimeArtifactsRevision,
diff --git a/packages/eve/src/services/dev-client/agent-info-probe.test.ts b/packages/eve/src/services/dev-client/agent-info-probe.test.ts
index 6518a4c56..1806cb6d6 100644
--- a/packages/eve/src/services/dev-client/agent-info-probe.test.ts
+++ b/packages/eve/src/services/dev-client/agent-info-probe.test.ts
@@ -6,40 +6,14 @@ import {
type AgentInfoResult,
type Client,
} from "#client/index.js";
+import { createTestAgentInfoResult } from "#internal/testing/agent-info-fixture.js";
import { probeAgentInfo } from "./agent-info-probe.js";
-const AGENT_INFO = {
- agent: {
- agentRoot: "/tmp/weather-agent/agent",
- appRoot: "/tmp/weather-agent",
- model: { id: "gpt-5", routing: { kind: "gateway", target: "openai" } },
- name: "Weather Agent",
- },
- capabilities: { devRoutes: true },
- channels: { authored: [], available: [], disabledFramework: [], framework: [] },
- connections: [],
- diagnostics: { discoveryErrors: 0, discoveryWarnings: 0 },
- hooks: [],
- instructions: { dynamic: [], static: [] },
- kind: "eve-agent-info",
- mode: "development",
- sandbox: null,
- schedules: [],
- skills: { dynamic: [], static: [] },
- subagents: { local: [], total: 0 },
- tools: {
- authored: [],
- available: [],
- disabledFramework: [],
- dynamic: [],
- framework: [],
- reserved: [],
- },
- version: 2,
- workflow: { enabled: false, toolName: "Workflow" },
- workspace: { resourceRoot: null, rootEntries: [] },
-} satisfies AgentInfoResult;
+const AGENT_INFO = createTestAgentInfoResult({
+ modelId: "gpt-5",
+ name: "Weather Agent",
+}) satisfies AgentInfoResult;
async function advanceRetry(): Promise<void> {
await Promise.resolve();
diff --git a/packages/eve/src/services/dev-client/runtime-artifacts.ts b/packages/eve/src/services/dev-client/runtime-artifacts.ts
index 5ff93c703..950ddd4a7 100644
--- a/packages/eve/src/services/dev-client/runtime-artifacts.ts
+++ b/packages/eve/src/services/dev-client/runtime-artifacts.ts
@@ -17,10 +17,22 @@ import {
*/
export async function readDevelopmentRuntimeArtifactsRevision(input: {
readonly serverUrl: string;
+ readonly signal?: AbortSignal;
+ readonly timeoutMs?: number;
}): Promise<string | undefined> {
try {
const url = new URL(EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH, input.serverUrl);
- const response = await fetch(url);
+ const timeoutSignal =
+ input.timeoutMs === undefined ? undefined : AbortSignal.timeout(input.timeoutMs);
+ const signal =
+ input.signal === undefined
+ ? timeoutSignal
+ : timeoutSignal === undefined
+ ? input.signal
+ : AbortSignal.any([input.signal, timeoutSignal]);
+ const request: RequestInit = { redirect: "error" };
+ if (signal !== undefined) request.signal = signal;
+ const response = await fetch(url, request);
return await parseDevelopmentRuntimeArtifactsRevision(response);
} catch {
return undefined;
diff --git a/packages/eve/src/setup/channel-add-conflicts.ts b/packages/eve/src/setup/channel-add-conflicts.ts
index da79c0dbe..77d9b22db 100644
--- a/packages/eve/src/setup/channel-add-conflicts.ts
+++ b/packages/eve/src/setup/channel-add-conflicts.ts
@@ -4,6 +4,7 @@ import { isNextJsProject, type ChannelKind } from "#setup/scaffold/index.js";
import type { DisabledChannelReasons } from "#setup/cli/index.js";
import { compileChannelDefinition } from "#compiler/normalize-channel.js";
+import type { CompiledModuleBinding } from "#compiler/source-graph.js";
import { discoverAgent } from "#discover/discover-agent.js";
import { EVE_SESSION_ROUTE_PATH } from "#protocol/routes.js";
@@ -43,9 +44,21 @@ export async function inspectExistingChannelRegistrations(
const slackOwners = new Set<string>();
for (const source of manifest.channels) {
- const compiled = await compileChannelDefinition(agentRoot, source);
- const definitions = Array.isArray(compiled) ? compiled : [compiled];
- for (const definition of definitions) {
+ const binding: CompiledModuleBinding = {
+ backing: {
+ externalDependencies: [],
+ kind: "filesystem",
+ sourcePath: join(agentRoot, source.logicalPath),
+ },
+ logicalPath: source.logicalPath,
+ owner: { kind: "application" },
+ };
+ const compiled = await compileChannelDefinition(agentRoot, source, {
+ binding,
+ registries: [],
+ });
+ if (compiled.kind !== "channel") continue;
+ for (const definition of compiled.definitions) {
if (definition.kind !== "channel") {
continue;
}
diff --git a/packages/eve/src/setup/cli/select-component.ts b/packages/eve/src/setup/cli/select-component.ts
index 4cf226bec..358f87f7f 100644
--- a/packages/eve/src/setup/cli/select-component.ts
+++ b/packages/eve/src/setup/cli/select-component.ts
@@ -1,5 +1,5 @@
import { isCancel, Prompt, type State } from "@clack/core";
-import pc from "picocolors";
+import pc from "#compiled/picocolors/index.js";
import {
renderMultiselectPrompt,
diff --git a/packages/eve/src/setup/flows/link.ts b/packages/eve/src/setup/flows/link.ts
index bcfabbfa4..c8598cde9 100644
--- a/packages/eve/src/setup/flows/link.ts
+++ b/packages/eve/src/setup/flows/link.ts
@@ -21,7 +21,7 @@ import { WizardCancelledError } from "../step.js";
import { runInteractive, type AnySetupBox } from "../runner.js";
import { snapshotSetupState, type SetupState } from "../state.js";
import { withSpinner } from "../with-spinner.js";
-import pc from "picocolors";
+import pc from "#compiled/picocolors/index.js";
import { inProjectSetupState, prompterSink } from "./in-project.js";
diff --git a/packages/eve/src/setup/flows/model-source-change.ts b/packages/eve/src/setup/flows/model-source-change.ts
index 8effc82e5..f3b3a4013 100644
--- a/packages/eve/src/setup/flows/model-source-change.ts
+++ b/packages/eve/src/setup/flows/model-source-change.ts
@@ -14,7 +14,7 @@ import {
} from "#shared/chatgpt-model.js";
import { createStaticSourceChange } from "#source-change/static-source-change.js";
-import pc from "picocolors";
+import pc from "#compiled/picocolors/index.js";
export type ApplyModelSettingsOutcome =
| {
diff --git a/packages/eve/src/setup/flows/model.ts b/packages/eve/src/setup/flows/model.ts
index 9d873ac59..9e6de3b65 100644
--- a/packages/eve/src/setup/flows/model.ts
+++ b/packages/eve/src/setup/flows/model.ts
@@ -10,7 +10,7 @@ import type {
FieldPatch,
} from "#source-change/apply-agent-model-settings.js";
-import pc from "picocolors";
+import pc from "#compiled/picocolors/index.js";
import { AI_GATEWAY_API_KEY_ENV_VAR } from "../ai-gateway-api-key.js";
import {
diff --git a/packages/eve/src/setup/prompter.ts b/packages/eve/src/setup/prompter.ts
index 6973a42ef..643ce6c36 100644
--- a/packages/eve/src/setup/prompter.ts
+++ b/packages/eve/src/setup/prompter.ts
@@ -14,7 +14,7 @@ import {
type SetupSpinnerIntent,
} from "#setup/cli/index.js";
import { createRailLog, type RailSpinner } from "#setup/cli/index.js";
-import pc from "picocolors";
+import pc from "#compiled/picocolors/index.js";
import {
initialQuitGuardState,
diff --git a/packages/eve/src/setup/vercel-project.ts b/packages/eve/src/setup/vercel-project.ts
index 5f42f9ae3..d7abcc99c 100644
--- a/packages/eve/src/setup/vercel-project.ts
+++ b/packages/eve/src/setup/vercel-project.ts
@@ -1,7 +1,7 @@
import { createPromptCommandOutput, whimsyFor } from "#setup/cli/index.js";
import { HumanActionRequiredError } from "#setup/human-action.js";
import { captureVercel, runVercel, type VercelCaptureFailure } from "#setup/primitives/index.js";
-import pc from "picocolors";
+import pc from "#compiled/picocolors/index.js";
import { z } from "zod";
import {
diff --git a/packages/eve/src/setup/verified-remote-agent.test.ts b/packages/eve/src/setup/verified-remote-agent.test.ts
index 5c8d28bd4..fe7317455 100644
--- a/packages/eve/src/setup/verified-remote-agent.test.ts
+++ b/packages/eve/src/setup/verified-remote-agent.test.ts
@@ -3,41 +3,15 @@ import { describe, expect, it, vi } from "vitest";
import { ClientError } from "#client/client-error.js";
import type { AgentInfoResult, ClientOptions } from "#client/types.js";
import { resolveTestVercelTarget } from "#internal/testing/verified-vercel-target.js";
+import { createTestAgentInfoResult } from "#internal/testing/agent-info-fixture.js";
import { createHeadlessPrompter } from "#setup/headless.js";
import { inspectVerifiedRemoteAgent } from "./verified-remote-agent.js";
-const info: AgentInfoResult = {
- agent: {
- agentRoot: "/tmp/weather-agent/agent",
- appRoot: "/tmp/weather-agent",
- model: { id: "openai/gpt-5.5", routing: { kind: "gateway", target: "openai" } },
- name: "Weather Agent",
- },
- capabilities: { devRoutes: true },
- channels: { authored: [], available: [], disabledFramework: [], framework: [] },
- connections: [],
- diagnostics: { discoveryErrors: 0, discoveryWarnings: 0 },
- hooks: [],
- instructions: { dynamic: [], static: [] },
- kind: "eve-agent-info",
- mode: "development",
- sandbox: null,
- schedules: [],
- skills: { dynamic: [], static: [] },
- subagents: { local: [], total: 0 },
- tools: {
- authored: [],
- available: [],
- disabledFramework: [],
- dynamic: [],
- framework: [],
- reserved: [],
- },
- version: 2,
- workflow: { enabled: false, toolName: "Workflow" },
- workspace: { resourceRoot: null, rootEntries: [] },
-};
+const info: AgentInfoResult = createTestAgentInfoResult({
+ modelId: "openai/gpt-5.5",
+ name: "Weather Agent",
+});
const target = await resolveTestVercelTarget({
host: "agent.example.com",
diff --git a/packages/eve/src/runtime/actions/types.ts b/packages/eve/src/shared/action-types.ts
similarity index 100%
rename from packages/eve/src/runtime/actions/types.ts
rename to packages/eve/src/shared/action-types.ts
diff --git a/packages/eve/src/shared/agent-tool.ts b/packages/eve/src/shared/agent-tool.ts
new file mode 100644
index 000000000..ff0bbcb12
--- /dev/null
+++ b/packages/eve/src/shared/agent-tool.ts
@@ -0,0 +1,34 @@
+import { z } from "#compiled/zod/index.js";
+
+export const AGENT_TOOL_NAME = "agent";
+
+export const AGENT_TOOL_DESCRIPTION = [
+ "Delegate a focused subtask to a fresh copy of yourself.",
+ "Use it to isolate complex work or split a large task into independent pieces.",
+ "Issue multiple `agent` calls in one response to run a small fixed set in parallel.",
+ "Each child has fresh history and state but shares your tools and sandbox, so include essential context in `message` and give parallel writers non-overlapping scopes.",
+].join(" ");
+
+export const SUBAGENT_TOOL_INPUT_SCHEMA = z.strictObject({
+ message: z
+ .string()
+ .describe(
+ "The message to send to the subagent. Provide all context the subagent needs to complete the task; the subagent does not see the parent's history.",
+ ),
+ outputSchema: z
+ .looseObject({})
+ .describe(
+ "Only provide a non-empty JSON Schema when the caller explicitly requests structured output; otherwise omit this field. The subagent must match a provided schema, and that structured output becomes the tool result.",
+ )
+ .optional(),
+});
+
+export const PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA = SUBAGENT_TOOL_INPUT_SCHEMA.extend({
+ agentId: z
+ .string()
+ .nullable()
+ .describe(
+ "Only pass this to continue a previous delegation: the id of an agent from the <agents> list. To start a new agent — the common case — omit this field entirely (or pass null or an empty string).",
+ )
+ .optional(),
+});
diff --git a/packages/eve/src/runtime/connections/types.ts b/packages/eve/src/shared/connection-types.ts
similarity index 97%
rename from packages/eve/src/runtime/connections/types.ts
rename to packages/eve/src/shared/connection-types.ts
index 535f19a1c..7c0b55447 100644
--- a/packages/eve/src/runtime/connections/types.ts
+++ b/packages/eve/src/shared/connection-types.ts
@@ -9,10 +9,8 @@
import type { ToolSet } from "ai";
import type { ConnectionAuthorizationChallenge } from "#public/connections/errors.js";
-import type { Approval } from "#public/definitions/approval.js";
import type { SessionContext } from "#public/definitions/callback-context.js";
import type { JsonValue } from "#public/types/json.js";
-import type { ResolvedConnectionDefinition } from "#runtime/types.js";
/**
* Credential returned by a connection's `getToken` or
@@ -454,12 +452,3 @@ export interface ConnectionClient {
getToolMetadata(): Promise<readonly ConnectionToolMetadata[]>;
getTools(): Promise<ToolSet>;
}
-
-/** Per-session container mapping connection names to clients. */
-export interface ConnectionRegistry {
- dispose(): Promise<void>;
- getClient(connectionName: string): ConnectionClient;
- getConnectionApproval(connectionName: string): Approval | undefined;
- getConnectionNames(): readonly string[];
- getConnections(): readonly ResolvedConnectionDefinition[];
-}
diff --git a/packages/eve/src/shared/eve-server-health.test.ts b/packages/eve/src/shared/eve-server-health.test.ts
deleted file mode 100644
index 02b144f69..000000000
--- a/packages/eve/src/shared/eve-server-health.test.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { afterEach, describe, expect, it, vi } from "vitest";
-
-import { isEveServerHealthy } from "./eve-server-health.js";
-
-afterEach(() => {
- vi.unstubAllGlobals();
-});
-
-describe("isEveServerHealthy", () => {
- it("refuses health redirects", async () => {
- const fetchMock = vi.fn(async (_url: string, options: RequestInit) => {
- expect(options.redirect).toBe("error");
- return new Response(null, { status: 200 });
- });
- vi.stubGlobal("fetch", fetchMock);
-
- await expect(isEveServerHealthy("http://127.0.0.1:2000")).resolves.toBe(true);
- expect(fetchMock).toHaveBeenCalledWith(
- "http://127.0.0.1:2000/eve/v1/health",
- expect.objectContaining({ redirect: "error", signal: expect.any(AbortSignal) }),
- );
- });
-});
diff --git a/packages/eve/src/shared/eve-server-health.ts b/packages/eve/src/shared/eve-server-health.ts
deleted file mode 100644
index 771ec350b..000000000
--- a/packages/eve/src/shared/eve-server-health.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { EVE_HEALTH_ROUTE_PATH } from "#protocol/routes.js";
-
-const DEFAULT_EVE_SERVER_HEALTH_TIMEOUT_MS = 1_000;
-
-/** Returns whether an Eve server answers its health route successfully. */
-export async function isEveServerHealthy(
- serverUrl: string,
- options: {
- readonly signal?: AbortSignal;
- readonly timeoutMs?: number;
- } = {},
-): Promise<boolean> {
- const timeoutSignal = AbortSignal.timeout(
- options.timeoutMs ?? DEFAULT_EVE_SERVER_HEALTH_TIMEOUT_MS,
- );
- const signal =
- options.signal === undefined ? timeoutSignal : AbortSignal.any([options.signal, timeoutSignal]);
-
- try {
- const healthUrl = new URL(EVE_HEALTH_ROUTE_PATH, serverUrl).toString();
- const response = await fetch(healthUrl, { redirect: "error", signal });
- return response.ok;
- } catch {
- return false;
- }
-}
diff --git a/packages/eve/src/runtime/input/types.ts b/packages/eve/src/shared/input.ts
similarity index 98%
rename from packages/eve/src/runtime/input/types.ts
rename to packages/eve/src/shared/input.ts
index c1d90e0ba..4f16813c8 100644
--- a/packages/eve/src/runtime/input/types.ts
+++ b/packages/eve/src/shared/input.ts
@@ -1,6 +1,6 @@
import { z } from "#compiled/zod/index.js";
-import { runtimeToolCallActionRequestSchema } from "#runtime/actions/types.js";
+import { runtimeToolCallActionRequestSchema } from "#shared/action-types.js";
/**
* One selectable option presented to the user in an input request.
diff --git a/packages/eve/src/runtime/sessions/auth.ts b/packages/eve/src/shared/session-auth.ts
similarity index 100%
rename from packages/eve/src/runtime/sessions/auth.ts
rename to packages/eve/src/shared/session-auth.ts
diff --git a/packages/eve/src/execution/skills/types.ts b/packages/eve/src/shared/skill-types.ts
similarity index 90%
rename from packages/eve/src/execution/skills/types.ts
rename to packages/eve/src/shared/skill-types.ts
index 4ff3ac2bb..5987d8e17 100644
--- a/packages/eve/src/execution/skills/types.ts
+++ b/packages/eve/src/shared/skill-types.ts
@@ -9,7 +9,7 @@ export interface SkillFile {
}
/**
- * Handle to one authored skill, returned by `ctx.getSkill()`.
+ * Public handle to one authored skill, returned by `ctx.getSkill()`.
*
* Exposes skill metadata and reads files from a skill package.
*/
diff --git a/packages/eve/src/shared/task-tool.ts b/packages/eve/src/shared/task-tool.ts
new file mode 100644
index 000000000..698eb3ad0
--- /dev/null
+++ b/packages/eve/src/shared/task-tool.ts
@@ -0,0 +1,59 @@
+import { z } from "#compiled/zod/index.js";
+
+export const TASK_CANCEL_TOOL_NAME = "task_cancel";
+export const TASK_UPDATE_TOOL_NAME = "task_update";
+
+/** Transitional PR 1 task-tool names used by the existing dispatch mechanics. */
+export const TASK_TOOL_NAMES: ReadonlySet<string> = new Set([
+ TASK_CANCEL_TOOL_NAME,
+ TASK_UPDATE_TOOL_NAME,
+]);
+
+/** Transitional PR 1 dispatch classifier, removed by the kernel-effects PR. */
+export const TASK_CONTROL_TOOL_NAMES = TASK_TOOL_NAMES;
+
+const TASK_IDS_SCHEMA = z
+ .array(z.string().min(1))
+ .min(1)
+ .describe("Task ids from earlier subagent task receipts.");
+
+export const TASK_CANCEL_INPUT_SCHEMA = z.strictObject({ taskIds: TASK_IDS_SCHEMA });
+
+export const TASK_UPDATE_INPUT_SCHEMA = z.strictObject({
+ message: z.string().min(1).describe("Brief description of what this task is currently doing."),
+});
+
+const TASK_VIEW_SCHEMA = z.object({
+ inputRequests: z.array(z.unknown()).optional(),
+ lastOutput: z
+ .object({
+ data: z.unknown(),
+ type: z.enum(["result", "error"]),
+ })
+ .optional(),
+ metadata: z.union([
+ z.object({
+ agentId: z.string(),
+ kind: z.literal("subagent"),
+ mode: z.enum(["local", "remote"]),
+ name: z.string(),
+ }),
+ z.object({
+ data: z.record(z.string(), z.unknown()).optional(),
+ kind: z.string(),
+ name: z.string(),
+ }),
+ ]),
+ status: z.enum(["working", "input_required", "completed", "failed", "cancelled"]),
+ taskId: z.string(),
+});
+
+export const TASK_VIEWS_OUTPUT_SCHEMA = z.object({
+ tasks: z.array(TASK_VIEW_SCHEMA),
+});
+
+export const SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA = z.strictObject({
+ agentId: z.string(),
+ status: z.literal("working"),
+ taskId: z.string(),
+});
diff --git a/packages/eve/src/runtime/connections/validate-authorization.ts b/packages/eve/src/shared/validate-authorization.ts
similarity index 99%
rename from packages/eve/src/runtime/connections/validate-authorization.ts
rename to packages/eve/src/shared/validate-authorization.ts
index 2ba525088..621a86f69 100644
--- a/packages/eve/src/runtime/connections/validate-authorization.ts
+++ b/packages/eve/src/shared/validate-authorization.ts
@@ -8,7 +8,7 @@ import type {
AuthorizationDefinition,
InteractiveAuthorizationDefinition,
NonInteractiveAuthorizationDefinition,
-} from "#runtime/connections/types.js";
+} from "#shared/connection-types.js";
/**
* Validates that authored `auth` conforms to the connection auth contract.
diff --git a/packages/eve/src/runtime/framework-tools/bash.ts b/packages/eve/src/tools/bash.ts
similarity index 66%
rename from packages/eve/src/runtime/framework-tools/bash.ts
rename to packages/eve/src/tools/bash.ts
index e3d775e00..1931d239c 100644
--- a/packages/eve/src/runtime/framework-tools/bash.ts
+++ b/packages/eve/src/tools/bash.ts
@@ -1,9 +1,7 @@
import { z } from "#compiled/zod/index.js";
-import { type BashInput, executeBashOnSandbox } from "#execution/sandbox/bash-tool.js";
-import { requireSandboxSession } from "#execution/sandbox/require-sandbox.js";
-import type { ResolvedToolDefinition } from "#runtime/types.js";
-import type { ToolExecuteOptions } from "#shared/tool-definition.js";
+import { executeBashOnSandbox, type BashInput } from "#execution/sandbox/bash-tool.js";
+import { defineTool } from "#public/definitions/tool.js";
/**
* Shared input schema used by the framework `bash` tool and any author tool
@@ -36,20 +34,13 @@ 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.
*/
-async function executeBash(input: unknown, options?: ToolExecuteOptions): Promise<unknown> {
- return executeBashOnSandbox(
- await requireSandboxSession(options?.abortSignal),
- input as BashInput,
- );
-}
-
-export const BASH_TOOL_DEFINITION: ResolvedToolDefinition = {
+export const bash = defineTool({
description: "Execute a shell command in the shared workspace environment.",
- execute: executeBash,
+ async execute(input, ctx) {
+ return await executeBashOnSandbox(await ctx.getSandbox(), input as BashInput);
+ },
inputSchema: BASH_INPUT_SCHEMA,
- logicalPath: "eve:framework/bash",
- name: "bash",
outputSchema: BASH_OUTPUT_SCHEMA,
- sourceId: "eve:bash-tool",
- sourceKind: "module",
-};
+});
+
+export default bash;
diff --git a/packages/eve/src/tools/connection-search.ts b/packages/eve/src/tools/connection-search.ts
new file mode 100644
index 000000000..177e42b10
--- /dev/null
+++ b/packages/eve/src/tools/connection-search.ts
@@ -0,0 +1,11 @@
+import { resolveConnectionSearchDynamicTools } from "#execution/tools/connection-search.js";
+import { defineDynamic } from "#public/definitions/tool.js";
+
+/** Canonical definition for dynamic connection tool discovery. */
+export const connectionSearch = defineDynamic({
+ events: {
+ "step.started": resolveConnectionSearchDynamicTools,
+ },
+});
+
+export default connectionSearch;
diff --git a/packages/eve/src/tools/define-bash-tool.ts b/packages/eve/src/tools/define-bash-tool.ts
new file mode 100644
index 000000000..71c23a3f5
--- /dev/null
+++ b/packages/eve/src/tools/define-bash-tool.ts
@@ -0,0 +1,34 @@
+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.ts
new file mode 100644
index 000000000..6c4ba8fc2
--- /dev/null
+++ b/packages/eve/src/tools/define-glob-tool.ts
@@ -0,0 +1,35 @@
+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.ts
new file mode 100644
index 000000000..0edf0a015
--- /dev/null
+++ b/packages/eve/src/tools/define-grep-tool.ts
@@ -0,0 +1,35 @@
+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.ts
new file mode 100644
index 000000000..6646d6181
--- /dev/null
+++ b/packages/eve/src/tools/define-read-file-tool.ts
@@ -0,0 +1,34 @@
+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.ts
new file mode 100644
index 000000000..b7d3567fb
--- /dev/null
+++ b/packages/eve/src/tools/define-write-file-tool.ts
@@ -0,0 +1,38 @@
+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/runtime/framework-tools/glob.ts b/packages/eve/src/tools/glob.ts
similarity index 71%
rename from packages/eve/src/runtime/framework-tools/glob.ts
rename to packages/eve/src/tools/glob.ts
index ae2b26be8..0d1738cf0 100644
--- a/packages/eve/src/runtime/framework-tools/glob.ts
+++ b/packages/eve/src/tools/glob.ts
@@ -1,9 +1,7 @@
import { z } from "#compiled/zod/index.js";
-import { executeGlobOnSandbox, type GlobInput } from "#execution/sandbox/glob-tool.js";
-import { requireSandboxSession } from "#execution/sandbox/require-sandbox.js";
-import type { ResolvedToolDefinition } from "#runtime/types.js";
-import type { ToolExecuteOptions } from "#shared/tool-definition.js";
+import { type GlobInput, executeGlobOnSandbox } from "#execution/sandbox/glob-tool.js";
+import { defineTool } from "#public/definitions/tool.js";
/**
* Shared input schema used by the framework `glob` tool and any author tool
@@ -47,14 +45,7 @@ export const GLOB_OUTPUT_SCHEMA = z.strictObject({
/**
* Framework-owned executor that delegates to the default sandbox.
*/
-async function executeGlob(input: unknown, options?: ToolExecuteOptions): Promise<unknown> {
- return executeGlobOnSandbox(
- await requireSandboxSession(options?.abortSignal),
- input as GlobInput,
- );
-}
-
-export const GLOB_TOOL_DEFINITION: ResolvedToolDefinition = {
+export const glob = defineTool({
description: [
"Fast file pattern matching tool that works with any codebase size.",
"",
@@ -63,11 +54,11 @@ export const GLOB_TOOL_DEFINITION: ResolvedToolDefinition = {
"- Returns matching file paths.",
"- Call this tool in parallel when you know there are multiple patterns to search for.",
].join("\n"),
- execute: executeGlob,
+ async execute(input, ctx) {
+ return await executeGlobOnSandbox(await ctx.getSandbox(), input as GlobInput);
+ },
inputSchema: GLOB_INPUT_SCHEMA,
- logicalPath: "eve:framework/glob",
- name: "glob",
outputSchema: GLOB_OUTPUT_SCHEMA,
- sourceId: "eve:glob-tool",
- sourceKind: "module",
-};
+});
+
+export default glob;
diff --git a/packages/eve/src/runtime/framework-tools/grep.ts b/packages/eve/src/tools/grep.ts
similarity index 78%
rename from packages/eve/src/runtime/framework-tools/grep.ts
rename to packages/eve/src/tools/grep.ts
index 65767bd50..644d43518 100644
--- a/packages/eve/src/runtime/framework-tools/grep.ts
+++ b/packages/eve/src/tools/grep.ts
@@ -1,9 +1,7 @@
import { z } from "#compiled/zod/index.js";
-import { executeGrepOnSandbox, type GrepInput } from "#execution/sandbox/grep-tool.js";
-import { requireSandboxSession } from "#execution/sandbox/require-sandbox.js";
-import type { ResolvedToolDefinition } from "#runtime/types.js";
-import type { ToolExecuteOptions } from "#shared/tool-definition.js";
+import { type GrepInput, executeGrepOnSandbox } from "#execution/sandbox/grep-tool.js";
+import { defineTool } from "#public/definitions/tool.js";
/**
* Shared input schema used by the framework `grep` tool and any author tool
@@ -68,14 +66,7 @@ export const GREP_OUTPUT_SCHEMA = z.strictObject({
/**
* Framework-owned executor that delegates to the default sandbox.
*/
-async function executeGrep(input: unknown, options?: ToolExecuteOptions): Promise<unknown> {
- return executeGrepOnSandbox(
- await requireSandboxSession(options?.abortSignal),
- input as GrepInput,
- );
-}
-
-export const GREP_TOOL_DEFINITION: ResolvedToolDefinition = {
+export const grep = defineTool({
description: [
"Fast content search tool that works with any codebase size.",
"",
@@ -87,11 +78,11 @@ export const GREP_TOOL_DEFINITION: ResolvedToolDefinition = {
"- Call this tool in parallel when you have multiple independent searches.",
"- Any line longer than 2000 characters is truncated.",
].join("\n"),
- execute: executeGrep,
+ async execute(input, ctx) {
+ return await executeGrepOnSandbox(await ctx.getSandbox(), input as GrepInput);
+ },
inputSchema: GREP_INPUT_SCHEMA,
- logicalPath: "eve:framework/grep",
- name: "grep",
outputSchema: GREP_OUTPUT_SCHEMA,
- sourceId: "eve:grep-tool",
- sourceKind: "module",
-};
+});
+
+export default grep;
diff --git a/packages/eve/src/tools/load-skill.ts b/packages/eve/src/tools/load-skill.ts
new file mode 100644
index 000000000..939ffe823
--- /dev/null
+++ b/packages/eve/src/tools/load-skill.ts
@@ -0,0 +1,20 @@
+import {
+ executeLoadSkill,
+ SKILL_INPUT_SCHEMA,
+ SKILL_OUTPUT_SCHEMA,
+} from "#execution/tools/load-skill.js";
+import { defineTool } from "#public/definitions/tool.js";
+
+export const loadSkill = defineTool({
+ description: [
+ "Load the full instructions for one available skill by name or id.",
+ "Use this tool when the request clearly matches a listed skill description or when the user explicitly asks for that skill.",
+ "Loading adds the skill instructions to the current turn.",
+ 'Choose the "skill" value from the Available skills block.',
+ ].join(" "),
+ execute: executeLoadSkill,
+ inputSchema: SKILL_INPUT_SCHEMA,
+ outputSchema: SKILL_OUTPUT_SCHEMA,
+});
+
+export default loadSkill;
diff --git a/packages/eve/src/runtime/framework-tools/read-file.ts b/packages/eve/src/tools/read-file.ts
similarity index 76%
rename from packages/eve/src/runtime/framework-tools/read-file.ts
rename to packages/eve/src/tools/read-file.ts
index c6fbd1fa2..5e66380c8 100644
--- a/packages/eve/src/runtime/framework-tools/read-file.ts
+++ b/packages/eve/src/tools/read-file.ts
@@ -1,9 +1,7 @@
import { z } from "#compiled/zod/index.js";
-import { executeReadFileOnSandbox, type ReadFileInput } from "#execution/sandbox/read-file-tool.js";
-import { requireSandboxSession } from "#execution/sandbox/require-sandbox.js";
-import type { ResolvedToolDefinition } from "#runtime/types.js";
-import type { ToolExecuteOptions } from "#shared/tool-definition.js";
+import { type ReadFileInput, executeReadFileOnSandbox } from "#execution/sandbox/read-file-tool.js";
+import { defineTool } from "#public/definitions/tool.js";
/**
* Shared input schema used by the framework `read_file` tool and any author
@@ -46,14 +44,7 @@ export const READ_FILE_OUTPUT_SCHEMA = z.strictObject({
/**
* Framework-owned executor that delegates to the default sandbox.
*/
-async function executeReadFile(input: unknown, options?: ToolExecuteOptions): Promise<unknown> {
- return executeReadFileOnSandbox(
- await requireSandboxSession(options?.abortSignal),
- input as ReadFileInput,
- );
-}
-
-export const READ_FILE_TOOL_DEFINITION: ResolvedToolDefinition = {
+export const readFile = defineTool({
description: [
"Read a file from the local filesystem. If the path does not exist, an error is returned.",
"",
@@ -67,11 +58,11 @@ export const READ_FILE_TOOL_DEFINITION: ResolvedToolDefinition = {
"- Call this tool in parallel when you know there are multiple files you want to read.",
"- Avoid tiny repeated slices (30 line chunks). If you need more context, read a larger window.",
].join("\n"),
- execute: executeReadFile,
+ async execute(input, ctx) {
+ return await executeReadFileOnSandbox(await ctx.getSandbox(), input as ReadFileInput);
+ },
inputSchema: READ_FILE_INPUT_SCHEMA,
- logicalPath: "eve:framework/read-file",
- name: "read_file",
outputSchema: READ_FILE_OUTPUT_SCHEMA,
- sourceId: "eve:read-file-tool",
- sourceKind: "module",
-};
+});
+
+export default readFile;
diff --git a/packages/eve/src/tools/sleep.ts b/packages/eve/src/tools/sleep.ts
new file mode 100644
index 000000000..94b8ac5d8
--- /dev/null
+++ b/packages/eve/src/tools/sleep.ts
@@ -0,0 +1,34 @@
+import { defineTool, type ToolDefinition } from "#public/definitions/tool.js";
+import {
+ executeSleepTool,
+ SLEEP_INPUT_SCHEMA,
+ SLEEP_OUTPUT_SCHEMA,
+ SLEEP_TOOL_DESCRIPTION,
+ type SleepToolInput,
+ type SleepToolOutput,
+} from "#execution/tools/sleep.js";
+
+export type { SleepToolInput, SleepToolOutput };
+
+/**
+ * Defines the opt-in durable `sleep` tool.
+ *
+ * Export it from `agent/tools/sleep.ts`:
+ *
+ * ```ts
+ * import { sleep } from "eve/tools/sleep";
+ *
+ * export default sleep();
+ * ```
+ *
+ * Calls pause the durable turn workflow rather than holding an application
+ * runtime open with an in-process timer.
+ */
+export function sleep(): ToolDefinition<SleepToolInput, SleepToolOutput> {
+ return defineTool({
+ description: SLEEP_TOOL_DESCRIPTION,
+ execute: executeSleepTool,
+ inputSchema: SLEEP_INPUT_SCHEMA,
+ outputSchema: SLEEP_OUTPUT_SCHEMA,
+ });
+}
diff --git a/packages/eve/src/tools/todo.ts b/packages/eve/src/tools/todo.ts
new file mode 100644
index 000000000..6ca970dce
--- /dev/null
+++ b/packages/eve/src/tools/todo.ts
@@ -0,0 +1,36 @@
+import {
+ executeTodoTool,
+ TODO_INPUT_SCHEMA,
+ TODO_OUTPUT_SCHEMA,
+ type TodoToolInput,
+} from "#execution/tools/todo.js";
+import { defineTool } from "#public/definitions/tool.js";
+
+export const todo = defineTool({
+ description: [
+ "Use this tool to create and manage a structured task list for the current session.",
+ "This helps you track progress, organize complex tasks, and demonstrate thoroughness.",
+ "",
+ "When to use:",
+ "- Complex multistep tasks requiring 3 or more distinct steps",
+ "- When the user provides multiple tasks or a numbered list",
+ "- After receiving new instructions, to capture requirements",
+ "- After completing a task, to mark it complete and add follow-ups",
+ "",
+ "When NOT to use:",
+ "- Single, straightforward tasks that need no tracking",
+ "- Purely conversational or informational requests",
+ "",
+ "Usage:",
+ "- Call with `todos` to replace the entire list (full replacement write)",
+ "- Call without `todos` to read the current list",
+ "- Both return the full current list with status counts",
+ "- Mark tasks in_progress when you start, completed when done",
+ "- Only have ONE task in_progress at a time",
+ ].join("\n"),
+ execute: async (input) => executeTodoTool((input ?? {}) as TodoToolInput),
+ inputSchema: TODO_INPUT_SCHEMA,
+ outputSchema: TODO_OUTPUT_SCHEMA,
+});
+
+export default todo;
diff --git a/packages/eve/src/runtime/framework-tools/web-fetch.ts b/packages/eve/src/tools/web-fetch.ts
similarity index 70%
rename from packages/eve/src/runtime/framework-tools/web-fetch.ts
rename to packages/eve/src/tools/web-fetch.ts
index 37fb1fa08..0aa0da771 100644
--- a/packages/eve/src/runtime/framework-tools/web-fetch.ts
+++ b/packages/eve/src/tools/web-fetch.ts
@@ -1,12 +1,7 @@
import { z } from "#compiled/zod/index.js";
-import { executeWebFetchTool, type WebFetchInput } from "#execution/web-fetch/tool.js";
-import type { ResolvedToolDefinition } from "#runtime/types.js";
-import type { ToolExecuteOptions } from "#shared/tool-definition.js";
-
-async function executeWebFetch(input: unknown, options?: ToolExecuteOptions): Promise<unknown> {
- return executeWebFetchTool(input as WebFetchInput, { abortSignal: options?.abortSignal });
-}
+import { type WebFetchInput, executeWebFetchTool } from "#execution/web-fetch/tool.js";
+import { defineTool } from "#public/definitions/tool.js";
export const WEB_FETCH_INPUT_SCHEMA = z.strictObject({
format: z
@@ -26,7 +21,7 @@ export const WEB_FETCH_OUTPUT_SCHEMA = z.strictObject({
url: z.string(),
});
-export const WEB_FETCH_TOOL_DEFINITION: ResolvedToolDefinition = {
+export const webFetch = defineTool({
description: [
"Fetch a webpage and return its content in the requested format. Use this to retrieve and analyze content from URLs.",
"",
@@ -38,11 +33,11 @@ export const WEB_FETCH_TOOL_DEFINITION: ResolvedToolDefinition = {
"- Maximum response size is 5 MB; content is further capped at the shared tool-output budget (50 KB / 2000 lines)",
"- This tool is read-only and does not modify any files",
].join("\n"),
- execute: executeWebFetch,
+ async execute(input, ctx) {
+ return await executeWebFetchTool(input as WebFetchInput, { abortSignal: ctx.abortSignal });
+ },
inputSchema: WEB_FETCH_INPUT_SCHEMA,
- logicalPath: "eve:framework/web-fetch",
- name: "web_fetch",
outputSchema: WEB_FETCH_OUTPUT_SCHEMA,
- sourceId: "eve:web-fetch-tool",
- sourceKind: "module",
-};
+});
+
+export default webFetch;
diff --git a/packages/eve/src/runtime/framework-tools/write-file.ts b/packages/eve/src/tools/write-file.ts
similarity index 73%
rename from packages/eve/src/runtime/framework-tools/write-file.ts
rename to packages/eve/src/tools/write-file.ts
index 313a18888..40b86822e 100644
--- a/packages/eve/src/runtime/framework-tools/write-file.ts
+++ b/packages/eve/src/tools/write-file.ts
@@ -1,12 +1,10 @@
import { z } from "#compiled/zod/index.js";
import {
- executeWriteFileOnSandbox,
type WriteFileInput,
+ executeWriteFileOnSandbox,
} from "#execution/sandbox/write-file-tool.js";
-import { requireSandboxSession } from "#execution/sandbox/require-sandbox.js";
-import type { ResolvedToolDefinition } from "#runtime/types.js";
-import type { ToolExecuteOptions } from "#shared/tool-definition.js";
+import { defineTool } from "#public/definitions/tool.js";
/**
* Shared input schema used by the framework `write_file` tool and any author
@@ -35,14 +33,7 @@ export const WRITE_FILE_OUTPUT_SCHEMA = z.strictObject({
/**
* Framework-owned executor that delegates to the default sandbox.
*/
-async function executeWriteFile(input: unknown, options?: ToolExecuteOptions): Promise<unknown> {
- return executeWriteFileOnSandbox(
- await requireSandboxSession(options?.abortSignal),
- input as WriteFileInput,
- );
-}
-
-export const WRITE_FILE_TOOL_DEFINITION: ResolvedToolDefinition = {
+export const writeFile = defineTool({
description: [
"Writes a file to the local filesystem.",
"",
@@ -53,11 +44,11 @@ export const WRITE_FILE_TOOL_DEFINITION: ResolvedToolDefinition = {
"- NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User.",
"- Only use emojis if the user explicitly requests it. Avoid writing emojis to files unless asked.",
].join("\n"),
- execute: executeWriteFile,
+ async execute(input, ctx) {
+ return await executeWriteFileOnSandbox(await ctx.getSandbox(), input as WriteFileInput);
+ },
inputSchema: WRITE_FILE_INPUT_SCHEMA,
- logicalPath: "eve:framework/write-file",
- name: "write_file",
outputSchema: WRITE_FILE_OUTPUT_SCHEMA,
- sourceId: "eve:write-file-tool",
- sourceKind: "module",
-};
+});
+
+export default writeFile;
diff --git a/packages/eve/test/client.test.ts b/packages/eve/test/client.test.ts
index 116cde7d9..29d21e005 100644
--- a/packages/eve/test/client.test.ts
+++ b/packages/eve/test/client.test.ts
@@ -19,6 +19,7 @@ import {
createTurnStartedEvent,
type UnstampedMessageStreamEvent,
} from "../src/protocol/message.js";
+import { createTestAgentInfoResult } from "../src/internal/testing/agent-info-fixture.js";
// ---------------------------------------------------------------------------
// Helpers
@@ -229,87 +230,12 @@ describe("Client.health", () => {
describe("Client.info", () => {
it("fetches the agent info payload from the info route", async () => {
- const payload = {
- agent: {
- agentRoot: "/tmp/weather-agent/agent",
- appRoot: "/tmp/weather-agent",
- model: {
- id: "gpt-5",
- routing: { kind: "gateway", target: "openai" },
- },
- name: "Weather Agent",
- },
- capabilities: { devRoutes: true },
- channels: {
- authored: [],
- available: [],
- disabledFramework: [],
- framework: [],
- },
- connections: [],
- diagnostics: {
- discoveryErrors: 0,
- discoveryWarnings: 0,
- },
- hooks: [],
- instructions: {
- dynamic: [],
- static: [
- {
- content: "You are a weather assistant.",
- logicalPath: "agent/instructions.md",
- name: "instructions",
- role: "system",
- sourceKind: "markdown",
- },
- ],
- },
- kind: "eve-agent-info",
- mode: "development",
- sandbox: null,
- schedules: [],
- skills: {
- dynamic: [],
- static: [],
- },
- subagents: {
- local: [],
- total: 0,
- },
- tools: {
- authored: [
- {
- description: "Get the weather.",
- hasAuth: false,
- hasExecute: true,
- hasModelOutputProjection: false,
- hasOutputSchema: false,
- inputSchema: { type: "object" },
- logicalPath: "agent/tools/get_weather.ts",
- name: "get_weather",
- origin: "authored",
- outputSchema: null,
- replacesFrameworkTool: false,
- requiresApproval: false,
- sourceKind: "module",
- },
- ],
- available: [],
- disabledFramework: [],
- dynamic: [],
- framework: [],
- reserved: [],
- },
- version: 2,
- workflow: {
- enabled: false,
- toolName: "Workflow",
- },
- workspace: {
- resourceRoot: null,
- rootEntries: [],
- },
- } satisfies AgentInfoResult;
+ const payload = createTestAgentInfoResult({
+ agentRoot: "/tmp/weather-agent/agent",
+ appRoot: "/tmp/weather-agent",
+ modelId: "gpt-5",
+ name: "Weather Agent",
+ }) satisfies AgentInfoResult;
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(Response.json(payload));
const client = new Client({ host: "http://localhost:3000" });
diff --git a/packages/eve/test/define-read-file-tool.test.ts b/packages/eve/test/define-read-file-tool.test.ts
index ab442ced4..daaa1c52d 100644
--- a/packages/eve/test/define-read-file-tool.test.ts
+++ b/packages/eve/test/define-read-file-tool.test.ts
@@ -7,7 +7,7 @@ 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/runtime/framework-tools/file-state.js";
+import { ReadFileStateKey } from "../src/execution/tools/file-state.js";
function createFakeAccess(files: Record<string, string>): SandboxAccess {
return {
diff --git a/packages/eve/test/define-write-file-tool.test.ts b/packages/eve/test/define-write-file-tool.test.ts
index 4f69b7b07..76df73f07 100644
--- a/packages/eve/test/define-write-file-tool.test.ts
+++ b/packages/eve/test/define-write-file-tool.test.ts
@@ -7,10 +7,7 @@ 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/runtime/framework-tools/file-state.js";
+import { createReadFileStamp, ReadFileStateKey } from "../src/execution/tools/file-state.js";
function createFakeAccess(files: Record<string, string>): SandboxAccess {
return {
diff --git a/packages/eve/test/file-tool-compaction.test.ts b/packages/eve/test/file-tool-compaction.test.ts
index 9f50dbbe4..d4f61e00a 100644
--- a/packages/eve/test/file-tool-compaction.test.ts
+++ b/packages/eve/test/file-tool-compaction.test.ts
@@ -8,7 +8,7 @@ import { executeReadFileOnSandbox } from "../src/execution/sandbox/read-file-too
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 { ReadFileStateKey } from "../src/runtime/framework-tools/file-state.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.ts
index 57175cb73..e5f536d44 100644
--- a/packages/eve/test/read-file-tool.test.ts
+++ b/packages/eve/test/read-file-tool.test.ts
@@ -8,7 +8,7 @@ import type { ReadFileResult } from "../src/execution/sandbox/read-file-tool.js"
import { executeReadFileOnSandbox } from "../src/execution/sandbox/read-file-tool.js";
import type { SandboxAccess } from "../src/sandbox/state.js";
import type { SandboxSession } from "../src/shared/sandbox-session.js";
-import { ReadFileStateKey } from "../src/runtime/framework-tools/file-state.js";
+import { ReadFileStateKey } from "../src/execution/tools/file-state.js";
const HOME_PROBE_COMMAND = `printf '%s\\n' "$HOME"`;
diff --git a/packages/eve/test/resolve-agent.test.ts b/packages/eve/test/resolve-agent.test.ts
index e62f93159..0f8e570da 100644
--- a/packages/eve/test/resolve-agent.test.ts
+++ b/packages/eve/test/resolve-agent.test.ts
@@ -1,559 +1,116 @@
import { asSchema } from "ai";
import { describe, expect, it } from "vitest";
import { z } from "#compiled/zod/index.js";
-import {
- type CompiledChannelDefinition,
- createCompiledAgentManifest,
- ROOT_COMPILED_AGENT_NODE_ID,
-} from "../src/compiler/manifest.js";
-import type { CompiledModuleMap } from "../src/compiler/module-map.js";
-import { TEST_DEFAULT_MODEL_ID } from "../src/internal/testing/app-harness.js";
+
+import { compileFromMemory } from "../src/compiler/compile-from-memory.js";
+import { defineTool } from "../src/public/definitions/tool.js";
import { ResolveAgentError, resolveAgent } from "../src/runtime/resolve-agent.js";
import { serializeInputSchema } from "../src/shared/tool-schema.js";
describe("resolveAgent", () => {
- it("hydrates compiled authored metadata and attaches tool execute functions", async () => {
- const slackChannelDefinition: CompiledChannelDefinition = {
- kind: "channel",
- name: "slack",
- method: "POST",
- urlPath: "/slack",
- logicalPath: "channels/slack.mjs",
- sourceId: "channels/slack.mjs",
- sourceKind: "module",
- };
- const manifest = createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- channels: [slackChannelDefinition],
- config: {
- model: {
- id: "anthropic/claude-sonnet-4.5",
- routing: { kind: "gateway", target: "anthropic" },
- },
- name: "weather-agent",
- source: {
- exportName: "config",
- sourceKind: "module",
- logicalPath: "agent.mjs",
- sourceId: "agent.mjs",
- },
- },
- instructions: [
- {
- content: "You are a weather-focused assistant.",
- name: "instructions",
- logicalPath: "instructions.md",
- role: "system",
- sourceId: "instructions.md",
- sourceKind: "markdown",
- },
- ],
- sandbox: {
- logicalPath: "sandbox/sandbox.mjs",
- sourceHash: "sandbox-source-hash",
- sourceId: "sandbox/sandbox.mjs",
- sourceKind: "module",
- },
- skills: [
- {
- description: "Use the weather tool before answering forecast questions.",
- logicalPath: "skills/get-weather.md",
- markdown: "Call the weather tool before answering forecast questions.",
- name: "get-weather",
- sourceId: "skills/get-weather.md",
- sourceKind: "markdown",
- },
- {
- description: "Route weather questions.",
- logicalPath: "skills/route-weather.mjs",
- markdown: "Route weather questions to the weather tool.",
- name: "route-weather",
- sourceId: "skills/route-weather.mjs",
- sourceKind: "module",
- },
- {
- description: "Escalate complex weather research tasks.",
- logicalPath: "skills/research/SKILL.md",
- markdown: "Research complex weather questions before returning findings.",
- name: "research",
- referencesPath: "/app/agent/skills/research/references",
- rootPath: "/app/agent/skills/research",
- scriptsPath: "/app/agent/skills/research/scripts",
- skillId: "research",
- skillFilePath: "/app/agent/skills/research/SKILL.md",
- sourceId: "skills/research/SKILL.md",
- sourceKind: "skill-package",
- },
- ],
+ it("hydrates the effective compiled graph and reattaches tool execution", async () => {
+ const execute = (input: { city: string }) => input;
+ const { manifest, moduleMap } = await compileFromMemory({
+ model: "openai/gpt-5.4",
+ name: "weather-agent",
+ skills: [{ description: "Use weather data.", name: "weather" }],
tools: [
{
description: "Get the current weather for a city.",
+ execute,
inputSchema: {
- properties: {
- city: {
- type: "string",
- },
- },
+ properties: { city: { type: "string" } },
required: ["city"],
type: "object",
},
- logicalPath: "tools/get-weather.mjs",
name: "get_weather",
- sourceId: "tools/get-weather.mjs",
- sourceKind: "module",
},
],
});
- const moduleMap: CompiledModuleMap = {
- nodes: {
- [ROOT_COMPILED_AGENT_NODE_ID]: {
- modules: {
- "channels/slack.mjs": {
- default() {
- // Minimal CompiledChannel shape (what `defineChannel`
- // returns). Avoids importing `defineChannel` from a
- // test fixture module.
- return {
- __kind: "eve:channel",
- routes: [
- {
- method: "POST",
- path: "/slack",
- async handler() {
- return new Response("ok");
- },
- },
- ],
- adapter: { kind: "channel" },
- };
- },
- },
- "sandbox/sandbox.mjs": {
- default() {
- return {
- description: "Use this sandbox for repository shell work.",
- onSession() {
- return undefined;
- },
- };
- },
- },
- "tools/get-weather.mjs": {
- default() {
- return {
- description: "Get the current weather for a city.",
- execute(input: { city: string }) {
- return input;
- },
- inputSchema: {
- properties: {
- city: {
- type: "string",
- },
- },
- required: ["city"],
- type: "object",
- },
- name: "get_weather",
- };
- },
- },
- },
- },
- },
- };
- const resolved = await resolveAgent({
- manifest,
- moduleMap,
- });
- const [resolvedChannel] = resolved.channels;
+ const resolved = await resolveAgent({ manifest, moduleMap });
+ const weather = resolved.tools.find((tool) => tool.name === "get_weather");
- expect(resolved.config?.name).toBe("weather-agent");
- expect(resolved.config).toEqual({
- compaction: {},
- model: {
- id: "anthropic/claude-sonnet-4.5",
- },
+ expect(resolved.config).toMatchObject({
+ model: { id: "openai/gpt-5.4" },
name: "weather-agent",
- source: {
- exportName: "config",
- logicalPath: "agent.mjs",
- sourceId: "agent.mjs",
- sourceKind: "module",
- },
- });
- if (resolvedChannel === undefined) {
- throw new Error("Expected one resolved channel.");
- }
- expect(resolvedChannel.name).toBe("slack");
- expect(resolvedChannel.method).toBe("POST");
- expect(resolvedChannel.urlPath).toBe("/slack");
- expect(typeof resolvedChannel.fetch).toBe("function");
- expect(resolved.channels).toHaveLength(1);
- expect(resolved.metadata).toEqual({
- agentRoot: "/app/agent",
- appRoot: "/app",
- diagnosticsSummary: {
- errors: 0,
- warnings: 0,
- },
- });
- expect(resolved.instructions).toEqual([
- {
- content: "You are a weather-focused assistant.",
- logicalPath: "instructions.md",
- name: "instructions",
- role: "system",
- sourceId: "instructions.md",
- sourceKind: "markdown",
- },
- ]);
- expect(resolved.sandbox).toEqual({
- backend: expect.objectContaining({
- create: expect.any(Function),
- name: expect.any(String),
- }),
- bootstrap: undefined,
- description: undefined,
- exportName: undefined,
- logicalPath: "sandbox/sandbox.mjs",
- onSession: expect.any(Function),
- revalidationKey: undefined,
- sourceHash: "sandbox-source-hash",
- sourceId: "sandbox/sandbox.mjs",
- sourceKind: "module",
- });
- expect(resolved.skills).toEqual([
- {
- description: "Use the weather tool before answering forecast questions.",
- logicalPath: "skills/get-weather.md",
- markdown: "Call the weather tool before answering forecast questions.",
- name: "get-weather",
- sourceId: "skills/get-weather.md",
- sourceKind: "markdown",
- },
- {
- description: "Route weather questions.",
- logicalPath: "skills/route-weather.mjs",
- markdown: "Route weather questions to the weather tool.",
- name: "route-weather",
- sourceId: "skills/route-weather.mjs",
- sourceKind: "module",
- },
- {
- description: "Escalate complex weather research tasks.",
- logicalPath: "skills/research/SKILL.md",
- markdown: "Research complex weather questions before returning findings.",
- name: "research",
- referencesPath: "/app/agent/skills/research/references",
- rootPath: "/app/agent/skills/research",
- scriptsPath: "/app/agent/skills/research/scripts",
- skillId: "research",
- skillFilePath: "/app/agent/skills/research/SKILL.md",
- sourceId: "skills/research/SKILL.md",
- sourceKind: "skill-package",
- },
- ]);
- expect(resolved.workspaceSpec).toEqual({
- rootEntries: [],
});
- expect(resolved.tools).toHaveLength(1);
- expect(resolved.tools[0]).toMatchObject({
+ expect(resolved.channels).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ method: "GET", urlPath: "/eve/v1/health" }),
+ expect.objectContaining({ method: "GET", urlPath: "/eve/v1/info" }),
+ ]),
+ );
+ expect(resolved.sandbox).toMatchObject({
+ backend: expect.objectContaining({ create: expect.any(Function), name: expect.any(String) }),
+ logicalPath: "sandbox.ts",
+ });
+ expect(resolved.skills).toContainEqual(
+ expect.objectContaining({ description: "Use weather data.", name: "weather" }),
+ );
+ expect(weather).toMatchObject({
description: "Get the current weather for a city.",
- logicalPath: "tools/get-weather.mjs",
- name: "get_weather",
- sourceId: "tools/get-weather.mjs",
- sourceKind: "module",
+ owner: { kind: "application" },
});
- expect(serializeInputSchema(resolved.tools[0]!.inputSchema!)).toMatchObject({
- properties: {
- city: {
- type: "string",
- },
- },
+ expect(serializeInputSchema(weather!.inputSchema!)).toMatchObject({
+ properties: { city: { type: "string" } },
required: ["city"],
type: "object",
});
expect(
- resolved.tools[0]?.execute?.({ city: "Brooklyn" }, { messages: [], toolCallId: "call_1" }),
- ).toEqual({
- city: "Brooklyn",
- });
+ weather?.execute?.({ city: "Brooklyn" }, { messages: [], toolCallId: "call_1" }),
+ ).toEqual({ city: "Brooklyn" });
});
- it("reattaches live standard-schema validators from authored tool exports", async () => {
+ it("retains live standard-schema validators from programmatic sources", async () => {
const schema = z.object({
maxRows: z.number().int().positive().default(200),
sql: z.string().default("SELECT 1"),
});
- const manifest = createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- model: {
- id: TEST_DEFAULT_MODEL_ID,
- routing: { kind: "gateway", target: "openai" },
- },
- name: "weather-agent",
- },
- tools: [
+ const { manifest, moduleMap } = await compileFromMemory({
+ model: "openai/gpt-5.4",
+ modules: [
{
- description: "Execute a query.",
- inputSchema: {
- additionalProperties: false,
- properties: {
- maxRows: {
- type: "number",
- },
- sql: {
- type: "string",
- },
- },
- type: "object",
- },
- logicalPath: "tools/query.mjs",
- name: "query",
- sourceId: "tools/query.mjs",
- sourceKind: "module",
+ loadNamespace: async () => ({
+ default: defineTool({
+ description: "Execute a query.",
+ execute: (input) => input,
+ inputSchema: schema,
+ }),
+ }),
+ logicalPath: "tools/query.ts",
},
],
});
- const moduleMap: CompiledModuleMap = {
- nodes: {
- [ROOT_COMPILED_AGENT_NODE_ID]: {
- modules: {
- "tools/query.mjs": {
- default() {
- return {
- description: "Execute a query.",
- execute(input: unknown) {
- return input;
- },
- inputSchema: schema,
- name: "query",
- };
- },
- },
- },
- },
- },
- };
-
- const resolved = await resolveAgent({
- manifest,
- moduleMap,
- });
- const inputSchema = resolved.tools[0]?.inputSchema;
- expect(inputSchema).toBeDefined();
-
- const sdkSchema = asSchema(inputSchema!);
- const result = await sdkSchema.validate!({});
-
- expect(result).toEqual({
- success: true,
- value: {
- maxRows: 200,
- sql: "SELECT 1",
- },
- });
- });
-
- it("falls back to the bootstrap model when no compiled config is present", async () => {
- const resolved = await resolveAgent({
- manifest: createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- model: {
- id: TEST_DEFAULT_MODEL_ID,
- routing: { kind: "gateway", target: "openai" },
- },
- name: "weather-agent",
- },
- }),
- moduleMap: {
- nodes: {
- [ROOT_COMPILED_AGENT_NODE_ID]: {
- modules: {},
- },
- },
- },
- });
- expect(resolved.config?.name).toBe("weather-agent");
- expect(resolved.config).toEqual({
- compaction: {},
- model: {
- id: TEST_DEFAULT_MODEL_ID,
- },
- name: "weather-agent",
- });
- expect(resolved.instructions).toEqual([]);
- expect(resolved.sandbox).toBeNull();
- expect(resolved.skills).toEqual([]);
- expect(resolved.tools).toEqual([]);
- expect(resolved.workspaceSpec).toEqual({
- rootEntries: [],
- });
- });
-
- it("threads the compiled sandbox workspace folder into the resolved agent", async () => {
- const resolved = await resolveAgent({
- manifest: createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- model: { id: TEST_DEFAULT_MODEL_ID, routing: { kind: "gateway", target: "openai" } },
- name: "weather-agent",
- },
- sandboxWorkspaces: [
- {
- logicalPath: "sandbox/workspace",
- rootEntries: ["seed.txt", "prompts/"],
- sourceId: "sandbox/workspace",
- sourcePath: "/app/agent/sandbox/workspace",
- },
- ],
- }),
- moduleMap: {
- nodes: {
- [ROOT_COMPILED_AGENT_NODE_ID]: {
- modules: {},
- },
- },
- },
- });
-
- // The sandbox workspace's root entries flow into the prompt-facing
- // workspace spec and the byte-free resource-root descriptor the
- // runtime graph builder hands to the registry.
- expect(resolved.workspaceSpec.rootEntries).toEqual(["prompts/", "seed.txt"]);
- expect(resolved.workspaceResourceRoot.rootEntries).toEqual(["prompts/", "seed.txt"]);
- });
-
- it("preserves source-backed model references already compiled into the manifest", async () => {
- const resolved = await resolveAgent({
- manifest: createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- model: {
- id: "test-provider/weather-pro",
- source: {
- sourceKind: "module",
- logicalPath: "agent.mjs",
- sourceId: "agent.mjs",
- },
- routing: { kind: "external", provider: "test-provider" },
- },
- name: "weather-agent",
- },
- }),
- moduleMap: {
- nodes: {
- [ROOT_COMPILED_AGENT_NODE_ID]: {
- modules: {},
- },
- },
- },
- });
+ const resolved = await resolveAgent({ manifest, moduleMap });
+ const query = resolved.tools.find((tool) => tool.name === "query");
+ const result = await asSchema(query!.inputSchema!).validate!({});
- expect(resolved.config?.model).toEqual({
- id: "test-provider/weather-pro",
- source: {
- sourceKind: "module",
- logicalPath: "agent.mjs",
- sourceId: "agent.mjs",
- },
- });
+ expect(result).toEqual({ success: true, value: { maxRows: 200, sql: "SELECT 1" } });
});
- it("preserves model options on resolved runtime model references", async () => {
- const resolved = await resolveAgent({
- manifest: createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- model: {
- id: "anthropic/claude-opus-4.5-thinking",
- providerOptions: {
- anthropic: {
- thinking: {
- budget_tokens: 1024,
- },
- },
- },
- routing: { kind: "gateway", target: "anthropic" },
- },
- name: "weather-agent",
- },
- }),
- moduleMap: {
- nodes: {
- [ROOT_COMPILED_AGENT_NODE_ID]: {
- modules: {},
- },
- },
- },
+ it("rejects an invalid live export for a compiled executable tool", async () => {
+ const { manifest, moduleMap } = await compileFromMemory({
+ model: "openai/gpt-5.4",
+ tools: [{ name: "weather" }],
});
-
- expect(resolved.config?.model).toEqual({
- id: "anthropic/claude-opus-4.5-thinking",
- providerOptions: {
- anthropic: {
- thinking: {
- budget_tokens: 1024,
+ const weather = manifest.tools.find((tool) => tool.name === "weather")!;
+ const root = moduleMap.nodes.__root__!;
+ const invalidMap = {
+ nodes: {
+ ...moduleMap.nodes,
+ __root__: {
+ modules: {
+ ...root.modules,
+ [weather.sourceId]: { default: { description: "Missing execute." } },
},
},
},
- });
- });
-
- it("rejects invalid authored tool exports while resolving the compiled agent", async () => {
- const manifest = createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- model: {
- id: TEST_DEFAULT_MODEL_ID,
- routing: { kind: "gateway", target: "openai" },
- },
- name: "weather-agent",
- },
- tools: [
- {
- description: "Missing execute should fail runtime resolution.",
- inputSchema: null,
- logicalPath: "tools/get-weather.mjs",
- name: "get_weather",
- sourceId: "tools/get-weather.mjs",
- sourceKind: "module",
- },
- ],
- });
+ };
- await expect(
- resolveAgent({
- manifest,
- moduleMap: {
- nodes: {
- [ROOT_COMPILED_AGENT_NODE_ID]: {
- modules: {
- "tools/get-weather.mjs": {
- default: async () => {
- return {
- description: "Missing execute should fail runtime resolution.",
- name: "get_weather",
- };
- },
- },
- },
- },
- },
- },
- }),
- ).rejects.toBeInstanceOf(ResolveAgentError);
+ await expect(resolveAgent({ manifest, moduleMap: invalidMap })).rejects.toBeInstanceOf(
+ ResolveAgentError,
+ );
});
});
diff --git a/packages/eve/test/runtime-agent-framework-tools.test.ts b/packages/eve/test/runtime-agent-framework-tools.test.ts
deleted file mode 100644
index c8007fa46..000000000
--- a/packages/eve/test/runtime-agent-framework-tools.test.ts
+++ /dev/null
@@ -1,119 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import {
- createCompiledAgentManifest,
- createCompiledAgentNodeManifest,
- ROOT_COMPILED_AGENT_NODE_ID,
-} from "../src/compiler/manifest.js";
-import { createNodeHarnessTools } from "../src/execution/node-step.js";
-import { TEST_DEFAULT_MODEL_ID } from "../src/internal/testing/app-harness.js";
-import { resolveRuntimeAgentGraph } from "../src/runtime/resolve-agent-graph.js";
-
-describe("runtime agent framework tools", () => {
- it("lets an authored agent tool replace the built-in agent action", async () => {
- const manifest = createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- model: {
- id: TEST_DEFAULT_MODEL_ID,
- routing: { kind: "gateway", target: "openai" },
- },
- name: "weather-agent",
- },
- tools: [
- {
- description: "Delegate through an authored implementation.",
- inputSchema: null,
- logicalPath: "tools/agent.mjs",
- name: "agent",
- sourceId: "tools/agent.mjs",
- sourceKind: "module",
- },
- ],
- });
- const graph = await resolveRuntimeAgentGraph({
- manifest,
- moduleMap: {
- nodes: {
- [ROOT_COMPILED_AGENT_NODE_ID]: {
- modules: {
- "tools/agent.mjs": {
- default: {
- description: "Delegate through an authored implementation.",
- execute: () => "authored-agent",
- },
- },
- },
- },
- },
- },
- });
-
- expect(graph.root.turnAgent.tools.filter((tool) => tool.name === "agent")).toMatchObject([
- { kind: "authored-tool" },
- ]);
- expect(
- createNodeHarnessTools({ node: graph.root }).get("agent")?.runtimeAction,
- ).toBeUndefined();
- });
-
- it("lets a declared subagent named agent replace the built-in agent action", async () => {
- const child = createCompiledAgentNodeManifest({
- agentRoot: "/app/agent/subagents/agent",
- appRoot: "/app",
- config: {
- model: {
- id: TEST_DEFAULT_MODEL_ID,
- routing: { kind: "gateway", target: "openai" },
- },
- name: "agent",
- },
- });
- const manifest = createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- model: {
- id: TEST_DEFAULT_MODEL_ID,
- routing: { kind: "gateway", target: "openai" },
- },
- name: "root-agent",
- },
- subagentEdges: [
- {
- childNodeId: "subagents/agent",
- parentNodeId: ROOT_COMPILED_AGENT_NODE_ID,
- },
- ],
- subagents: [
- {
- agent: child,
- description: "A declared specialist named agent.",
- entryPath: "/app/agent/subagents/agent",
- logicalPath: "subagents/agent",
- name: "agent",
- nodeId: "subagents/agent",
- rootPath: "/app/agent/subagents/agent",
- sourceId: "subagents/agent",
- sourceKind: "module",
- },
- ],
- });
- const graph = await resolveRuntimeAgentGraph({
- manifest,
- moduleMap: {
- nodes: {
- [ROOT_COMPILED_AGENT_NODE_ID]: { modules: {} },
- "subagents/agent": { modules: {} },
- },
- },
- });
-
- expect(graph.root.turnAgent.tools.filter((tool) => tool.name === "agent")).toMatchObject([
- { kind: "subagent" },
- ]);
- const runtimeAction = createNodeHarnessTools({ node: graph.root }).get("agent")?.runtimeAction;
- expect(runtimeAction).toMatchObject({ kind: "subagent-call", subagentName: "agent" });
- });
-});
diff --git a/packages/eve/test/runtime-agent-graph.test.ts b/packages/eve/test/runtime-agent-graph.test.ts
index 5c97ff2ce..0d72522ac 100644
--- a/packages/eve/test/runtime-agent-graph.test.ts
+++ b/packages/eve/test/runtime-agent-graph.test.ts
@@ -1,30 +1,8 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import {
- createCompiledAgentResources,
- createCompiledAgentManifest,
- createCompiledAgentNodeManifest,
- ROOT_COMPILED_AGENT_NODE_ID,
-} from "../src/compiler/manifest.js";
-import type { CompiledModuleMap } from "../src/compiler/module-map.js";
-import { defineAgent } from "../src/public/definitions/agent.js";
-import { defineDynamic } from "../src/public/definitions/tool.js";
-import { createNodeHarnessTools } from "../src/execution/node-step.js";
-import { TEST_DEFAULT_MODEL_ID } from "../src/internal/testing/app-harness.js";
-import { ROOT_RUNTIME_AGENT_NODE_ID } from "../src/runtime/graph.js";
-import { resolveRuntimeAgentGraph } from "../src/runtime/resolve-agent-graph.js";
-const SUBAGENT_TOOL_INPUT_SCHEMA = {
- type: "object",
- properties: {
- message: {
- type: "string",
- description:
- "The message to send to the subagent. Provide all context the subagent needs to complete the task; the subagent does not see the parent's history.",
- },
- },
- required: ["message"],
- additionalProperties: false,
-} as const;
+import { compileFromMemory } from "../src/compiler/compile-from-memory.js";
+import { disableTool } from "../src/public/definitions/tool.js";
+import { resolveRuntimeAgentGraph } from "../src/runtime/resolve-agent-graph.js";
describe("resolveRuntimeAgentGraph", () => {
beforeEach(() => {
@@ -35,1007 +13,74 @@ describe("resolveRuntimeAgentGraph", () => {
vi.unstubAllEnvs();
});
- it("defaults agents to the Vercel sandbox backend on hosted Vercel", async () => {
- const manifest = createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- model: {
- id: TEST_DEFAULT_MODEL_ID,
- routing: { kind: "gateway", target: "openai" },
- },
- name: "workspace-agent",
- },
- skills: [
- {
- description: "Use the research checklist.",
- logicalPath: "skills/research.md",
- markdown: "Use the research checklist.",
- name: "research",
- sourceId: "skills/research.md",
- sourceKind: "markdown",
- },
- ],
- subagentEdges: [
- {
- childNodeId: "subagents/researcher",
- parentNodeId: ROOT_COMPILED_AGENT_NODE_ID,
- },
- ],
- subagents: [
- {
- agent: createCompiledAgentNodeManifest({
- agentRoot: "/app/agent/subagents/researcher",
- appRoot: "/app",
- config: {
- description: "Investigate one task in depth.",
- model: {
- id: TEST_DEFAULT_MODEL_ID,
- routing: { kind: "gateway", target: "openai" },
- },
- name: "researcher",
- },
- skills: [
- {
- description: "Use the reviewer checklist.",
- logicalPath: "skills/reviewer.md",
- markdown: "Use the reviewer checklist.",
- name: "reviewer",
- sourceId: "skills/reviewer.md",
- sourceKind: "markdown",
- },
- ],
- }),
- description: "Investigate one task in depth.",
- entryPath: "/app/agent/subagents/researcher",
- logicalPath: "subagents/researcher",
- name: "researcher",
- nodeId: "subagents/researcher",
- rootPath: "/app/agent/subagents/researcher",
- sourceId: "subagents/researcher",
- sourceKind: "module",
- },
- ],
- });
- const graph = await resolveRuntimeAgentGraph({
- manifest,
- moduleMap: {
- nodes: {
- [ROOT_COMPILED_AGENT_NODE_ID]: {
- modules: {},
- },
- "subagents/researcher": {
- modules: {},
- },
- },
- },
- });
-
- expect(graph.root.sandboxRegistry.sandbox?.definition.backend.name).toBe("vercel");
- expect(
- graph.nodesByNodeId.get("subagents/researcher")?.sandboxRegistry.sandbox?.definition.backend
- .name,
- ).toBe("vercel");
- });
-
- it("keeps dynamic subagents out of the static toolset and resolves their handlers", async () => {
- const dynamic = defineDynamic({
- events: {
- "session.started": () =>
- defineAgent({
- description: "Research the request.",
- model: TEST_DEFAULT_MODEL_ID,
- }),
- },
- });
- const manifest = createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- model: {
- id: TEST_DEFAULT_MODEL_ID,
- routing: { kind: "gateway", target: "openai" },
- },
- name: "root",
- },
- subagentEdges: [
- {
- childNodeId: "subagents/researcher",
- parentNodeId: ROOT_COMPILED_AGENT_NODE_ID,
- },
- ],
- subagents: [
- {
- agent: createCompiledAgentResources({
- agentRoot: "/app/agent/subagents/researcher",
- appRoot: "/app",
- }),
- configResolver: {
- eventNames: ["session.started"],
- logicalPath: "agent.ts",
- sourceId: "agent.ts",
- sourceKind: "module",
- },
- entryPath: "/app/agent/subagents/researcher/agent.ts",
- logicalPath: "subagents/researcher",
- name: "researcher",
- nodeId: "subagents/researcher",
- rootPath: "/app/agent/subagents/researcher",
- sourceId: "subagents/researcher",
- sourceKind: "module",
- },
- ],
- });
-
- const graph = await resolveRuntimeAgentGraph({
- manifest,
- moduleMap: {
- nodes: {
- [ROOT_COMPILED_AGENT_NODE_ID]: { modules: {} },
- "subagents/researcher": {
- modules: {
- "agent.ts": { default: dynamic },
- },
- },
- },
- },
- });
-
- expect(graph.root.turnAgent.tools.some((tool) => tool.name === "researcher")).toBe(false);
- expect(graph.root.subagentRegistry.dynamicNodeIds).toContain("subagents/researcher");
- expect(graph.root.subagentRegistry.dynamicResolvers).toMatchObject([
- {
- eventNames: ["session.started"],
- name: "researcher",
- nodeId: "subagents/researcher",
- },
- ]);
- expect(graph.nodesByNodeId.has("subagents/researcher")).toBe(true);
- });
-
- it("resolves recursive local subagents into a cached runtime graph bundle", async () => {
- const appRoot = "/app";
- const agentRoot = "/app/agent";
- const researcherRoot = "/app/agent/subagents/researcher";
- const reviewerRoot = "/app/agent/subagents/researcher/subagents/reviewer";
- const reviewerDefinition = defineAgent({
- description: "Review one draft.",
- model: TEST_DEFAULT_MODEL_ID,
- });
- const reviewerManifest = createCompiledAgentNodeManifest({
- agentRoot: reviewerRoot,
- appRoot,
- config: {
- description: reviewerDefinition.description,
- model: {
- id: TEST_DEFAULT_MODEL_ID,
- routing: { kind: "gateway", target: "openai" },
- },
- name: "reviewer",
- },
- instructions: [
- {
- content: "Review drafts carefully.",
- name: "reviewer-instructions",
- logicalPath: "instructions.md",
- role: "system",
- sourceId: "instructions.md",
- sourceKind: "markdown",
- },
- ],
- });
- const researcherDefinition = defineAgent({
- description: "Investigate one task in depth.",
- model: TEST_DEFAULT_MODEL_ID,
- });
- const researcherManifest = createCompiledAgentNodeManifest({
- agentRoot: researcherRoot,
- appRoot,
- config: {
- description: researcherDefinition.description,
- model: {
- id: TEST_DEFAULT_MODEL_ID,
- routing: { kind: "gateway", target: "openai" },
- },
- name: "researcher",
- },
- instructions: [
- {
- content: "Investigate one task in depth.",
- name: "researcher-instructions",
- logicalPath: "instructions.md",
- role: "system",
- sourceId: "instructions.md",
- sourceKind: "markdown",
- },
- ],
- tools: [
- {
- description: "Search the web.",
- inputSchema: null,
- logicalPath: "tools/search.mjs",
- name: "search",
- sourceId: "tools/search.mjs",
- sourceKind: "module",
- },
- ],
- });
- const manifest = createCompiledAgentManifest({
- agentRoot,
- appRoot,
- config: {
- model: {
- id: TEST_DEFAULT_MODEL_ID,
- routing: { kind: "gateway", target: "openai" },
- },
- name: "weather-agent",
- },
- instructions: [
- {
- content: "Answer weather questions.",
- name: "instructions",
- logicalPath: "instructions.md",
- role: "system",
- sourceId: "instructions.md",
- sourceKind: "markdown",
- },
- ],
- subagentEdges: [
- {
- childNodeId: "subagents/researcher",
- parentNodeId: ROOT_COMPILED_AGENT_NODE_ID,
- },
- {
- childNodeId: "subagents/researcher::subagents/reviewer",
- parentNodeId: "subagents/researcher",
- },
- ],
- subagents: [
- {
- agent: researcherManifest,
- description: researcherDefinition.description!,
- entryPath: researcherRoot,
- logicalPath: "subagents/researcher",
- name: "researcher",
- nodeId: "subagents/researcher",
- rootPath: researcherRoot,
- sourceId: "subagents/researcher",
- sourceKind: "module",
- },
- {
- agent: reviewerManifest,
- description: reviewerDefinition.description!,
- entryPath: reviewerRoot,
- logicalPath: "subagents/reviewer",
- name: "reviewer",
- nodeId: "subagents/researcher::subagents/reviewer",
- rootPath: reviewerRoot,
- sourceId: "subagents/reviewer",
- sourceKind: "module",
- },
- ],
- tools: [
- {
- description: "Get the weather.",
- inputSchema: null,
- logicalPath: "tools/get-weather.mjs",
- name: "get_weather",
- sourceId: "tools/get-weather.mjs",
- sourceKind: "module",
- },
- ],
- });
- const moduleMap: CompiledModuleMap = {
- nodes: {
- [ROOT_COMPILED_AGENT_NODE_ID]: {
- modules: {
- "tools/get-weather.mjs": {
- default: {
- description: "Get the weather.",
- execute(input: unknown) {
- return input;
- },
- name: "get_weather",
- },
- },
- },
- },
- "subagents/researcher": {
- modules: {
- "tools/search.mjs": {
- default: {
- description: "Search the web.",
- execute(input: unknown) {
- return input;
- },
- name: "search",
- },
- },
- },
- },
- "subagents/researcher::subagents/reviewer": {
- modules: {},
- },
- },
- };
-
- const graph = await resolveRuntimeAgentGraph({
- manifest,
- moduleMap,
+ it("hydrates the compiler-selected framework graph without runtime catalogs", async () => {
+ const { manifest, moduleMap } = await compileFromMemory({
+ model: "openai/gpt-5.4",
+ name: "workspace-agent",
});
- expect([...graph.nodesByNodeId.keys()].sort()).toEqual([
- ROOT_RUNTIME_AGENT_NODE_ID,
- "subagents/researcher",
- "subagents/researcher::subagents/reviewer",
- ]);
- expect(graph.root.turnAgent.tools).toMatchObject([
- {
- 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.",
- kind: "authored-tool",
- name: "ask_question",
- },
- {
- description: "Execute a shell command in the shared workspace environment.",
- kind: "authored-tool",
- name: "bash",
- },
- {
- kind: "authored-tool",
- name: "read_file",
- },
- {
- kind: "authored-tool",
- name: "write_file",
- },
- {
- kind: "authored-tool",
- name: "todo",
- },
- {
- description: [
- "Fetch a webpage and return its content in the requested format. Use this to retrieve and analyze content from URLs.",
- "",
- "Usage notes:",
- "- The URL must be a fully-formed valid URL starting with https://",
- "- HTML responses are automatically converted to markdown or plain text based on the requested format",
- '- Format options: "markdown" (default), "text", or "html"',
- "- Default timeout is 30 seconds (max 120 seconds)",
- "- Maximum response size is 5 MB; content is further capped at the shared tool-output budget (50 KB / 2000 lines)",
- "- This tool is read-only and does not modify any files",
- ].join("\n"),
- kind: "authored-tool",
- name: "web_fetch",
- },
- {
- description:
- "Search the web for real-time information. Use this to find up-to-date information about current events, recent developments, or topics that may have changed since the knowledge cutoff.",
- kind: "authored-tool",
- name: "web_search",
- },
- {
- kind: "authored-tool",
- name: "load_skill",
- },
- {
- description: "Get the weather.",
- inputSchema: null,
- kind: "authored-tool",
- logicalPath: "tools/get-weather.mjs",
- name: "get_weather",
- sourceId: "tools/get-weather.mjs",
- },
- {
- description: "Investigate one task in depth.",
- inputSchema: SUBAGENT_TOOL_INPUT_SCHEMA,
- kind: "subagent",
- logicalPath: "subagents/researcher",
- name: "researcher",
- nodeId: "subagents/researcher",
- sourceId: "subagents/researcher",
- },
- ]);
-
- const researcherNode = graph.nodesByNodeId.get("subagents/researcher");
- const reviewerNode = graph.nodesByNodeId.get("subagents/researcher::subagents/reviewer");
-
- expect(researcherNode?.agent.config?.name).toBe("researcher");
- expect(researcherNode?.agent.instructions).toEqual([
- {
- content: "Investigate one task in depth.",
- name: "researcher-instructions",
- logicalPath: "instructions.md",
- role: "system",
- sourceId: "instructions.md",
- sourceKind: "markdown",
- },
- ]);
- expect(researcherNode?.turnAgent.tools).toMatchObject([
- {
- 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.",
- kind: "authored-tool",
- name: "ask_question",
- },
- {
- description: "Execute a shell command in the shared workspace environment.",
- kind: "authored-tool",
- name: "bash",
- },
- {
- kind: "authored-tool",
- name: "read_file",
- },
- {
- kind: "authored-tool",
- name: "write_file",
- },
- {
- kind: "authored-tool",
- name: "todo",
- },
- {
- description: [
- "Fetch a webpage and return its content in the requested format. Use this to retrieve and analyze content from URLs.",
- "",
- "Usage notes:",
- "- The URL must be a fully-formed valid URL starting with https://",
- "- HTML responses are automatically converted to markdown or plain text based on the requested format",
- '- Format options: "markdown" (default), "text", or "html"',
- "- Default timeout is 30 seconds (max 120 seconds)",
- "- Maximum response size is 5 MB; content is further capped at the shared tool-output budget (50 KB / 2000 lines)",
- "- This tool is read-only and does not modify any files",
- ].join("\n"),
- kind: "authored-tool",
- name: "web_fetch",
- },
- {
- description:
- "Search the web for real-time information. Use this to find up-to-date information about current events, recent developments, or topics that may have changed since the knowledge cutoff.",
- kind: "authored-tool",
- name: "web_search",
- },
- {
- kind: "authored-tool",
- name: "load_skill",
- },
- {
- description: "Search the web.",
- inputSchema: null,
- kind: "authored-tool",
- logicalPath: "tools/search.mjs",
- name: "search",
- sourceId: "tools/search.mjs",
- },
- {
- description: "Review one draft.",
- inputSchema: SUBAGENT_TOOL_INPUT_SCHEMA,
- kind: "subagent",
- logicalPath: "subagents/reviewer",
- name: "reviewer",
- nodeId: "subagents/researcher::subagents/reviewer",
- sourceId: "subagents/reviewer",
- },
- ]);
- expect(reviewerNode?.agent.instructions).toEqual([
- {
- content: "Review drafts carefully.",
- name: "reviewer-instructions",
- logicalPath: "instructions.md",
- role: "system",
- sourceId: "instructions.md",
- sourceKind: "markdown",
- },
- ]);
- });
-
- it("resolves remote subagents from the owning node manifest only", async () => {
- const appRoot = "/app";
- const agentRoot = "/app/agent";
- const researcherRoot = "/app/agent/subagents/researcher";
- const researcherManifest = createCompiledAgentNodeManifest({
- agentRoot: researcherRoot,
- appRoot,
- config: {
- description: "Investigate one task in depth.",
- model: {
- id: TEST_DEFAULT_MODEL_ID,
- routing: { kind: "gateway", target: "openai" },
- },
- name: "researcher",
- },
- remoteAgents: [
- {
- description: "Answer niche follow-up questions remotely.",
- entryPath: `${researcherRoot}/subagents/qux.ts`,
- logicalPath: "subagents/qux.ts",
- name: "qux",
- nodeId: "subagents/qux.ts",
- path: "/eve/v1/session",
- rootPath: researcherRoot,
- sourceId: "subagents/qux.ts",
- sourceKind: "module",
- url: "https://qux.example.com",
- },
- ],
- });
- const manifest = createCompiledAgentManifest({
- agentRoot,
- appRoot,
- config: {
- model: {
- id: TEST_DEFAULT_MODEL_ID,
- routing: { kind: "gateway", target: "openai" },
- },
- name: "router",
- },
- remoteAgents: [
- {
- description: "Answer weather questions remotely.",
- entryPath: `${agentRoot}/subagents/weather.ts`,
- logicalPath: "subagents/weather.ts",
- name: "weather",
- nodeId: "subagents/weather.ts",
- path: "/eve/v1/session",
- rootPath: agentRoot,
- sourceId: "subagents/weather.ts",
- sourceKind: "module",
- },
- ],
- subagentEdges: [
- {
- childNodeId: "subagents/researcher",
- parentNodeId: ROOT_COMPILED_AGENT_NODE_ID,
- },
- ],
- subagents: [
- {
- agent: researcherManifest,
- description: "Investigate one task in depth.",
- entryPath: researcherRoot,
- logicalPath: "subagents/researcher",
- name: "researcher",
- nodeId: "subagents/researcher",
- rootPath: researcherRoot,
- sourceId: "subagents/researcher",
- sourceKind: "module",
- },
- ],
- });
- const graph = await resolveRuntimeAgentGraph({
- manifest,
- moduleMap: {
- nodes: {
- [ROOT_COMPILED_AGENT_NODE_ID]: {
- modules: {
- "subagents/weather.ts": {
- default: {
- description: "Answer weather questions remotely.",
- kind: "remote",
- path: "/eve/v1/session",
- url: () => "https://weather.example.com",
- },
- },
- },
- },
- "subagents/researcher": {
- modules: {
- "subagents/qux.ts": {
- default: {
- description: "Answer niche follow-up questions remotely.",
- kind: "remote",
- path: "/eve/v1/session",
- url: "https://qux.example.com",
- },
- },
- },
- },
- },
- },
- });
- const rootRemote = graph.root.subagentRegistry.subagentsByName.get("weather");
- const researcherNode = graph.nodesByNodeId.get("subagents/researcher");
- const nestedRemote = researcherNode?.subagentRegistry.subagentsByName.get("qux");
-
- expect([...graph.nodesByNodeId.keys()].sort()).toEqual([
- ROOT_RUNTIME_AGENT_NODE_ID,
- "subagents/researcher",
- ]);
- expect(graph.root.subagentRegistry.subagentsByName.has("qux")).toBe(false);
- expect(rootRemote?.prepared).toMatchObject({
- kind: "remote",
- logicalPath: "subagents/weather.ts",
- name: "weather",
- nodeId: "subagents/weather.ts",
- });
- expect(rootRemote?.definition).toMatchObject({
- kind: "remote",
- url: "https://weather.example.com",
- });
- expect(nestedRemote?.prepared).toMatchObject({
- kind: "remote",
- logicalPath: "subagents/qux.ts",
- name: "qux",
- nodeId: "subagents/qux.ts",
- });
- expect(nestedRemote?.definition).toMatchObject({
- kind: "remote",
- url: "https://qux.example.com",
- });
- });
-
- it("resolves a remote subagent url function from process.env at runtime", async () => {
- vi.stubEnv("WEATHER_AGENT_URL", "https://weather.internal.vercel.app");
- const agentRoot = "/app/agent";
- const manifest = createCompiledAgentManifest({
- agentRoot,
- appRoot: "/app",
- config: {
- model: {
- id: TEST_DEFAULT_MODEL_ID,
- routing: { kind: "gateway", target: "openai" },
- },
- name: "router",
- },
- remoteAgents: [
- {
- description: "Answer weather questions remotely.",
- entryPath: `${agentRoot}/subagents/weather.ts`,
- logicalPath: "subagents/weather.ts",
- name: "weather",
- nodeId: "subagents/weather.ts",
- path: "/eve/v1/session",
- rootPath: agentRoot,
- sourceId: "subagents/weather.ts",
- sourceKind: "module",
- },
- ],
- });
- const graph = await resolveRuntimeAgentGraph({
- manifest,
- moduleMap: {
- nodes: {
- [ROOT_COMPILED_AGENT_NODE_ID]: {
- modules: {
- "subagents/weather.ts": {
- default: {
- description: "Answer weather questions remotely.",
- kind: "remote",
- path: "/eve/v1/session",
- url: () => process.env.WEATHER_AGENT_URL,
- },
- },
- },
- },
- },
- },
- });
-
- expect(graph.root.subagentRegistry.subagentsByName.get("weather")?.definition).toMatchObject({
- kind: "remote",
- url: "https://weather.internal.vercel.app",
- });
- });
-
- it("lets an authored tool replace a framework tool by name collision", async () => {
- const manifest = createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- model: {
- id: TEST_DEFAULT_MODEL_ID,
- routing: { kind: "gateway", target: "openai" },
- },
- name: "weather-agent",
- },
- tools: [
- {
- description: "Run a vetted shell command in the project sandbox.",
- inputSchema: null,
- logicalPath: "tools/bash.mjs",
- name: "bash",
- sourceId: "tools/bash.mjs",
- sourceKind: "module",
- },
- ],
- });
- const moduleMap: CompiledModuleMap = {
- nodes: {
- [ROOT_COMPILED_AGENT_NODE_ID]: {
- modules: {
- "tools/bash.mjs": {
- default: {
- description: "Run a vetted shell command in the project sandbox.",
- execute(input: unknown) {
- return { kind: "authored-bash", input };
- },
- name: "bash",
- },
- },
- },
- },
- },
- };
-
const graph = await resolveRuntimeAgentGraph({ manifest, moduleMap });
- const tools = graph.root.turnAgent.tools;
- const bashEntries = tools.filter((tool) => tool.name === "bash");
+ const names = graph.root.turnAgent.tools.map((tool) => tool.name);
- expect(bashEntries).toHaveLength(1);
- expect(bashEntries[0]).toMatchObject({
- description: "Run a vetted shell command in the project sandbox.",
- kind: "authored-tool",
- logicalPath: "tools/bash.mjs",
- name: "bash",
- });
- expect(tools.map((tool) => tool.name)).toEqual([
- "ask_question",
- "read_file",
- "write_file",
- "todo",
- "web_fetch",
- "web_search",
- "load_skill",
- "bash",
- ]);
+ expect(graph.root.nodeId).toBe("__root__");
+ expect(graph.root.sandboxRegistry.sandbox.definition.backend.name).toBe("vercel");
+ expect(names).toEqual(manifest.tools.map((tool) => tool.name));
+ expect(names).toContain("web_search");
+ expect(graph.root.agent.tools.every((tool) => tool.owner.kind === "framework")).toBe(true);
});
- it("removes a framework tool when listed in disabledFrameworkTools", async () => {
- const manifest = createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- model: {
- id: TEST_DEFAULT_MODEL_ID,
- routing: { kind: "gateway", target: "openai" },
- },
- name: "weather-agent",
- },
- disabledFrameworkTools: ["web_fetch"],
- });
-
- const graph = await resolveRuntimeAgentGraph({
- manifest,
- moduleMap: {
- nodes: {
- [ROOT_COMPILED_AGENT_NODE_ID]: {
- modules: {},
- },
- },
- },
- });
-
- expect(graph.root.turnAgent.tools.map((tool) => tool.name)).toEqual([
- "ask_question",
- "bash",
- "read_file",
- "write_file",
- "todo",
- "web_search",
- "load_skill",
- ]);
- });
-
- it("accepts the runtime-owned agent tool in disabledFrameworkTools", async () => {
- const manifest = createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- model: {
- id: TEST_DEFAULT_MODEL_ID,
- routing: { kind: "gateway", target: "openai" },
- },
- name: "weather-agent",
- },
- disabledFrameworkTools: ["agent"],
- });
-
- const graph = await resolveRuntimeAgentGraph({
- manifest,
- moduleMap: {
- nodes: {
- [ROOT_COMPILED_AGENT_NODE_ID]: {
- modules: {},
- },
- },
- },
- });
-
- expect(graph.root.agent.disabledFrameworkTools).toContain("agent");
- expect(createNodeHarnessTools({ node: graph.root }).has("agent")).toBe(false);
- });
-
- it("combines replacement and disable in one agent", async () => {
- const manifest = createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- model: {
- id: TEST_DEFAULT_MODEL_ID,
- routing: { kind: "gateway", target: "openai" },
- },
- name: "weather-agent",
- },
- disabledFrameworkTools: ["web_fetch"],
- tools: [
+ it("uses authored replacement and disable decisions already recorded by the compiler", async () => {
+ const { manifest, moduleMap } = await compileFromMemory({
+ model: "openai/gpt-5.4",
+ modules: [
{
- description: "Sandboxed shell.",
- inputSchema: null,
- logicalPath: "tools/bash.mjs",
- name: "bash",
- sourceId: "tools/bash.mjs",
- sourceKind: "module",
+ loadNamespace: async () => ({ default: disableTool() }),
+ logicalPath: "tools/web_fetch.ts",
},
],
- });
- const moduleMap: CompiledModuleMap = {
- nodes: {
- [ROOT_COMPILED_AGENT_NODE_ID]: {
- modules: {
- "tools/bash.mjs": {
- default: {
- description: "Sandboxed shell.",
- execute(input: unknown) {
- return input;
- },
- name: "bash",
- },
- },
- },
- },
- },
- };
-
- const graph = await resolveRuntimeAgentGraph({ manifest, moduleMap });
- const tools = graph.root.turnAgent.tools;
-
- expect(tools.map((tool) => tool.name)).toEqual([
- "ask_question",
- "read_file",
- "write_file",
- "todo",
- "web_search",
- "load_skill",
- "bash",
- ]);
- expect(tools.find((tool) => tool.name === "bash")).toMatchObject({
- description: "Sandboxed shell.",
- logicalPath: "tools/bash.mjs",
- });
- });
-
- it("includes web_search as a default framework tool", async () => {
- const manifest = createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- model: {
- id: TEST_DEFAULT_MODEL_ID,
- routing: { kind: "gateway", target: "openai" },
- },
- name: "weather-agent",
- },
- });
-
- const graph = await resolveRuntimeAgentGraph({
- manifest,
- moduleMap: {
- nodes: {
- [ROOT_COMPILED_AGENT_NODE_ID]: {
- modules: {},
- },
- },
- },
- });
-
- expect(graph.root.turnAgent.tools.map((t) => t.name)).toContain("web_search");
- });
-
- it("removes web_search when listed in disabledFrameworkTools", async () => {
- const manifest = createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- model: {
- id: TEST_DEFAULT_MODEL_ID,
- routing: { kind: "gateway", target: "openai" },
- },
- name: "weather-agent",
- },
- disabledFrameworkTools: ["web_search"],
- });
-
- const graph = await resolveRuntimeAgentGraph({
- manifest,
- moduleMap: {
- nodes: {
- [ROOT_COMPILED_AGENT_NODE_ID]: {
- modules: {},
- },
- },
- },
- });
-
- expect(graph.root.turnAgent.tools.map((t) => t.name)).not.toContain("web_search");
- });
-
- it("replaces the framework web_search when an authored tool overrides it", async () => {
- const manifest = createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- model: {
- id: TEST_DEFAULT_MODEL_ID,
- routing: { kind: "gateway", target: "openai" },
- },
- name: "weather-agent",
- },
tools: [
{
- description: "Custom web search.",
- inputSchema: null,
- logicalPath: "tools/web_search.mjs",
- name: "web_search",
- sourceId: "tools/web_search.mjs",
- sourceKind: "module",
+ description: "Application-owned shell.",
+ execute: (input) => input,
+ name: "bash",
},
],
});
- const moduleMap: CompiledModuleMap = {
- nodes: {
- [ROOT_COMPILED_AGENT_NODE_ID]: {
- modules: {
- "tools/web_search.mjs": {
- default: {
- description: "Custom web search.",
- execute(input: unknown) {
- return input;
- },
- name: "web_search",
- },
- },
- },
- },
- },
- };
const graph = await resolveRuntimeAgentGraph({ manifest, moduleMap });
-
- expect(graph.root.turnAgent.tools.find((t) => t.name === "web_search")).toMatchObject({
- description: "Custom web search.",
- kind: "authored-tool",
- name: "web_search",
- });
+ const bash = graph.root.turnAgent.tools.filter((tool) => tool.name === "bash");
+
+ expect(bash).toHaveLength(1);
+ expect(bash[0]).toMatchObject({
+ description: "Application-owned shell.",
+ owner: { kind: "application" },
+ });
+ expect(graph.root.turnAgent.tools.map((tool) => tool.name)).not.toContain("web_fetch");
+ expect(manifest.sourceComposition.entries).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ kind: "shadowed",
+ winnerSourceId: expect.stringContaining("tools/bash.ts"),
+ }),
+ expect.objectContaining({
+ kind: "disabled",
+ source: expect.objectContaining({ logicalPath: "tools/web_fetch.ts" }),
+ }),
+ ]),
+ );
});
- it("throws when disabledFrameworkTools references an unknown framework tool", async () => {
- const manifest = createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- model: {
- id: TEST_DEFAULT_MODEL_ID,
- routing: { kind: "gateway", target: "openai" },
- },
- name: "weather-agent",
- },
- disabledFrameworkTools: ["nonexistent_tool"],
- });
+ it("rejects module maps that diverge from the manifest bindings", async () => {
+ const { manifest, moduleMap } = await compileFromMemory({ model: "openai/gpt-5.4" });
+ const root = moduleMap.nodes.__root__!;
+ const [removed, ...remaining] = Object.entries(root.modules);
+ if (removed === undefined) throw new Error("Expected compiled bindings.");
await expect(
resolveRuntimeAgentGraph({
manifest,
- moduleMap: {
- nodes: {
- [ROOT_COMPILED_AGENT_NODE_ID]: {
- modules: {},
- },
- },
- },
+ moduleMap: { nodes: { __root__: { modules: Object.fromEntries(remaining) } } },
}),
- ).rejects.toThrow(
- /agent\/tools\/nonexistent_tool\.ts exports disableTool\(\) but "nonexistent_tool" is not a framework tool/,
- );
+ ).rejects.toThrow("do not match its bindings");
});
});
diff --git a/packages/eve/test/runtime-prompt-compose.test.ts b/packages/eve/test/runtime-prompt-compose.test.ts
index ef69206e9..5823be9dc 100644
--- a/packages/eve/test/runtime-prompt-compose.test.ts
+++ b/packages/eve/test/runtime-prompt-compose.test.ts
@@ -10,6 +10,7 @@ describe("composeRuntimeBasePrompt", () => {
content: "You are a weather assistant.\n",
name: "instructions",
logicalPath: "instructions.md",
+ owner: { kind: "application" },
role: "system",
sourceId: "instructions.md",
sourceKind: "markdown",
@@ -40,6 +41,7 @@ describe("composeRuntimeBasePrompt", () => {
content: " \n",
name: "instructions",
logicalPath: "instructions.md",
+ owner: { kind: "application" },
role: "system",
sourceId: "instructions.md",
sourceKind: "markdown",
@@ -57,6 +59,7 @@ describe("composeRuntimeBasePrompt", () => {
content: "First system block.",
logicalPath: "instructions/10-first.md",
name: "instructions/10-first",
+ owner: { kind: "application" },
role: "system",
sourceId: "instructions/10-first.md",
sourceKind: "markdown",
@@ -65,6 +68,7 @@ describe("composeRuntimeBasePrompt", () => {
content: "Durable user context.",
logicalPath: "instructions/20-user.ts",
name: "instructions/20-user",
+ owner: { kind: "application" },
role: "user",
sourceId: "instructions/20-user.ts",
sourceKind: "module",
@@ -73,6 +77,7 @@ describe("composeRuntimeBasePrompt", () => {
content: "Second system block.",
logicalPath: "instructions/30-second.ts",
name: "instructions/30-second",
+ owner: { kind: "application" },
role: "system",
sourceId: "instructions/30-second.ts",
sourceKind: "module",
@@ -89,6 +94,7 @@ describe("composeRuntimeBasePrompt", () => {
content: " First system block. ",
logicalPath: "instructions/a.ts",
name: "instructions/a",
+ owner: { kind: "application" },
role: "system",
sourceId: "instructions/a.ts",
sourceKind: "module",
@@ -97,6 +103,7 @@ describe("composeRuntimeBasePrompt", () => {
content: "\tSecond system block.\n",
logicalPath: "instructions/b.ts",
name: "instructions/b",
+ owner: { kind: "application" },
role: "system",
sourceId: "instructions/b.ts",
sourceKind: "module",
diff --git a/packages/eve/test/runtime-sandbox-registry.test.ts b/packages/eve/test/runtime-sandbox-registry.test.ts
deleted file mode 100644
index 1f019b0e9..000000000
--- a/packages/eve/test/runtime-sandbox-registry.test.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import type { CompiledWorkspaceResourceRoot } from "../src/compiler/manifest.js";
-import { docker } from "../src/public/sandbox/backends/docker.js";
-import {
- createFrameworkSandboxDefinition,
- createRuntimeSandboxRegistry,
- DEFAULT_SANDBOX_SOURCE_ID,
-} from "../src/runtime/sandbox/registry.js";
-import type { ResolvedSandboxDefinition } from "../src/runtime/types.js";
-
-const EMPTY_RESOURCE_ROOT: CompiledWorkspaceResourceRoot = {
- logicalPath: "",
- rootEntries: [],
-};
-
-describe("createRuntimeSandboxRegistry", () => {
- it("falls back to the framework default sandbox when no authored override is present", () => {
- const registry = createRuntimeSandboxRegistry({
- authoredSandbox: null,
- workspaceResourceRoot: EMPTY_RESOURCE_ROOT,
- });
-
- expect(registry.sandbox?.definition.sourceId).toBe(DEFAULT_SANDBOX_SOURCE_ID);
- expect(registry.sandbox?.workspaceResourceRoot).toBe(EMPTY_RESOURCE_ROOT);
- });
-
- it("attaches the workspace resource root descriptor to the framework default", () => {
- const workspaceResourceRoot: CompiledWorkspaceResourceRoot = {
- logicalPath: "workspace-resources/__root__",
- rootEntries: ["skills/"],
- };
-
- const registry = createRuntimeSandboxRegistry({
- authoredSandbox: null,
- workspaceResourceRoot,
- });
-
- expect(registry.sandbox?.definition.sourceId).toBe(DEFAULT_SANDBOX_SOURCE_ID);
- expect(registry.sandbox?.workspaceResourceRoot).toBe(workspaceResourceRoot);
- });
-
- it("uses the authored sandbox when provided, replacing the framework default", () => {
- const authoredSandbox = createResolvedSandboxDefinition({
- logicalPath: "sandbox/sandbox.ts",
- sourceId: "sandbox/sandbox.ts",
- });
-
- const registry = createRuntimeSandboxRegistry({
- authoredSandbox,
- workspaceResourceRoot: EMPTY_RESOURCE_ROOT,
- });
-
- expect(registry.sandbox?.definition).toBe(authoredSandbox);
- });
-
- it("attaches the workspace resource root descriptor to the authored sandbox", () => {
- const authoredSandbox = createResolvedSandboxDefinition({
- logicalPath: "sandbox/sandbox.ts",
- sourceId: "sandbox/sandbox.ts",
- });
- const workspaceResourceRoot: CompiledWorkspaceResourceRoot = {
- logicalPath: "workspace-resources/__root__",
- rootEntries: ["skills/"],
- };
-
- const registry = createRuntimeSandboxRegistry({
- authoredSandbox,
- workspaceResourceRoot,
- });
-
- expect(registry.sandbox?.definition).toBe(authoredSandbox);
- expect(registry.sandbox?.workspaceResourceRoot).toBe(workspaceResourceRoot);
- });
-
- it("createFrameworkSandboxDefinition resolves a fresh default backend on each call", () => {
- const definition = createFrameworkSandboxDefinition();
-
- expect(definition.sourceId).toBe(DEFAULT_SANDBOX_SOURCE_ID);
- expect(definition.sourceKind).toBe("module");
- expect(typeof definition.backend.name).toBe("string");
- });
-});
-
-function createResolvedSandboxDefinition(input: {
- readonly logicalPath: string;
- readonly sourceId: string;
-}): ResolvedSandboxDefinition {
- return {
- backend: docker(),
- logicalPath: input.logicalPath,
- sourceId: input.sourceId,
- sourceKind: "module",
- };
-}
diff --git a/packages/eve/test/runtime-schedule-resolution.test.ts b/packages/eve/test/runtime-schedule-resolution.test.ts
index 3fc291ee9..69e43caea 100644
--- a/packages/eve/test/runtime-schedule-resolution.test.ts
+++ b/packages/eve/test/runtime-schedule-resolution.test.ts
@@ -1,64 +1,41 @@
import { describe, expect, it } from "vitest";
-import { createCompiledAgentManifest } from "../src/compiler/manifest.js";
-import { TEST_DEFAULT_MODEL_ID } from "../src/internal/testing/app-harness.js";
+import { compileFromMemory } from "../src/compiler/compile-from-memory.js";
+import { defineSchedule } from "../src/public/definitions/schedule.js";
import { resolveSchedules } from "../src/runtime/schedules/resolve-schedule.js";
describe("resolveSchedules", () => {
- it("hydrates compiled authored schedules into runtime-owned models", async () => {
- const manifest = createCompiledAgentManifest({
- agentRoot: "/app/agent",
- appRoot: "/app",
- config: {
- model: {
- id: TEST_DEFAULT_MODEL_ID,
- routing: { kind: "gateway", target: "openai" },
- },
- name: "weather-agent",
- },
- schedules: [
+ it("hydrates effective compiled schedules into runtime-owned models", async () => {
+ const { manifest } = await compileFromMemory({
+ model: "openai/gpt-5.4",
+ modules: [
{
- cron: "0 8 * * *",
- hasRun: true,
- name: "daily-digest",
- logicalPath: "schedules/daily-digest.mjs",
- sourceId: "schedules/daily-digest.mjs",
- sourceKind: "module",
+ loadNamespace: async () => ({
+ default: defineSchedule({ cron: "0 8 * * *", run: async () => undefined }),
+ }),
+ logicalPath: "schedules/daily-digest.ts",
},
{
- cron: "0 0 * * 0",
- hasRun: false,
- name: "cleanup",
- logicalPath: "schedules/cleanup.md",
- markdown: "Clean stale data.",
- sourceId: "schedules/cleanup.md",
- sourceKind: "markdown",
+ loadNamespace: async () => ({
+ default: defineSchedule({ cron: "0 0 * * 0", markdown: "Clean stale data." }),
+ }),
+ logicalPath: "schedules/cleanup.ts",
},
],
});
- await expect(
- resolveSchedules({
- manifest,
- }),
- ).resolves.toEqual([
- {
+ await expect(resolveSchedules({ manifest })).resolves.toEqual([
+ expect.objectContaining({
cron: "0 8 * * *",
hasRun: true,
name: "daily-digest",
- logicalPath: "schedules/daily-digest.mjs",
- sourceId: "schedules/daily-digest.mjs",
- sourceKind: "module",
- },
- {
+ }),
+ expect.objectContaining({
cron: "0 0 * * 0",
hasRun: false,
- name: "cleanup",
- logicalPath: "schedules/cleanup.md",
markdown: "Clean stale data.",
- sourceId: "schedules/cleanup.md",
- sourceKind: "markdown",
- },
+ name: "cleanup",
+ }),
]);
});
});
diff --git a/packages/eve/test/runtime-subagent-registry.test.ts b/packages/eve/test/runtime-subagent-registry.test.ts
index 3ebd21c1f..7a64542e3 100644
--- a/packages/eve/test/runtime-subagent-registry.test.ts
+++ b/packages/eve/test/runtime-subagent-registry.test.ts
@@ -1,10 +1,8 @@
import { describe, expect, it } from "vitest";
import { RuntimeRegistryError } from "../src/internal/runtime-registry.js";
-import {
- createRuntimeSubagentRegistry,
- PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA,
-} from "../src/runtime/subagents/registry.js";
+import { createRuntimeSubagentRegistry } from "../src/runtime/subagents/registry.js";
+import { PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA } from "../src/shared/agent-tool.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.ts
index 10b6363fd..fda15ead1 100644
--- a/packages/eve/test/runtime-tool-registry.test.ts
+++ b/packages/eve/test/runtime-tool-registry.test.ts
@@ -99,6 +99,7 @@ function createResolvedToolDefinition(input: {
},
logicalPath: input.logicalPath,
name: input.name,
+ owner: { kind: "application" },
sourceId: input.sourceId,
sourceKind: "module",
};
diff --git a/packages/eve/test/scenarios/agent-info-route.scenario.test.ts b/packages/eve/test/scenarios/agent-info-route.scenario.test.ts
index 746ad7c0d..e74769fdc 100644
--- a/packages/eve/test/scenarios/agent-info-route.scenario.test.ts
+++ b/packages/eve/test/scenarios/agent-info-route.scenario.test.ts
@@ -14,8 +14,6 @@ import { useTemporaryAppRoots } from "../../src/internal/testing/use-temporary-a
const createAppRoot = useTemporaryAppRoots();
const APP_ROOT_OPTIONS = { packageName: "agent-info-route-test-agent" } as const;
-const EVE_CHANNEL_IMPORT_URL = new URL("../../dist/src/public/channels/eve.js", import.meta.url);
-const EVE_TOOLS_IMPORT_URL = new URL("../../dist/src/public/tools/index.js", import.meta.url);
const INFO_ROUTE_KEY = `GET ${EVE_INFO_ROUTE_PATH}`;
// A request to the local server. The deployment environment, not this
@@ -36,42 +34,6 @@ type MinimalAgentInfoH3Event = Pick<H3Event, "context" | "waitUntil"> & {
readonly req: Request;
};
-async function installEveChannelShim(appRoot: string): Promise<void> {
- const packageRoot = join(appRoot, "node_modules", "eve");
- await mkdir(join(packageRoot, "channels"), { recursive: true });
- await writeFile(
- join(packageRoot, "package.json"),
- `${JSON.stringify(
- {
- name: "eve",
- type: "module",
- exports: {
- "./channels/eve": "./channels/eve.js",
- },
- },
- null,
- 2,
- )}\n`,
- );
- await writeFile(
- join(packageRoot, "channels", "eve.js"),
- `export { eveChannel } from ${JSON.stringify(EVE_CHANNEL_IMPORT_URL.href)};\n`,
- );
-}
-
-async function installEveToolsShim(appRoot: string): Promise<void> {
- const packageRoot = join(appRoot, "node_modules", "eve");
- await mkdir(packageRoot, { recursive: true });
- await writeFile(
- join(packageRoot, "package.json"),
- `${JSON.stringify({ name: "eve", type: "module", exports: { "./tools": "./tools.js" } })}\n`,
- );
- await writeFile(
- join(packageRoot, "tools.js"),
- `export { disableTool } from ${JSON.stringify(EVE_TOOLS_IMPORT_URL.href)};\n`,
- );
-}
-
function createInfoEvent(request: Request): H3Event {
Object.assign(request, { ip: "127.0.0.1" });
const event: MinimalAgentInfoH3Event = {
@@ -103,7 +65,6 @@ describe("eve agent info route", () => {
await writeFile(join(agentRoot, "agent.mjs"), 'export default { model: "openai/gpt-5.4" };\n');
await writeFile(join(agentRoot, "instructions.md"), "You are a precise assistant.\n");
await mkdir(join(agentRoot, "tools"), { recursive: true });
- await installEveToolsShim(appRoot);
await writeFile(
join(agentRoot, "tools", "get_weather.mjs"),
'export default { description: "Get the weather.", async execute() { return { temperature: 72 }; } };\n',
@@ -122,28 +83,32 @@ describe("eve agent info route", () => {
const payload = (await response.json()) as AgentInfoResponse;
expect(payload.kind).toBe("eve-agent-info");
- expect(payload.version).toBe(2);
+ expect(payload.version).toBe(3);
expect(payload.mode).toBe("development");
expect(payload.agent.model.id).toBe("openai/gpt-5.4");
expect(payload.instructions.static[0]?.content).toContain("precise assistant");
expect(payload.instructions.static[0]?.role).toBe("system");
expect(payload.instructions.dynamic).toEqual([]);
- expect(payload.tools.authored.map((tool) => tool.name)).toEqual(["get_weather"]);
- expect(payload.tools.available.map((tool) => tool.name)).toContain("bash");
- expect(payload.tools.available.map((tool) => tool.name)).toContain("agent");
- expect(payload.tools.available.map((tool) => tool.name)).toContain("get_weather");
- expect(payload.tools.framework.find((tool) => tool.name === "bash")).toMatchObject({
- origin: "framework",
- status: "active",
+ expect(
+ payload.tools.static
+ .filter((tool) => tool.owner.kind === "application")
+ .map((tool) => tool.name),
+ ).toEqual(["get_weather"]);
+ expect(payload.tools.static.map((tool) => tool.name)).toContain("bash");
+ expect(payload.tools.static.map((tool) => tool.name)).toContain("agent");
+ expect(payload.tools.static.map((tool) => tool.name)).toContain("get_weather");
+ expect(payload.tools.static.find((tool) => tool.name === "bash")).toMatchObject({
+ owner: { kind: "framework" },
});
- expect(payload.tools.framework.find((tool) => tool.name === "agent")).toMatchObject({
- origin: "framework",
- status: "active",
+ expect(payload.tools.static.find((tool) => tool.name === "agent")).toMatchObject({
+ owner: { kind: "framework" },
});
- expect(payload.channels.available.map((channel) => channel.urlPath)).toContain(
+ expect(payload.channels.routes.map((channel) => channel.urlPath)).toContain(
EVE_SESSION_ROUTE_PATH,
);
- expect(payload.channels.framework.length).toBeGreaterThan(0);
+ expect(payload.channels.routes.some((channel) => channel.owner.kind === "framework")).toBe(
+ true,
+ );
expect(payload.diagnostics).toEqual({
discoveryErrors: 0,
discoveryWarnings: 0,
@@ -159,11 +124,10 @@ describe("eve agent info route", () => {
await requestAgentInfo(appRoot, LOOPBACK_REQUEST)
).json()) as AgentInfoResponse;
- expect(disabledPayload.tools.available.map((tool) => tool.name)).not.toContain("agent");
- expect(disabledPayload.tools.framework.find((tool) => tool.name === "agent")).toMatchObject({
- disabledByAuthor: true,
- status: "disabled",
- });
+ expect(disabledPayload.tools.static.map((tool) => tool.name)).not.toContain("agent");
+ expect(
+ disabledPayload.composition.disabled.some((entry) => entry.logicalPath === "tools/agent.mjs"),
+ ).toBe(true);
});
it("returns 401 for a deployment request without a Vercel OIDC bearer token", async () => {
@@ -199,7 +163,6 @@ describe("eve agent info route", () => {
);
await mkdir(join(agentRoot, "channels"), { recursive: true });
- await installEveChannelShim(appRoot);
await writeFile(join(agentRoot, "agent.mjs"), 'export default { model: "openai/gpt-5.4" };\n');
await writeFile(join(agentRoot, "instructions.md"), "You are a precise assistant.\n");
await writeFile(
diff --git a/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.ts b/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.ts
index 8c8a032d2..ef9722b0f 100644
--- a/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.ts
+++ b/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.ts
@@ -802,7 +802,7 @@ describe("app runtime dependency tracing", () => {
expect(serverModuleSource).not.toContain('import("esbuild")');
expect(serverModuleSource).not.toContain('import("rolldown")');
expect(serverModuleSource).toContain(
- "This tool requires sandbox access on the runtime context.",
+ "Execute a shell command in the shared workspace environment.",
);
expect(serverModuleSource).toContain("The dynamic skill");
expect(serverModuleSource).toContain("URL must start with https://");
diff --git a/packages/eve/test/scenarios/bundle-module-evaluation.scenario.test.ts b/packages/eve/test/scenarios/bundle-module-evaluation.scenario.test.ts
index 1eeba0aba..24d829876 100644
--- a/packages/eve/test/scenarios/bundle-module-evaluation.scenario.test.ts
+++ b/packages/eve/test/scenarios/bundle-module-evaluation.scenario.test.ts
@@ -94,18 +94,16 @@ describe("eve dist single-chunk module evaluation", () => {
expect(loaded.__steps_registered).toBe(true);
}, 180_000);
- it("every framework tool definition is defined in the concatenated chunk (no silent `undefined` slots)", async () => {
- // Defense in depth: catches any future cycle that lands a
- // `*_TOOL_DEFINITION` after the registry in the bundle.
- const scratch = await createScratchDirectory("eve-framework-tools-eval-");
+ it("loads every framework programmatic namespace from the concatenated chunk", async () => {
+ const scratch = await createScratchDirectory("eve-framework-sources-eval-");
const outDir = join(scratch, "out");
await mkdir(outDir, { recursive: true });
const entryFile = join(scratch, "entry.mjs");
- const eveEntry = resolvePackageSourceFilePath("src/runtime/framework-tools/index.ts");
+ const eveEntry = resolvePackageSourceFilePath("src/framework/sources/registry.ts");
await writeFile(
entryFile,
- `import * as ft from ${JSON.stringify(eveEntry)};\nexport default ft;\n`,
+ `import * as sources from ${JSON.stringify(eveEntry)};\nexport default sources;\n`,
);
const outfile = await bundleEveDistAsSingleChunk({
@@ -115,12 +113,14 @@ describe("eve dist single-chunk module evaluation", () => {
});
const loaded = await import(pathToFileURL(outfile).href);
- const tools = loaded.default.getAllFrameworkToolDefinitions();
- expect(tools.length).toBeGreaterThan(0);
- for (const tool of tools) {
- expect(tool, "framework tool entry must be defined").toBeDefined();
- expect(typeof tool.name).toBe("string");
- expect(tool.name.length).toBeGreaterThan(0);
+ const registry = loaded.default.frameworkAgentSourceRegistry;
+ const modules = registry.registrations.flatMap(
+ (registration: { source: { modules: Array<{ loadNamespace(): Promise<unknown> }> } }) =>
+ registration.source.modules,
+ );
+ expect(modules.length).toBeGreaterThan(0);
+ for (const module of modules) {
+ await expect(module.loadNamespace()).resolves.toMatchObject({ default: expect.anything() });
}
}, 180_000);
});
diff --git a/packages/eve/test/scenarios/compile-agent.scenario.test.ts b/packages/eve/test/scenarios/compile-agent.scenario.test.ts
index 20a387ed6..afbcd0a52 100644
--- a/packages/eve/test/scenarios/compile-agent.scenario.test.ts
+++ b/packages/eve/test/scenarios/compile-agent.scenario.test.ts
@@ -17,6 +17,7 @@ import { CompileAgentError, compileAgent } from "../../src/compiler/compile-agen
import {
COMPILED_AGENT_MANIFEST_VERSION,
ROOT_COMPILED_AGENT_NODE_ID,
+ type CompiledAgentManifest,
} from "../../src/compiler/manifest.js";
import { createDiscoverWarningDiagnostic } from "../../src/discover/diagnostics.js";
import {
@@ -48,6 +49,13 @@ const TSC_BIN_PATH = fileURLToPath(
);
const DEFAULT_AGENT_MODEL_ID = "zai/glm-5.2";
+function applicationOwnedEntries<TEntry extends { readonly sourceId: string }>(
+ manifest: CompiledAgentManifest,
+ entries: readonly TEntry[],
+): TEntry[] {
+ return entries.filter((entry) => manifest.bindings[entry.sourceId]?.owner.kind === "application");
+}
+
describe("compiler artifacts", () => {
it("uses the framework default model when agent.ts is omitted", async () => {
const { agentRoot, appRoot } = await createAppRoot(
@@ -66,7 +74,14 @@ describe("compiler artifacts", () => {
},
name: "test-agent",
});
- expect(withoutConfig.manifest.config.source).toBeUndefined();
+ expect(withoutConfig.manifest.config.source).toMatchObject({
+ logicalPath: "agent.ts",
+ sourceId: "eve:defaults:agent.ts",
+ sourceKind: "module",
+ });
+ expect(
+ withoutConfig.manifest.bindings[withoutConfig.manifest.config.source.sourceId]?.owner,
+ ).toEqual({ feature: "eve:defaults", kind: "framework" });
await writeFile(join(agentRoot, "agent.mjs"), "export default {};\n");
await expect(compileAgent({ startPath: appRoot })).rejects.toThrow(
@@ -183,9 +198,13 @@ describe("compiler artifacts", () => {
sourceId: "instructions.md",
},
],
- version: 13,
+ version: 14,
});
- expect(normalizeArtifactValue(JSON.parse(compiledManifestText), appRoot)).toMatchObject({
+ const compiledArtifact = normalizeArtifactValue(
+ JSON.parse(compiledManifestText) as CompiledAgentManifest,
+ appRoot,
+ );
+ expect(compiledArtifact).toMatchObject({
agentRoot: "<app-root>/agent",
appRoot: "<app-root>",
config: {
@@ -200,8 +219,22 @@ describe("compiler artifacts", () => {
errors: 0,
warnings: 1,
},
- channels: [
+ kind: "eve-agent-compiled-manifest",
+ instructions: [
{
+ content: "You are a precise assistant.",
+ name: "instructions",
+ logicalPath: "instructions.md",
+ role: "system",
+ sourceId: "instructions.md",
+ sourceKind: "markdown",
+ },
+ ],
+ version: COMPILED_AGENT_MANIFEST_VERSION,
+ });
+ expect(compiledArtifact.channelRoutes.effective).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
kind: "channel",
logicalPath: "channels/support.mjs",
method: "POST",
@@ -209,8 +242,8 @@ describe("compiler artifacts", () => {
sourceId: "channels/support.mjs",
sourceKind: "module",
urlPath: "/support",
- },
- {
+ }),
+ expect.objectContaining({
kind: "channel",
logicalPath: "channels/support.mjs",
method: "GET",
@@ -218,36 +251,29 @@ describe("compiler artifacts", () => {
sourceId: "channels/support.mjs",
sourceKind: "module",
urlPath: "/support/events",
- },
- ],
- kind: "eve-agent-compiled-manifest",
- instructions: [
- {
- content: "You are a precise assistant.",
- name: "instructions",
- logicalPath: "instructions.md",
- role: "system",
- sourceId: "instructions.md",
- sourceKind: "markdown",
- },
- ],
- version: COMPILED_AGENT_MANIFEST_VERSION,
- });
+ }),
+ ]),
+ );
expect(normalizeArtifactValue(JSON.parse(diagnosticsText), appRoot)).toMatchObject({
diagnostics: [
{
code: "discover/unsupported-directory",
message: 'Ignoring unsupported directory "drafts/" in the agent root.',
severity: "warning",
- sourcePath: "<app-root>/agent/drafts",
+ sources: [
+ {
+ nodeId: "__root__",
+ sourcePath: "<app-root>/agent/drafts",
+ },
+ ],
},
],
- kind: "eve-discovery-diagnostics",
+ kind: "eve-compiler-diagnostics",
summary: {
errors: 0,
warnings: 1,
},
- version: 1,
+ version: 2,
});
const compileMetadata = JSON.parse(metadataText) as {
generator: {
@@ -285,7 +311,7 @@ describe("compiler artifacts", () => {
},
kind: "eve-compile-metadata",
status: "ready",
- version: 5,
+ version: COMPILE_METADATA_VERSION,
});
expect(moduleMapText).toContain('"nodes": Object.freeze({');
expect(moduleMapText).toContain(`"${ROOT_COMPILED_AGENT_NODE_ID}": Object.freeze({`);
@@ -409,26 +435,25 @@ describe("compiler artifacts", () => {
const normalizedModuleMapText = normalizeArtifactValue(moduleMapText.trimEnd(), appRoot);
- // Authored instructions modules execute once at build time and are baked into the
- // compiled manifest as markdown. They never appear in the module map.
- expect(normalizedModuleMapText).not.toContain("instructions.mjs");
- expect(normalizedModuleMapText).toContain('import * as module_0 from "../../agent/agent.mjs";');
+ // Every selected module-backed source retains a total binding, including
+ // modules whose normalized content is serialized into the manifest.
+ expect(normalizedModuleMapText).toContain('from "../../agent/agent.mjs";');
+ expect(normalizedModuleMapText).toContain('from "../../agent/instructions.mjs";');
+ expect(normalizedModuleMapText).toContain('from "../../agent/tools/get_weather.mjs";');
+ expect(normalizedModuleMapText).toContain('from "../../agent/subagents/reviewer/agent.mjs";');
expect(normalizedModuleMapText).toContain(
- 'import * as module_1 from "../../agent/tools/get_weather.mjs";',
+ 'from "../../agent/subagents/reviewer/instructions.mjs";',
);
expect(normalizedModuleMapText).toContain(
- 'import * as module_2 from "../../agent/subagents/reviewer/agent.mjs";',
- );
- expect(normalizedModuleMapText).toContain(
- 'import * as module_3 from "../../agent/subagents/reviewer/tools/review.mjs";',
+ 'from "../../agent/subagents/reviewer/tools/review.mjs";',
);
expect(normalizedModuleMapText).toContain('"nodes": Object.freeze({');
expect(normalizedModuleMapText).toContain(`"${ROOT_COMPILED_AGENT_NODE_ID}": Object.freeze({`);
- expect(normalizedModuleMapText).toContain('"agent.mjs": module_0');
- expect(normalizedModuleMapText).toContain('"tools/get_weather.mjs": module_1');
+ expect(normalizedModuleMapText).toMatch(/"agent\.mjs": module_\d+/);
+ expect(normalizedModuleMapText).toMatch(/"tools\/get_weather\.mjs": module_\d+/);
expect(normalizedModuleMapText).toContain('"subagents/reviewer": Object.freeze({');
- expect(normalizedModuleMapText).toContain('"agent.mjs": module_2');
- expect(normalizedModuleMapText).toContain('"tools/review.mjs": module_3');
+ expect(normalizedModuleMapText).toMatch(/"agent\.mjs": module_\d+/);
+ expect(normalizedModuleMapText).toMatch(/"tools\/review\.mjs": module_\d+/);
});
it("records versioned artifact hashes in compile metadata", () => {
@@ -436,7 +461,8 @@ describe("compiler artifacts", () => {
const paths = resolveCompilerArtifactPaths(appRoot);
const firstMetadata = createCompileMetadata({
appRoot,
- diagnosticsArtifactJson: '{"kind":"eve-discovery-diagnostics"}\n',
+ compiledManifestJson: '{"kind":"eve-compiled-agent-manifest"}\n',
+ diagnosticsArtifactJson: '{"kind":"eve-compiler-diagnostics"}\n',
diagnosticsSummary: {
errors: 0,
warnings: 1,
@@ -447,7 +473,8 @@ describe("compiler artifacts", () => {
});
const secondMetadata = createCompileMetadata({
appRoot,
- diagnosticsArtifactJson: '{"kind":"eve-discovery-diagnostics"}\n',
+ compiledManifestJson: '{"kind":"eve-compiled-agent-manifest"}\n',
+ diagnosticsArtifactJson: '{"kind":"eve-compiler-diagnostics"}\n',
diagnosticsSummary: {
errors: 0,
warnings: 1,
@@ -612,7 +639,7 @@ describe("compileAgent", () => {
sourceId: "agent.cjs",
},
});
- expect(result.manifest.schedules).toEqual([
+ expect(result.manifest.schedules).toMatchObject([
{
cron: "0 0 * * *",
hasRun: false,
@@ -623,7 +650,7 @@ describe("compileAgent", () => {
sourceKind: "module",
},
]);
- expect(result.manifest.skills).toEqual([
+ expect(result.manifest.skills).toMatchObject([
{
description: "Hand off the task to the next specialist.",
logicalPath: "skills/handoff.mts",
@@ -633,7 +660,7 @@ describe("compileAgent", () => {
sourceKind: "module",
},
]);
- expect(result.manifest.tools).toEqual([
+ expect(applicationOwnedEntries(result.manifest, result.manifest.tools)).toMatchObject([
{
description:
"Get weather details using lib extension imports through mixed extension loading across cjs/js/mts/mjs modules.",
@@ -653,12 +680,12 @@ describe("compileAgent", () => {
sourceId: "sandbox/sandbox.cjs",
sourceKind: "module",
});
- expect(normalizeArtifactValue(moduleMapText, app.appRoot)).toContain('"agent.cjs": module_0');
- expect(normalizeArtifactValue(moduleMapText, app.appRoot)).toContain(
- '"sandbox/sandbox.cjs": module_1',
+ expect(normalizeArtifactValue(moduleMapText, app.appRoot)).toMatch(/"agent\.cjs": module_\d+/);
+ expect(normalizeArtifactValue(moduleMapText, app.appRoot)).toMatch(
+ /"sandbox\/sandbox\.cjs": module_\d+/,
);
- expect(normalizeArtifactValue(moduleMapText, app.appRoot)).toContain(
- '"tools/get_weather.mts": module_2',
+ expect(normalizeArtifactValue(moduleMapText, app.appRoot)).toMatch(
+ /"tools\/get_weather\.mts": module_\d+/,
);
});
@@ -672,7 +699,7 @@ describe("compileAgent", () => {
startPath: app.appRoot,
});
- expect(result.manifest.tools).toEqual([
+ expect(applicationOwnedEntries(result.manifest, result.manifest.tools)).toMatchObject([
{
description: "Return alias path markers from @/ and @/lib/ imports.",
inputSchema: null,
@@ -691,18 +718,22 @@ describe("compileAgent", () => {
startPath: app.appRoot,
});
- // The disable sentinel reaches the compiled manifest as a name in the
- // dedicated array, not as a tool entry.
- expect([...result.manifest.disabledFrameworkTools].sort()).toEqual([
- "agent",
- "web_fetch",
- "web_search",
- ]);
+ expect(
+ result.manifest.sourceComposition.entries
+ .filter((entry) => entry.kind === "disabled")
+ .map((entry) => entry.source.logicalPath)
+ .sort(),
+ ).toEqual(["tools/agent.ts", "tools/web_fetch.ts", "tools/web_search.ts"]);
// Both the wrapped bash and the replacement todo land in `tools` as
- // ordinary CompiledToolDefinitions. The web_fetch override is intentionally
- // absent — the disable sentinel is partitioned out before this point.
- const toolsByName = new Map(result.manifest.tools.map((tool) => [tool.name, tool]));
+ // ordinary CompiledToolDefinitions. Disabled slots are absent from the
+ // effective tool graph and retained only as composition diagnostics.
+ const toolsByName = new Map(
+ applicationOwnedEntries(result.manifest, result.manifest.tools).map((tool) => [
+ tool.name,
+ tool,
+ ]),
+ );
expect([...toolsByName.keys()].sort()).toEqual(["bash", "todo"]);
@@ -757,7 +788,7 @@ describe("compileAgent", () => {
sourceId: "agent.cjs",
},
});
- expect(result.manifest.schedules).toEqual([
+ expect(result.manifest.schedules).toMatchObject([
{
cron: "0 0 * * *",
hasRun: false,
@@ -818,7 +849,7 @@ describe("compileAgent", () => {
expect(skillMarkdown).toBe("Gather evidence first.");
expect(checklist).toBe("# Checklist\n\n- Find primary sources.\n");
expect(asset).toEqual(Buffer.from([0, 1, 255]));
- expect(result.manifest.skills).toEqual([
+ expect(result.manifest.skills).toMatchObject([
{
description: "Research unfamiliar topics.",
logicalPath: "skills/research.mjs",
@@ -855,7 +886,7 @@ describe("compileAgent", () => {
startPath: appRoot,
});
- expect(result.manifest.tools).toEqual([
+ expect(applicationOwnedEntries(result.manifest, result.manifest.tools)).toMatchObject([
{
description: "Refund a charge.",
inputSchema: null,
@@ -906,7 +937,7 @@ describe("compileAgent", () => {
startPath: appRoot,
});
- expect(result.manifest.schedules).toEqual([
+ expect(result.manifest.schedules).toMatchObject([
{
cron: "0 0 * * 0",
hasRun: false,
@@ -1124,7 +1155,7 @@ describe("compileAgent", () => {
description: "Answer niche follow-up questions remotely.",
logicalPath: "subagents/qux.ts",
name: "qux",
- nodeId: "subagents/qux.ts",
+ nodeId: "subagents/researcher::subagents/qux.ts",
path: "/eve/v1/session",
sourceId: "subagents/qux.ts",
url: "https://qux.example.com",
@@ -1289,15 +1320,13 @@ describe("compileAgent", () => {
nodeId: "subagents/researcher",
sourceId: "subagents/researcher",
});
- expect(normalizedModuleMapText).toContain('import * as module_0 from "../../agent/agent.mjs";');
- expect(normalizedModuleMapText).toContain(
- 'import * as module_1 from "../../agent/subagents/researcher/agent.mjs";',
- );
+ expect(normalizedModuleMapText).toContain('from "../../agent/agent.mjs";');
+ expect(normalizedModuleMapText).toContain('from "../../agent/subagents/researcher/agent.mjs";');
expect(normalizedModuleMapText).toContain(
- 'import * as module_2 from "../../agent/subagents/researcher/sandbox/sandbox.mjs";',
+ 'from "../../agent/subagents/researcher/sandbox/sandbox.mjs";',
);
expect(normalizedModuleMapText).toContain('"subagents/researcher": Object.freeze({');
- expect(normalizedModuleMapText).toContain('"sandbox/sandbox.mjs": module_2');
+ expect(normalizedModuleMapText).toMatch(/"sandbox\/sandbox\.mjs": module_\d+/);
});
it("fails fast on discovery errors after writing inspectable artifacts", async () => {
diff --git a/packages/eve/test/scenarios/compiled-artifacts-bootstrap.scenario.test.ts b/packages/eve/test/scenarios/compiled-artifacts-bootstrap.scenario.test.ts
index 5db98f368..99c278a05 100644
--- a/packages/eve/test/scenarios/compiled-artifacts-bootstrap.scenario.test.ts
+++ b/packages/eve/test/scenarios/compiled-artifacts-bootstrap.scenario.test.ts
@@ -99,10 +99,13 @@ describe("writeCompiledArtifactsFiles", () => {
const instrumentationPluginSource = await readFile(instrumentationPluginPath, "utf8");
expect(instrumentationPluginSource).toContain(
- join(agentRoot, "instrumentation.ts").replaceAll("\\", "/"),
+ generatedArtifacts.bootstrapPath.replaceAll("\\", "/"),
);
expect(instrumentationPluginSource).toContain(
- `import * as instrumentationModule from ${JSON.stringify(join(agentRoot, "instrumentation.ts").replaceAll("\\", "/"))};`,
+ `moduleMap.nodes["__root__"].modules["instrumentation.ts"]`,
+ );
+ expect(instrumentationPluginSource).not.toContain(
+ join(agentRoot, "instrumentation.ts").replaceAll("\\", "/"),
);
expect(instrumentationPluginSource).toContain("registerInstrumentationConfig");
@@ -318,6 +321,9 @@ describe("writeCompiledArtifactsFiles", () => {
const bootstrapSource = await readFile(generatedArtifacts.bootstrapPath, "utf8");
+ expect(compileResult.manifest.skills).toContainEqual(
+ expect.objectContaining({ name: "research", sourceKind: "skill-package" }),
+ );
expect(bootstrapSource).not.toContain("workspaceResources");
expect(bootstrapSource).not.toContain("contentBase64");
expect(bootstrapSource).not.toContain("Always confirm the source of truth.");
diff --git a/packages/eve/test/scenarios/dev-server-apps.scenario.test.ts b/packages/eve/test/scenarios/dev-server-apps.scenario.test.ts
index 66e8b70b5..cfb7d26ac 100644
--- a/packages/eve/test/scenarios/dev-server-apps.scenario.test.ts
+++ b/packages/eve/test/scenarios/dev-server-apps.scenario.test.ts
@@ -108,7 +108,7 @@ function createWorkspaceExtensionToolSource(description: string): string {
}
async function workspaceExtensionToolDescription(serverUrl: string): Promise<string | undefined> {
- return (await fetchAgentInfo(serverUrl)).tools.authored.find(
+ return (await fetchAgentInfo(serverUrl)).tools.static.find(
(tool) => tool.name === "workspace__marker",
)?.description;
}
diff --git a/packages/eve/test/scenarios/dev-server-chaos.scenario.test.ts b/packages/eve/test/scenarios/dev-server-chaos.scenario.test.ts
index 5d3ffc601..7396c9a6b 100644
--- a/packages/eve/test/scenarios/dev-server-chaos.scenario.test.ts
+++ b/packages/eve/test/scenarios/dev-server-chaos.scenario.test.ts
@@ -145,7 +145,7 @@ async function completeStreamedTurn(server: RunningEveDev, message: string): Pro
async function waitForToolMarker(serverUrl: string, marker: string): Promise<void> {
await waitForCondition(async () => {
const info = await fetchAgentInfo(serverUrl);
- return info.tools.authored.some((tool) => tool.description?.includes(marker));
+ return info.tools.static.some((tool) => tool.description?.includes(marker));
}, `Timed out waiting for the "${marker}" tool revision to publish.`);
}
diff --git a/packages/eve/test/scenarios/dev-server-descriptors.ts b/packages/eve/test/scenarios/dev-server-descriptors.ts
index 04fb24451..c600718f0 100644
--- a/packages/eve/test/scenarios/dev-server-descriptors.ts
+++ b/packages/eve/test/scenarios/dev-server-descriptors.ts
@@ -33,42 +33,39 @@ export const TRANSACTIONAL_REBUILD_DESCRIPTOR: ScenarioAppDescriptor = {
...DEV_SERVER_AGENT_DESCRIPTOR,
files: {
...DEV_SERVER_AGENT_DESCRIPTOR.files,
- "agent/channels/dev-generation.ts": createOverlappingChannelSource(),
+ "agent/channels/dev-generation.ts": createTransactionalRouteSource(),
"agent/instrumentation.ts": createInstrumentationSource("one"),
},
};
export function createInstrumentationSource(marker: string): string {
return [
- 'import { randomUUID } from "node:crypto";',
- "",
"declare global {",
" var __EVE_INSTRUMENTATION_MARKER__: string | undefined;",
- " var __EVE_WORKER_ID__: string | undefined;",
"}",
"",
`globalThis.__EVE_INSTRUMENTATION_MARKER__ = ${JSON.stringify(marker)};`,
- "globalThis.__EVE_WORKER_ID__ = randomUUID();",
"export default {};",
"",
].join("\n");
}
-export function createOverlappingChannelSource(): string {
+export function createTransactionalRouteSource(): string {
return createTransactionalChannelSource([
- ' GET("/overlap/:slug", (_request, context) => new Response(`parameter:${context.params.slug}`)),',
+ ' GET("/overlap/parameter/:slug", (_request, context) => new Response(`parameter:${context.params.slug}`)),',
' GET("/overlap/static", () => new Response("static")),',
]);
}
export function createTransactionalChannelSource(routeLines: readonly string[]): string {
return [
+ 'import { threadId } from "node:worker_threads";',
'import { defineChannel, GET } from "eve/channels";',
"",
"export default defineChannel({",
" routes: [",
' GET("/instrumentation-marker", () => new Response(String(globalThis.__EVE_INSTRUMENTATION_MARKER__ ?? "missing"))),',
- ' GET("/worker-id", () => new Response(String(globalThis.__EVE_WORKER_ID__ ?? "missing"))),',
+ ' GET("/worker-id", () => new Response(String(threadId))),',
...routeLines,
" ],",
"});",
diff --git a/packages/eve/test/scenarios/dev-server-rebuild.scenario.test.ts b/packages/eve/test/scenarios/dev-server-rebuild.scenario.test.ts
index 864fab6bf..ee632dea5 100644
--- a/packages/eve/test/scenarios/dev-server-rebuild.scenario.test.ts
+++ b/packages/eve/test/scenarios/dev-server-rebuild.scenario.test.ts
@@ -18,7 +18,7 @@ import {
DEV_SERVER_SCENARIO_TIMEOUT_MS,
TRANSACTIONAL_REBUILD_DESCRIPTOR,
createInstrumentationSource,
- createOverlappingChannelSource,
+ createTransactionalRouteSource,
createTransactionalChannelSource,
} from "./dev-server-descriptors.js";
import {
@@ -49,9 +49,9 @@ describe("eve dev server rebuild transactions", () => {
try {
const initialRevision = await readDevelopmentRevision(server.url);
const initialWorkerId = await fetchText(server.url, "/worker-id");
- expect(
- (await fetchAgentInfo(server.url)).tools.authored.map((tool) => tool.name),
- ).toContain("get_weather");
+ expect((await fetchAgentInfo(server.url)).tools.static.map((tool) => tool.name)).toContain(
+ "get_weather",
+ );
await rm(join(app.appRoot, "agent", "tools", "get_weather.ts"));
await forceDevelopmentRebuild(server.url);
@@ -59,7 +59,7 @@ describe("eve dev server rebuild transactions", () => {
await expect(readDevelopmentRevision(server.url)).resolves.not.toBe(initialRevision);
await expect(fetchText(server.url, "/worker-id")).resolves.toBe(initialWorkerId);
expect(
- (await fetchAgentInfo(server.url)).tools.authored.map((tool) => tool.name),
+ (await fetchAgentInfo(server.url)).tools.static.map((tool) => tool.name),
).not.toContain("get_weather");
expect(hasKnownDevServerFailure(`${server.stdout()}\n${server.stderr()}`)).toBe(false);
} finally {
@@ -70,7 +70,7 @@ describe("eve dev server rebuild transactions", () => {
);
it(
- "replaces the worker for instrumentation changes and preserves Nitro's selected route",
+ "replaces the worker for instrumentation changes and preserves compiled routes",
async () => {
const app = await scenarioApp(TRANSACTIONAL_REBUILD_DESCRIPTOR);
const server = await startEveDev(app.appRoot);
@@ -149,7 +149,7 @@ describe("eve dev server rebuild transactions", () => {
await writeFile(
join(app.appRoot, "agent", "channels", "dev-generation.ts"),
- createOverlappingChannelSource(),
+ createTransactionalRouteSource(),
);
await writeFile(
join(app.appRoot, "agent", "instrumentation.ts"),
diff --git a/packages/eve/test/scenarios/dev-server-workflow-generations.scenario.test.ts b/packages/eve/test/scenarios/dev-server-workflow-generations.scenario.test.ts
index ddb8e51e6..888808c23 100644
--- a/packages/eve/test/scenarios/dev-server-workflow-generations.scenario.test.ts
+++ b/packages/eve/test/scenarios/dev-server-workflow-generations.scenario.test.ts
@@ -132,10 +132,10 @@ describe("eve dev server workflow generations", () => {
`Timed out waiting for the selected-generation retry.\n\nstdout:\n${server.stdout()}\n\nstderr:\n${server.stderr()}`,
);
expect(readCompletedMessages(firstResult.events)).toContain("generation-one");
- // Deliberate contract change from the worker-pinned architecture: the
- // retried turn keeps its generation's authored modules but resumes in
- // the replaced worker, so it observes the current instrumentation.
- expect(readCompletedMessages(firstResult.events)).toContain("instrumentation-two");
+ // Instrumentation is now an ordinary compiled source. Retrying an old
+ // generation therefore restores that generation's instrumentation
+ // together with its tool modules.
+ expect(readCompletedMessages(firstResult.events)).toContain("instrumentation-one");
const secondResult = await sendDevelopmentMessage({
message: "Use get_marker.",
@@ -143,7 +143,9 @@ describe("eve dev server workflow generations", () => {
serverUrl: server.url,
});
expect(readCompletedMessages(secondResult.events)).toContain("generation-two");
- expect(readCompletedMessages(secondResult.events)).toContain("instrumentation-two");
+ // The retained generation's ordinary instrumentation module was the
+ // last instrumentation source evaluated in this worker.
+ expect(readCompletedMessages(secondResult.events)).toContain("instrumentation-one");
} finally {
await server.stop();
}
@@ -234,9 +236,9 @@ describe("eve dev server workflow generations", () => {
await expect(
readFile(recoveredPath, "utf8").then((source) => JSON.parse(source) as unknown),
).resolves.toEqual({
- // The recovered delivery executes in the restarted worker (current
- // instrumentation) with its recorded generation's modules.
- instrumentation: "two",
+ // The recorded generation owns both its tool and instrumentation
+ // sources, even when recovery happens in a freshly started worker.
+ instrumentation: "one",
marker: "generation-one-runtime",
});
} finally {
diff --git a/packages/eve/test/scenarios/eve-init.scenario.test.ts b/packages/eve/test/scenarios/eve-init.scenario.test.ts
index 6e000bc53..fa2cb0809 100644
--- a/packages/eve/test/scenarios/eve-init.scenario.test.ts
+++ b/packages/eve/test/scenarios/eve-init.scenario.test.ts
@@ -92,6 +92,9 @@ async function createFakePnpmEnvironment(scratch: string): Promise<{
const env = {
...withoutCodingAgentMarkers(baseEnv),
EVE_INIT_PNPM_LOG: logPath,
+ GIT_CONFIG_COUNT: "1",
+ GIT_CONFIG_KEY_0: "commit.gpgsign",
+ GIT_CONFIG_VALUE_0: "false",
GIT_AUTHOR_EMAIL: "[email protected]",
GIT_AUTHOR_NAME: "eve Init",
GIT_COMMITTER_EMAIL: "[email protected]",
@@ -138,6 +141,9 @@ async function createFakeNpmEnvironment(scratch: string): Promise<{
const env = {
...withoutCodingAgentMarkers(baseEnv),
EVE_INIT_NPM_LOG: logPath,
+ GIT_CONFIG_COUNT: "1",
+ GIT_CONFIG_KEY_0: "commit.gpgsign",
+ GIT_CONFIG_VALUE_0: "false",
GIT_AUTHOR_EMAIL: "[email protected]",
GIT_AUTHOR_NAME: "eve Init",
GIT_COMMITTER_EMAIL: "[email protected]",
diff --git a/packages/eve/test/scenarios/load-agent-info-data.scenario.test.ts b/packages/eve/test/scenarios/load-agent-info-data.scenario.test.ts
index 72add9295..57ce0f02e 100644
--- a/packages/eve/test/scenarios/load-agent-info-data.scenario.test.ts
+++ b/packages/eve/test/scenarios/load-agent-info-data.scenario.test.ts
@@ -6,7 +6,7 @@ import { describe, expect, it } from "vitest";
import { resolveCompilerArtifactPaths } from "../../src/compiler/artifacts.js";
import { compileAgent } from "../../src/compiler/compile-agent.js";
import {
- loadAgentInfoData,
+ loadAgentInfoManifestData,
resolveAgentInfoCompiledArtifactsSource,
} from "../../src/internal/nitro/routes/agent-info/load-agent-info-data.js";
import { createDiskRuntimeCompiledArtifactsSource } from "../../src/runtime/compiled-artifacts-source.js";
@@ -67,14 +67,12 @@ describe("loadAgentInfoData", () => {
kind: "production",
});
expect(agentInfoCompiledArtifactsSource.kind).toBe("bundled");
- const data = await loadAgentInfoData({
+ const data = await loadAgentInfoManifestData({
compiledArtifactsSource: agentInfoCompiledArtifactsSource,
});
- expect(data.agent.config?.name).toBe(data.manifest.config.name);
expect(data.manifest.config.name).toBe(manifest.config.name);
- expect(data.agent.sandbox).not.toBeNull();
- expect(data.agent.sandbox?.sourceKind).toBe("module");
+ expect(data.manifest.sandbox.sourceKind).toBe("module");
expect(data.schedules).toEqual([]);
});
});
diff --git a/packages/eve/test/scenarios/mounted-extension-directory-override.scenario.test.ts b/packages/eve/test/scenarios/mounted-extension-directory-override.scenario.test.ts
index c84df5843..c2a5ffb20 100644
--- a/packages/eve/test/scenarios/mounted-extension-directory-override.scenario.test.ts
+++ b/packages/eve/test/scenarios/mounted-extension-directory-override.scenario.test.ts
@@ -153,4 +153,87 @@ describe("mounted extension via directory form with override", () => {
);
expect(pulse).toBeUndefined();
});
+
+ it("replaces extension local and remote subagents with remote overrides", async () => {
+ const app = await scenarioApp({
+ name: "mounted-extension-subagent-override-repro",
+ installDependencies: true,
+ files: {
+ "agent/agent.mjs": 'export default { model: "openai/gpt-5.4" };\n',
+ "agent/instructions.md": "You are a precise assistant.\n",
+ "agent/extensions/crm/extension.mjs": [
+ 'import crm from "@acme/crm";',
+ "export default crm({});",
+ "",
+ ].join("\n"),
+ "agent/extensions/crm/subagents/weather.mjs": [
+ 'import { defineRemoteAgent } from "eve";',
+ "export default defineRemoteAgent({",
+ ' description: "Use the remote weather agent.",',
+ ' url: "https://weather.example.com",',
+ "});",
+ "",
+ ].join("\n"),
+ "agent/extensions/crm/subagents/alerts.mjs": [
+ 'import { defineRemoteAgent } from "eve";',
+ "export default defineRemoteAgent({",
+ ' description: "Use the consumer alerts agent.",',
+ ' url: "https://consumer-alerts.example.com",',
+ "});",
+ "",
+ ].join("\n"),
+ "node_modules/@acme/crm/package.json": `${JSON.stringify({
+ name: "@acme/crm",
+ type: "module",
+ eve: { extension: { source: "source", dist: "extension" } },
+ exports: { ".": "./extension/extension.mjs" },
+ })}\n`,
+ "node_modules/@acme/crm/extension/_manifest.json": JSON.stringify({
+ kind: "eve-extension",
+ formatVersion: 1,
+ builtWithEve: "0.0.0-test",
+ requires: { extension: 1, subagent: 2 },
+ }),
+ "node_modules/@acme/crm/extension/extension.mjs": [
+ 'import { defineExtension } from "eve/extension";',
+ "export default defineExtension({});",
+ "",
+ ].join("\n"),
+ "node_modules/@acme/crm/extension/subagents/weather/agent.mjs": [
+ "export default {",
+ ' model: "openai/gpt-5.4",',
+ ' description: "Use the local weather agent.",',
+ "};",
+ "",
+ ].join("\n"),
+ "node_modules/@acme/crm/extension/subagents/alerts.mjs": [
+ 'import { defineRemoteAgent } from "eve";',
+ "export default defineRemoteAgent({",
+ ' description: "Use the extension alerts agent.",',
+ ' url: "https://extension-alerts.example.com",',
+ "});",
+ "",
+ ].join("\n"),
+ },
+ });
+
+ await compileAgent({ startPath: app.appRoot });
+ const manifest = await loadCompiledManifest({
+ compiledArtifactsSource: createDiskRuntimeCompiledArtifactsSource(app.appRoot),
+ });
+
+ expect(manifest.subagents).toHaveLength(0);
+ expect(manifest.remoteAgents).toMatchObject([
+ {
+ name: "crm__alerts",
+ owner: { kind: "application" },
+ url: "https://consumer-alerts.example.com",
+ },
+ {
+ name: "crm__weather",
+ owner: { kind: "application" },
+ url: "https://weather.example.com",
+ },
+ ]);
+ });
});
diff --git a/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts b/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts
index 404efd6f3..7faae7da4 100644
--- a/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts
+++ b/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts
@@ -249,7 +249,7 @@ describe("mounted extension installed under node_modules", () => {
);
expect(
JSON.parse(extensionFiles[`node_modules/${PACKAGE_NAME}/dist/extension/_manifest.json`]!),
- ).toMatchObject({ requires: { channel: 8, schedule: 3, subagent: 2 } });
+ ).toMatchObject({ requires: { channel: 9, schedule: 3, subagent: 2 } });
const app = await scenarioApp({
name: "mounted-extension-installed",
installDependencies: true,
diff --git a/packages/eve/test/scenarios/remote-agent-principal-forwarding.scenario.test.ts b/packages/eve/test/scenarios/remote-agent-principal-forwarding.scenario.test.ts
index 0a0cbea75..c6abaa4ce 100644
--- a/packages/eve/test/scenarios/remote-agent-principal-forwarding.scenario.test.ts
+++ b/packages/eve/test/scenarios/remote-agent-principal-forwarding.scenario.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
import type { SessionAuthContext } from "../../src/channel/types.js";
import { startRemoteAgentSession } from "../../src/execution/remote-agent-dispatch.js";
-import type { RuntimeRemoteAgentCallActionRequest } from "../../src/runtime/actions/types.js";
+import type { RuntimeRemoteAgentCallActionRequest } from "../../src/shared/action-types.js";
import type { ResolvedRuntimeRemoteAgentNode } from "../../src/runtime/types.js";
import {
type ScenarioAppDescriptor,
diff --git a/packages/eve/test/scenarios/runtime-loaders.scenario.test.ts b/packages/eve/test/scenarios/runtime-loaders.scenario.test.ts
index 363e54abe..20569cc50 100644
--- a/packages/eve/test/scenarios/runtime-loaders.scenario.test.ts
+++ b/packages/eve/test/scenarios/runtime-loaders.scenario.test.ts
@@ -345,8 +345,10 @@ describe("runtime compiled artifact loaders", () => {
compiledArtifactsSource,
}),
]);
- const [compiledChannel] = manifest.channels;
- const [resolvedChannel] = resolvedAgent.channels;
+ const compiledChannel = manifest.channelRoutes.effective.find(
+ (channel) => channel.name === "slack",
+ );
+ const resolvedChannel = resolvedAgent.channels.find((channel) => channel.name === "slack");
expect(manifest.config).toEqual({
compaction: {},
@@ -412,14 +414,19 @@ describe("runtime compiled artifact loaders", () => {
expect(resolvedChannel.method).toBe("POST");
expect(resolvedChannel.urlPath).toBe("/slack");
expect(typeof resolvedChannel.fetch).toBe("function");
- expect(resolvedAgent.channels).toHaveLength(1);
- // Authored instructions modules execute once at build time. They never appear in
- // the runtime module map.
- expect(Object.keys(moduleMap.nodes[ROOT_COMPILED_AGENT_NODE_ID]?.modules ?? {})).toEqual([
+ expect(resolvedAgent.channels.filter((channel) => channel.name === "slack")).toHaveLength(1);
+ // The canonical module map retains every source node that participates in
+ // compilation while excluding implementation-only imports such as `lib/`.
+ const rootModuleIds = Object.keys(moduleMap.nodes[ROOT_COMPILED_AGENT_NODE_ID]?.modules ?? {});
+ expect(rootModuleIds.filter((moduleId) => !moduleId.startsWith("eve:"))).toEqual([
"agent.mjs",
"channels/slack.mjs",
+ "instructions.mjs",
+ "schedules/daily-digest.mjs",
+ "skills/route-weather.mjs",
"tools/get_weather.mjs",
]);
+ expect(rootModuleIds.some((moduleId) => moduleId.startsWith("eve:"))).toBe(true);
expect(
(
moduleMap.nodes[ROOT_COMPILED_AGENT_NODE_ID]!.modules["tools/get_weather.mjs"] as {
@@ -428,15 +435,19 @@ describe("runtime compiled artifact loaders", () => {
).default.description,
).toBe("Get the weather.");
await expect(
- resolvedAgent.tools[0]?.execute?.(
- { city: "Brooklyn" },
- { messages: [], toolCallId: "call_1" },
- ),
+ resolvedAgent.tools
+ .find((tool) => tool.name === "get_weather")
+ ?.execute?.({ city: "Brooklyn" }, { messages: [], toolCallId: "call_1" }),
).resolves.toEqual({
city: "Brooklyn",
source: "lib",
});
- expect(resolvedAgent.instructions).toEqual(manifest.instructions);
+ expect(resolvedAgent.instructions).toEqual(
+ manifest.instructions.map((instruction) => ({
+ ...instruction,
+ owner: { kind: "application" },
+ })),
+ );
expect(resolvedAgent.workspaceSpec).toEqual({
rootEntries: [],
});
@@ -501,7 +512,12 @@ describe("runtime compiled artifact loaders", () => {
}
).default.description,
);
- expect(resolvedAgent.instructions).toEqual(manifest.instructions);
+ expect(resolvedAgent.instructions).toEqual(
+ manifest.instructions.map((instruction) => ({
+ ...instruction,
+ owner: { kind: "application" },
+ })),
+ );
});
});
@@ -531,15 +547,16 @@ describe("runtime compiled artifact loaders", () => {
ROOT_COMPILED_AGENT_NODE_ID,
"subagents/researcher",
]);
- expect(Object.keys(moduleMap.nodes["subagents/researcher"]?.modules ?? {})).toEqual([
- "agent.mjs",
- "sandbox/sandbox.mjs",
- "tools/search.mjs",
- ]);
+ const researcherModuleIds = Object.keys(moduleMap.nodes["subagents/researcher"]?.modules ?? {});
+ expect(researcherModuleIds.filter((moduleId) => !moduleId.startsWith("eve:defaults:"))).toEqual(
+ ["agent.mjs", "sandbox/sandbox.mjs", "tools/search.mjs"],
+ );
+ expect(researcherModuleIds.some((moduleId) => moduleId.startsWith("eve:defaults:"))).toBe(true);
expect(researcherNode?.agent.instructions).toEqual([
{
content: "Investigate research tasks thoroughly.",
name: "instructions",
+ owner: { kind: "application" },
logicalPath: "instructions.md",
role: "system",
sourceId: "instructions.md",
@@ -560,10 +577,9 @@ describe("runtime compiled artifact loaders", () => {
),
).toBe(false);
await expect(
- researcherNode?.agent.tools[0]?.execute?.(
- { query: "climate" },
- { messages: [], toolCallId: "call_1" },
- ),
+ researcherNode?.agent.tools
+ .find((tool) => tool.name === "search")
+ ?.execute?.({ query: "climate" }, { messages: [], toolCallId: "call_1" }),
).resolves.toEqual({
query: "climate",
source: "subagent-lib",
@@ -618,7 +634,7 @@ describe("runtime compiled artifact loaders", () => {
const firstResolved = await loadResolvedCompiledAgent({
compiledArtifactsSource,
});
- const firstTool = firstResolved.tools[0];
+ const firstTool = firstResolved.tools.find((tool) => tool.name === "get_weather");
if (firstTool === undefined) {
throw new Error("Expected one compiled tool before the source update.");
@@ -646,7 +662,7 @@ describe("runtime compiled artifact loaders", () => {
const secondResolved = await loadResolvedCompiledAgent({
compiledArtifactsSource,
});
- const secondTool = secondResolved.tools[0];
+ const secondTool = secondResolved.tools.find((tool) => tool.name === "get_weather");
if (secondTool === undefined) {
throw new Error("Expected one compiled tool after the source update.");
diff --git a/packages/eve/test/scenarios/verify-oidc.scenario.test.ts b/packages/eve/test/scenarios/verify-oidc.scenario.test.ts
index 8d6627079..c33c3ff07 100644
--- a/packages/eve/test/scenarios/verify-oidc.scenario.test.ts
+++ b/packages/eve/test/scenarios/verify-oidc.scenario.test.ts
@@ -3,7 +3,7 @@ import { createServer } from "node:http";
import { exportJWK, generateKeyPair, SignJWT } from "jose";
import { describe, expect, it } from "vitest";
-import { authenticateOidcStrategy } from "../../src/runtime/governance/auth/oidc.js";
+import { authenticateOidcStrategy } from "../../src/channel/auth/oidc.js";
/**
* Scenario-tier coverage for the OIDC verifier's runtime-principal branch.
diff --git a/packages/eve/test/tool-defaults.test.ts b/packages/eve/test/tool-defaults.test.ts
deleted file mode 100644
index 132e3f7da..000000000
--- a/packages/eve/test/tool-defaults.test.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import {
- bash,
- glob,
- grep,
- loadSkill,
- readFile,
- todo,
- webFetch,
- writeFile,
-} from "../src/public/tools/defaults.js";
-
-/**
- * Smoke tests for the `eve/tools/defaults` barrel exports.
- *
- * These verify that every re-exported default carries its expected shape
- * so wiring breakage in the barrel re-export chain surfaces immediately.
- */
-describe("tool defaults barrel exports", () => {
- it("bash has description and execute", () => {
- expect(bash.description).toBeTypeOf("string");
- expect(bash.execute).toBeTypeOf("function");
- });
-
- it("glob has description, execute, and inputSchema", () => {
- expect(glob.description).toBeTypeOf("string");
- expect(glob.execute).toBeTypeOf("function");
- expect(glob.inputSchema).toBeDefined();
- });
-
- it("grep has description, execute, and inputSchema", () => {
- expect(grep.description).toBeTypeOf("string");
- expect(grep.execute).toBeTypeOf("function");
- expect(grep.inputSchema).toBeDefined();
- });
-
- it("readFile has description, execute, and inputSchema", () => {
- expect(readFile.description).toBeTypeOf("string");
- expect(readFile.execute).toBeTypeOf("function");
- expect(readFile.inputSchema).toBeDefined();
- });
-
- it("writeFile has description and execute", () => {
- expect(writeFile.description).toBeTypeOf("string");
- expect(writeFile.execute).toBeTypeOf("function");
- });
-
- it("todo has description and execute", () => {
- expect(todo.description).toBeTypeOf("string");
- expect(todo.execute).toBeTypeOf("function");
- });
-
- it("webFetch has description and execute", () => {
- expect(webFetch.description).toBeTypeOf("string");
- expect(webFetch.execute).toBeTypeOf("function");
- });
-
- it("loadSkill has description and execute", () => {
- expect(loadSkill.description).toBeTypeOf("string");
- expect(loadSkill.execute).toBeTypeOf("function");
- });
-});
diff --git a/packages/eve/test/tui-client/lib/server.ts b/packages/eve/test/tui-client/lib/server.ts
index 292d22742..fa3807b01 100644
--- a/packages/eve/test/tui-client/lib/server.ts
+++ b/packages/eve/test/tui-client/lib/server.ts
@@ -250,7 +250,7 @@ async function waitForAgentServer(input: {
/** Reads the agent name from a versioned `/eve/v1/info` response. */
export function getAgentNameFromInfoPayload(payload: unknown): string | undefined {
- if (!isRecord(payload) || payload.kind !== "eve-agent-info" || payload.version !== 2) {
+ if (!isRecord(payload) || payload.kind !== "eve-agent-info" || payload.version !== 3) {
return undefined;
}
diff --git a/packages/eve/test/vercel/vercel-verbose-bundling.vercel.test.ts b/packages/eve/test/vercel/vercel-verbose-bundling.vercel.test.ts
index feeaa1f1b..b3c884e72 100644
--- a/packages/eve/test/vercel/vercel-verbose-bundling.vercel.test.ts
+++ b/packages/eve/test/vercel/vercel-verbose-bundling.vercel.test.ts
@@ -1,7 +1,7 @@
import { afterAll, beforeAll, describe, it } from "vitest";
import { VERBOSE_BUNDLING_DESCRIPTOR } from "../../src/internal/testing/scenario-apps/verbose-bundling.js";
import type { MessageStreamEvent } from "../../src/protocol/message.js";
-import type { RuntimeToolResultActionResult } from "../../src/runtime/actions/types.js";
+import type { RuntimeToolResultActionResult } from "../../src/shared/action-types.js";
import { sendDevelopmentMessage } from "../dev-client-harness/send-message.js";
import { createDevelopmentSessionState } from "../dev-client-harness/session.js";
import {
diff --git a/packages/eve/test/write-file-tool.test.ts b/packages/eve/test/write-file-tool.test.ts
index d818957bb..0e0968b6d 100644
--- a/packages/eve/test/write-file-tool.test.ts
+++ b/packages/eve/test/write-file-tool.test.ts
@@ -9,10 +9,7 @@ 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 {
- createReadFileStamp,
- ReadFileStateKey,
-} from "../src/runtime/framework-tools/file-state.js";
+import { createReadFileStamp, ReadFileStateKey } from "../src/execution/tools/file-state.js";
const HOME_PROBE_COMMAND = `printf '%s\\n' "$HOME"`;
diff --git a/research/programmatic-agent-sources.md b/research/programmatic-agent-sources.md
index 613ee77f4..eef8d9352 100644
--- a/research/programmatic-agent-sources.md
+++ b/research/programmatic-agent-sources.md
@@ -1046,7 +1046,9 @@ Dispatch becomes declared effects, and the seam is deleted:
1. effect declarations and visibility conditions consumed by the kernel;
2. the exhaustive effect-kind lifecycle, with approvals riding
`request-input`;
-3. deletion of the complete magic-string dispatch layer listed in the
+3. replacement of `localSubagentExecutors` function-identity classification
+ with prepared `dispatch` effect state;
+4. deletion of the complete magic-string dispatch layer listed in the
deletion ledger's kernel row.
`COMPILED_AGENT_MANIFEST_VERSION` moves from 42 to 43 with the serialized
diff --git a/scripts/guard-invariants-baseline.json b/scripts/guard-invariants-baseline.json
index ae82b7a89..7ce44b66d 100644
--- a/scripts/guard-invariants-baseline.json
+++ b/scripts/guard-invariants-baseline.json
@@ -36,11 +36,9 @@
"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/public/tools/internal.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/framework-tools/connection-search-dynamic.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,