The Open Framework for Building Agents
feat(eve): connections - add defineDynamic support (#2738)
Andrew Barbaa0c33dc76dba
diff --git a/.changeset/dynamic-connections.md b/.changeset/dynamic-connections.mdnew file mode 100644index 000000000..7d6780ae6--- /dev/null+++ b/.changeset/dynamic-connections.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Allow `connections/` modules to use `defineDynamic` for caller-specific MCP and OpenAPI connection sets resolved at session or turn boundaries. Dynamic connections participate in ordinary discovery, auth, approval, and qualified tool calls, fail closed on resolver errors, and pin durable authorization to a stable resolved instance.diff --git a/docs/connections/overview.mdx b/docs/connections/overview.mdxindex be6924872..6ebabe0a4 100644--- a/docs/connections/overview.mdx+++ b/docs/connections/overview.mdx@@ -6,7 +6,7 @@ url: /connectionsA connection wires an agent into an external server you don't author, either an MCP server (Linear, GitHub, a warehouse) or any HTTP API with an OpenAPI document. eve handles the parts you'd otherwise hand-roll, discovering the remote tools, surfacing them to the model, and brokering auth. To instead let eve communicate with users through an external service, use a [channel](/docs/channels/overview).-Connections live under `agent/connections/`. The runtime name comes from the filename, so `agent/connections/linear.ts` registers as `"linear"`. The model never sees a connection's URL or credentials. It discovers tools through the built-in `connection_search` and calls them by their qualified name, `<connection>__<tool>` (e.g. `linear__list_issues`).+Connections live under `agent/connections/`. A static connection's runtime name comes from the filename, so `agent/connections/linear.ts` registers as `"linear"`. A dynamic connection file can instead resolve a caller-specific connection set at session or turn boundaries. The model never sees a connection's URL or credentials. It discovers tools through the built-in `connection_search` and calls them by their qualified name, `<connection>__<tool>` (e.g. `linear__list_issues`).## MCP connections@@ -20,6 +20,44 @@ Use an OpenAPI connection when the service exposes an OpenAPI 3.x document. eveRead [OpenAPI connections](/docs/connections/openapi) for `defineOpenAPIConnection`, `baseUrl`, and operation filters.+## Dynamic connections++Use `defineDynamic` when the connection set depends on the authenticated user,+tenant, or another runtime lookup. Import it with the connection factories from+`eve/connections`, then return one connection definition, a map of definitions,+or `null` from `session.started` or `turn.started`.++```ts title="agent/connections/accounts.ts"+import { defineDynamic, defineMcpClientConnection } from "eve/connections";+import { listAccounts } from "../lib/accounts";++export default defineDynamic({+ events: {+ "session.started": async (_event, ctx) => {+ const accounts = await listAccounts(ctx.session.auth.current);+ return Object.fromEntries(+ accounts.map((account) => [+ account.slug,+ defineMcpClientConnection({+ url: account.mcpUrl,+ description: account.description,+ instanceKey: account.id,+ auth: account.auth,+ }),+ ]),+ );+ },+ },+});+```++For a single returned definition, the filename supplies the connection name.+For a map, each bare map key becomes a connection name. Every entry must use+`defineMcpClientConnection` or `defineOpenAPIConnection`. Authenticated entries+must also set `instanceKey` to a stable, non-secret account or tenant identifier.+See [Dynamic capabilities](/docs/guides/dynamic-capabilities#dynamic-connections)+for event scope, naming, conflicts, and durable recovery behavior.+## Static-token auth`getToken` returns a `TokenResult` (`{ token, expiresAt? }`), and eve sends it as `Authorization: Bearer <token>` on every request. Because it runs on each connection attempt, you can mint a fresh token from wherever you keep secrets, including an env var, a secrets manager, an internal vault, or your own OAuth exchange:@@ -245,7 +283,13 @@ export default defineMcpClientConnection({Drop `resume` when the provider keeps flow state server-side, so nothing has to cross the step boundary.-`displayName` is presentation-only. The connection's path-derived name still keys the authorization flow, token cache, and callback URL. You can also set `displayName` on the `auth` definition itself (e.g. `auth: { ...connect("salesforce/myagent"), displayName: "Salesforce" }`); that definition-level value wins over one the strategy stamps on the challenge, and channels fall back to title-casing the connection name when neither is set.+`displayName` is presentation-only. The connection's resolved name still keys+the callback URL, while eve scopes token caching and authorization completion+to the opaque resolved instance identity. You can also set `displayName` on the+`auth` definition itself (e.g.+`auth: { ...connect("salesforce/myagent"), displayName: "Salesforce" }`); that+definition-level value wins over one the strategy stamps on the challenge, and+channels fall back to title-casing the connection name when neither is set.### Signaling authorization statediff --git a/docs/extensions.md b/docs/extensions.mdindex dfef7c248..bc602cd89 100644--- a/docs/extensions.md+++ b/docs/extensions.md@@ -39,7 +39,7 @@ An extension uses the same file conventions as an agent for its contributions:lib/http.ts```-Each listed slot accepts the same authored forms as its agent counterpart. Static and dynamic tools, skills, and instructions all work in an extension: `extension/instructions.ts` is as valid as `extension/instructions.md`, and `extension/tools/` can contain `defineDynamic(...)`.+Each listed slot accepts the same authored forms as its agent counterpart. Static and dynamic tools, connections, skills, and instructions all work in an extension: `extension/instructions.ts` is as valid as `extension/instructions.md`, and `extension/connections/` can contain `defineDynamic(...)`.Names come from paths, so call the tool `search`, not `crm_search`; the consumer's mount adds the `crm__` prefix. The same prefix applies to channel, schedule, and parent-visible subagent IDs, while channel route paths and schedule cron expressions stay unchanged. Keep shared code in `extension/lib/`.@@ -342,7 +342,7 @@ At build time, eve checks the extension's generated capability metadata. If the- [Integrations](/integrations): browse ready-to-install extensions using the Extensions filter- [Tools](/docs/tools): static tools, approval, and tool output-- [Dynamic capabilities](/docs/guides/dynamic-capabilities): dynamic tools, skills, and instructions+- [Dynamic capabilities](/docs/guides/dynamic-capabilities): dynamic connections, tools, skills, and instructions- [Instructions](/docs/instructions): static and TypeScript instructions- [Skills](/docs/skills): package procedures and supporting files- [Connections](/docs/connections): integrate external servicesdiff --git a/docs/getting-started.mdx b/docs/getting-started.mdxindex a6ea168d9..34d3717d1 100644--- a/docs/getting-started.mdx+++ b/docs/getting-started.mdx@@ -106,7 +106,7 @@ Each path under `agent/` has a specific purpose. Root agents can use every path| `instructions.md` / `instructions.ts` / `instructions/` | Base system prompt | Optional | A flat file or directory of `.md` and `.ts` files. Static sources compose at build time. Dynamic sources resolve at runtime. Required on the root, optional on subagents. || `instrumentation.ts` | Telemetry config | No | OTel exporter and AI SDK span settings, auto-discovered and run before agent code. Root-only. || `channels/` | HTTP and messaging entry points | No | Root-only. |-| `connections/` | External MCP and OpenAPI services | Yes | One connection per file; its name comes from the filename. |+| `connections/` | External MCP and OpenAPI services | Yes | Static files define one path-named connection. Dynamic files can resolve a caller-specific connection set at runtime. || `hooks/` | Lifecycle and stream-event subscribers | Yes | Module-backed only. Recursive directories are supported. || `skills/` | On-demand procedures and capability packs | Yes | Flat markdown, module-backed skills, or packaged skills. Runtime files are seeded under `$HOME/.agents/skills/`, with `/workspace/skills/` as a fallback. || `lib/` | Shared authored helper code | Yes | Import-only; not mounted into the workspace. |diff --git a/docs/guides/dynamic-capabilities.md b/docs/guides/dynamic-capabilities.mdindex b030aefa4..8c601b3c0 100644--- a/docs/guides/dynamic-capabilities.md+++ b/docs/guides/dynamic-capabilities.md@@ -1,9 +1,9 @@---title: "Dynamic Capabilities"-description: "Resolve models, subagents, tools, skills, and instructions at runtime with defineDynamic resolver events."+description: "Resolve models, subagents, connections, tools, skills, and instructions at runtime with defineDynamic resolver events."----`defineDynamic` resolves the model, subagents, tools, skills, and instructions at runtime from a session event instead of declaring them up front. Reach for it when the right capability isn't known until the session starts, because it hinges on who the caller is, what tenant they belong to, feature flags, or external data. The [subagents](../subagents), [tools](../tools), [skills](../skills), and [instructions](../instructions) guides each point here for their dynamic form.+`defineDynamic` resolves the model, subagents, connections, tools, skills, and instructions at runtime from a session event instead of declaring them up front. Reach for it when the right capability isn't known until the session starts, because it hinges on who the caller is, what tenant they belong to, feature flags, or external data. The [subagents](../subagents), [connections](../connections), [tools](../tools), [skills](../skills), and [instructions](../instructions) guides each point here for their dynamic form.eve evaluates a dynamic definition module once during compilation to classify and validate it, then retains that module as a runtime entry so its event handlers can run. Its top-level code therefore runs in both phases; keep caller-specific work inside the handlers. See [Authored module lifecycle](../reference/typescript-api#authored-module-lifecycle).@@ -20,8 +20,8 @@ full contract.Dynamic models do not compile a default model or model metadata. When aresolver first selects a model, eve normalizes the selection and resolves any-omitted context-window metadata from the AI Gateway catalog. Dynamic tools,-skills, instructions, and subagents may return `null` to omit a capability.+omitted context-window metadata from the AI Gateway catalog. Dynamic connections,+tools, skills, instructions, and subagents may return `null` to omit a capability.### Route image inputs to a vision model@@ -132,6 +132,91 @@ availability as capability composition, not as the only authorizationboundary: sensitive child tools still need their own authorization andapproval checks.+## Dynamic connections++Use a dynamic connection when the available MCP servers or OpenAPI services+depend on the authenticated caller. A handler returns one+`defineMcpClientConnection(...)` or `defineOpenAPIConnection(...)`, a map of+connection definitions, or `null`. Wrap every returned connection in its+protocol helper. Connection resolvers receive `ctx.session` and+`ctx.channel.kind`; they do not receive conversation messages, delivery+payloads, tool inputs, model outputs, continuation tokens, or free-form channel+metadata. Select accounts and endpoints from authenticated session identity or+application-owned data.++This example exposes one MCP connection for each cloud account enabled for the+current user:++```ts title="agent/connections/accounts.ts"+import { defineDynamic, defineMcpClientConnection } from "eve/connections";+import { listEnabledAccounts, mintAccountToken } from "../lib/accounts";++export default defineDynamic({+ events: {+ "session.started": async (_event, ctx) => {+ const principal = ctx.session.auth.current;+ if (principal?.principalType !== "user") return null;++ const accounts = await listEnabledAccounts(principal);+ return Object.fromEntries(+ accounts.map((account) => [+ account.slug,+ defineMcpClientConnection({+ url: "https://mcp.cloud.example.com",+ description: `${account.label} (${account.accountId})`,+ instanceKey: account.accountId,+ auth: {+ principalType: "user",+ getToken: ({ principal }) => mintAccountToken(principal, account),+ },+ }),+ ]),+ );+ },+ },+});+```++The returned definitions use the same auth, headers, filtering, provided+arguments, and approval options as static [MCP](../connections/mcp) and+[OpenAPI](../connections/openapi) connections. Each resolved connection joins+the per-step connection registry, appears in `connection_search`, and exposes+discovered tools as `<connection>__<tool>`.++Set `instanceKey` on every authenticated dynamic connection. Use a stable,+non-secret account or tenant identifier, and change it whenever the endpoint,+account, or auth provider changes. eve hashes the value before storing the+resolved instance identity in durable authorization state. If a parked sign-in+callback resumes after the resolver selects a different instance, eve rejects+the callback instead of passing it to the new connection or reusing its token.++### Naming and conflicts++| Return shape | File | Connection name(s) |+| ----------------------------- | ------------------------------- | ----------------------- |+| single connection definition | `agent/connections/accounts.ts` | `accounts` |+| map `{ production, staging }` | `agent/connections/accounts.ts` | `production`, `staging` |++A map key must be a legal connection name: lowercase ASCII letters, digits,+and dashes, starting with a letter, up to 64 characters. Map keys are bare;+eve does not prefix them with the file slug. A dynamic connection overrides a+same-named static connection. Two effective dynamic resolvers cannot emit the+same name; namespace one map key to remove the ambiguity.++### Events and recovery++Dynamic connections support `session.started` and `turn.started`. A turn result+replaces that file's session result for the turn, including when the turn+handler returns `null`. A throwing or invalid handler fails the lifecycle+without rebuilding the registry, so a static connection shadowed by the+dynamic result cannot reappear as a fallback.++eve may run the active session and turn handlers again when a parked turn+resumes or a durable step retries. This rebuilds live auth, header, approval,+and provided-argument callbacks without serializing them into workflow state.+Keep connection resolvers idempotent, and keep external side effects outside+the handler.+## Dynamic toolsPass `defineDynamic` an `events` object whose handlers return either a single `defineTool(...)`, a `Record<string, defineTool(...)>`, or `null` for no tools. Wrap every entry in `defineTool()`. eve records durable descriptors for `execute`, approval request and response policies, and `toModelOutput`, so a parked call can reconstruct the same callbacks in a fresh process.@@ -189,7 +274,7 @@ A single return produces one tool named after the file slug, identical to a stat### Conflicts-A dynamic tool or skill whose name matches an **authored** one **overrides** it — a per-caller resolver can replace a built-in by name. Two **dynamic** resolvers emitting the same name is a genuine ambiguity and throws; namespace one of the keys manually to resolve it.+A dynamic connection, tool, or skill whose name matches an **authored** one **overrides** it — a per-caller resolver can replace a static capability by name. Two **dynamic** resolvers of the same capability type emitting the same name is a genuine ambiguity and throws; namespace one of the keys manually to resolve it.### Events@@ -310,6 +395,7 @@ Dynamic system content that changes frequently can reduce provider prompt-cache## What to read next- Conditionally expose a specialist → [Subagents](../subagents)+- Resolve caller-specific external services → [Connections](../connections)- The static tool basics this builds on → [Tools](../tools)- The built-in tools and how to override them → [Built-in tools](../concepts/built-in-tools)- Authenticate a tool or connection to an external service → [Auth & route protection](./auth-and-route-protection)diff --git a/docs/reference/typescript-api.md b/docs/reference/typescript-api.mdindex 01291a226..dd84b6870 100644--- a/docs/reference/typescript-api.md+++ b/docs/reference/typescript-api.md@@ -30,28 +30,28 @@ export default defineTool({## The define\* helpers-| Helper | Import from | Authored at | Guide |-| ----------------------------------------------------- | ---------------------------------------------------- | -------------------------------------------------------------------------- | ------------------------------------------------------ |-| `defineAgent` | `eve` | `agent/agent.ts` | [agent.ts](../agent-config) |-| `defineTool` | `eve/tools` | `agent/tools/<name>.ts` | [Tools](../tools) |-| `defineDynamic` | `eve`, `eve/tools`, `eve/skills`, `eve/instructions` | dynamic model or subagent `agent.ts`; `agent/{tools,skills,instructions}/` | [Dynamic capabilities](../guides/dynamic-capabilities) |-| `defineMcpClientConnection` | `eve/connections` | `agent/connections/<name>.ts` | [MCP connections](../connections/mcp) |-| `defineOpenAPIConnection` | `eve/connections` | `agent/connections/<name>.ts` | [OpenAPI connections](../connections/openapi) |-| `defineChannel` | `eve/channels` | `agent/channels/<name>.ts` | [Custom channels](../channels/custom) |-| `eveChannel`, `slackChannel`, and the other platforms | `eve/channels/<platform>` | `agent/channels/<platform>.ts` | [Channels](../channels/overview) |-| `defineSkill` | `eve/skills` | `agent/skills/<name>.ts` | [Skills](../skills) |-| `defineInstructions` | `eve/instructions` | `agent/instructions.ts` | [Instructions](../instructions) |-| `defineMemory`, `defineMemoryProvider` | `eve/memory` | `agent/memory.ts` or `agent/memory/<slot>.ts` | [Memory](../memory) |-| `defineHook` | `eve/hooks` | `agent/hooks/<slug>.ts` | [Hooks](../guides/hooks) |-| `defineSchedule` | `eve/schedules` | `agent/schedules/<name>.ts` | [Schedules](../schedules) |-| `defineState` | `eve/context` | tools, hooks, lifecycle | [Session context](../guides/session-context) |-| `defineSandbox` | `eve/sandbox` | `agent/sandbox.ts` | [Sandbox](../sandbox) |-| `defineInstrumentation` | `eve/instrumentation` | `agent/instrumentation.ts` | [instrumentation.ts](../guides/instrumentation) |-| `defineRemoteAgent` | `eve` | `agent/subagents/<id>/agent.ts` | [Remote agents](../guides/remote-agents) |-| `defineEval` | `eve/evals` | `evals/*.eval.ts` | [Evals](../evals/overview) |-| `defineEvalConfig` | `eve/evals` | `evals/evals.config.ts` | [Evals](../evals/overview) |-| `mockModel` | `eve/evals` | Deterministic fixture agent models | [Evals](../evals/overview) |-| `useEveAgent` | `eve/react`, `eve/vue`, `eve/svelte` | frontend | [Frontend](../guides/frontend/overview) |+| Helper | Import from | Authored at | Guide |+| ----------------------------------------------------- | ----------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | ------------------------------------------------------ |+| `defineAgent` | `eve` | `agent/agent.ts` | [agent.ts](../agent-config) |+| `defineTool` | `eve/tools` | `agent/tools/<name>.ts` | [Tools](../tools) |+| `defineDynamic` | `eve`, `eve/tools`, `eve/skills`, `eve/instructions`, `eve/connections` | dynamic model or subagent `agent.ts`; `agent/{tools,skills,instructions,connections}/` | [Dynamic capabilities](../guides/dynamic-capabilities) |+| `defineMcpClientConnection` | `eve/connections` | `agent/connections/<name>.ts` | [MCP connections](../connections/mcp) |+| `defineOpenAPIConnection` | `eve/connections` | `agent/connections/<name>.ts` | [OpenAPI connections](../connections/openapi) |+| `defineChannel` | `eve/channels` | `agent/channels/<name>.ts` | [Custom channels](../channels/custom) |+| `eveChannel`, `slackChannel`, and the other platforms | `eve/channels/<platform>` | `agent/channels/<platform>.ts` | [Channels](../channels/overview) |+| `defineSkill` | `eve/skills` | `agent/skills/<name>.ts` | [Skills](../skills) |+| `defineInstructions` | `eve/instructions` | `agent/instructions.ts` | [Instructions](../instructions) |+| `defineMemory`, `defineMemoryProvider` | `eve/memory` | `agent/memory.ts` or `agent/memory/<slot>.ts` | [Memory](../memory) |+| `defineHook` | `eve/hooks` | `agent/hooks/<slug>.ts` | [Hooks](../guides/hooks) |+| `defineSchedule` | `eve/schedules` | `agent/schedules/<name>.ts` | [Schedules](../schedules) |+| `defineState` | `eve/context` | tools, hooks, lifecycle | [Session context](../guides/session-context) |+| `defineSandbox` | `eve/sandbox` | `agent/sandbox.ts` | [Sandbox](../sandbox) |+| `defineInstrumentation` | `eve/instrumentation` | `agent/instrumentation.ts` | [instrumentation.ts](../guides/instrumentation) |+| `defineRemoteAgent` | `eve` | `agent/subagents/<id>/agent.ts` | [Remote agents](../guides/remote-agents) |+| `defineEval` | `eve/evals` | `evals/*.eval.ts` | [Evals](../evals/overview) |+| `defineEvalConfig` | `eve/evals` | `evals/evals.config.ts` | [Evals](../evals/overview) |+| `mockModel` | `eve/evals` | Deterministic fixture agent models | [Evals](../evals/overview) |+| `useEveAgent` | `eve/react`, `eve/vue`, `eve/svelte` | frontend | [Frontend](../guides/frontend/overview) |Tool-wide authoring helpers such as `defineTool`, `defineDynamic`, and `disableTool` come from `eve/tools`. Capability-specific definitions and helpers use their own subpaths (see [Built-in tools](../concepts/built-in-tools)): reusable definitions such as `bash` and `glob` come from `eve/tools/<name>`, `webSearch` comes from `eve/tools/web_search`, `experimental_workflow` comes from `eve/tools/workflow`, `sleep` comes from `eve/tools/sleep`, and approval policies and types come from `eve/tools/approval`. The route verbs `GET`/`HEAD`/`POST`/`PUT`/`PATCH`/`DELETE`/`OPTIONS`/`WS` plus `disableRoute` come from `eve/channels`, and the channel auth helpers `localDev`/`vercelOidc`/`placeholderAuth` come from `eve/channels/auth`.@@ -59,6 +59,15 @@ Tool-wide authoring helpers such as `defineTool`, `defineDynamic`, and `disableT`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.+The `eve/connections` version of `defineDynamic` accepts `session.started` and+`turn.started` handlers returning one MCP or OpenAPI connection definition, a+map of connection definitions, or `null`. Its resolver context exposes+authenticated session identity and `channel.kind`, but not conversation history,+delivery payloads, tool inputs, model outputs, or free-form channel metadata. An+authenticated returned definition must set `instanceKey` to a stable,+non-secret account or tenant identifier so durable authorization resumes cannot+cross resolved instances.+## Authored module lifecycleeve evaluates TypeScript definition modules during compilation so it can validate and normalize the agent. Within one agent node, each module namespace loads at most once during that compile. The resolved definition then determines whether the module is also an entry in the runtime bundle:@@ -107,7 +116,7 @@ import template from "../../prompts/template.txt?raw";| `eve/tools/web_search` | Provider-managed `webSearch` configuration || `eve/tools/workflow` | Experimental `Workflow` tool definition || `eve/tools/sleep` | Opt-in durable `sleep` tool |-| `eve/connections` | `defineMcpClientConnection`, `defineOpenAPIConnection` |+| `eve/connections` | `defineMcpClientConnection`, `defineOpenAPIConnection`, `defineDynamic` || `eve/channels` | `defineChannel`, `disableRoute`, route verbs || `eve/channels/eve` | `eveChannel` || `eve/channels/auth` | `localDev`, `vercelOidc`, `placeholderAuth` |diff --git a/e2e/fixtures/agent-openapi-swagger/agent/agent.ts b/e2e/fixtures/agent-openapi-swagger/agent/agent.tsindex 384bb0e2a..8c7ad9038 100644--- a/e2e/fixtures/agent-openapi-swagger/agent/agent.ts+++ b/e2e/fixtures/agent-openapi-swagger/agent/agent.ts@@ -2,6 +2,33 @@ import { e2eAgentConfig } from "@eve-e2e/config";import { defineAgent } from "eve";export default defineAgent({- ...e2eAgentConfig(),+ ...e2eAgentConfig({+ mock: ({ lastUserMessage, toolResults, tools }) => {+ if (lastUserMessage?.includes("DYNAMIC_MCP_CONNECTION_E2E")) {+ const search = tools.find((tool) => tool.name === "connection_search");+ return search?.description?.includes("dynamic-mcp")+ ? "DYNAMIC_MCP_CONNECTION_FOUND"+ : "DYNAMIC_MCP_CONNECTION_MISSING";+ }+ if (!lastUserMessage?.includes("DYNAMIC_CONNECTION_E2E")) {+ return `Mock reply: ${lastUserMessage ?? ""}`;+ }+ if (toolResults.some((result) => result.name === "connection_search")) {+ return "DYNAMIC_CONNECTION_FOUND";+ }+ if (tools.some((tool) => tool.name === "connection_search")) {+ return {+ toolCalls: [+ {+ id: "dynamic-connection-search",+ input: { connection: "dynamic-catalog", keywords: "status", limit: 10 },+ name: "connection_search",+ },+ ],+ };+ }+ return "DYNAMIC_CONNECTION_MISSING";+ },+ }),reasoning: "high",});diff --git a/e2e/fixtures/agent-openapi-swagger/agent/connections/dynamic-catalog.ts b/e2e/fixtures/agent-openapi-swagger/agent/connections/dynamic-catalog.tsnew file mode 100644index 000000000..44dbde68d--- /dev/null+++ b/e2e/fixtures/agent-openapi-swagger/agent/connections/dynamic-catalog.ts@@ -0,0 +1,26 @@+import { defineDynamic, defineOpenAPIConnection } from "eve/connections";++export default defineDynamic({+ events: {+ "session.started": () => ({+ "dynamic-catalog": defineOpenAPIConnection({+ baseUrl: "https://catalog.example.com",+ description: "Caller-specific product catalog.",+ operations: { allow: ["getStatus"] },+ spec: {+ info: { title: "Dynamic catalog", version: "1.0.0" },+ openapi: "3.0.0",+ paths: {+ "/status": {+ get: {+ operationId: "getStatus",+ responses: { 200: { description: "Catalog status." } },+ summary: "Read catalog status.",+ },+ },+ },+ },+ }),+ }),+ },+});diff --git a/e2e/fixtures/agent-openapi-swagger/agent/connections/dynamic-mcp.ts b/e2e/fixtures/agent-openapi-swagger/agent/connections/dynamic-mcp.tsnew file mode 100644index 000000000..910bbd5f3--- /dev/null+++ b/e2e/fixtures/agent-openapi-swagger/agent/connections/dynamic-mcp.ts@@ -0,0 +1,11 @@+import { defineDynamic, defineMcpClientConnection } from "eve/connections";++export default defineDynamic({+ events: {+ "session.started": () =>+ defineMcpClientConnection({+ description: "Caller-specific dynamic MCP service.",+ url: "https://dynamic-mcp.example.invalid/mcp",+ }),+ },+});diff --git a/e2e/fixtures/agent-openapi-swagger/evals/dynamic-connection.eval.ts b/e2e/fixtures/agent-openapi-swagger/evals/dynamic-connection.eval.tsnew file mode 100644index 000000000..055efb4f6--- /dev/null+++ b/e2e/fixtures/agent-openapi-swagger/evals/dynamic-connection.eval.ts@@ -0,0 +1,31 @@+import { defineEval } from "eve/evals";++export default defineEval({+ description: "A session-scoped dynamic OpenAPI connection participates in connection_search.",++ async test(t) {+ if (process.env.EVE_E2E_MODEL !== "mock") {+ t.skip("Requires the deterministic mock model; the fixture API endpoint is non-routable.");+ }++ await t.send("DYNAMIC_CONNECTION_E2E");++ t.succeeded();+ t.toolOrder(["connection_search"]);+ t.calledTool("connection_search", { count: 1, output: hasDynamicStatusTool });+ t.messageIncludes("DYNAMIC_CONNECTION_FOUND");+ },+});++function hasDynamicStatusTool(value: unknown): boolean {+ return (+ Array.isArray(value) &&+ value.some(+ (entry) =>+ typeof entry === "object" &&+ entry !== null &&+ Reflect.get(entry, "connection") === "dynamic-catalog" &&+ Reflect.get(entry, "qualifiedName") === "dynamic-catalog__getStatus",+ )+ );+}diff --git a/e2e/fixtures/agent-openapi-swagger/evals/dynamic-mcp-connection.eval.ts b/e2e/fixtures/agent-openapi-swagger/evals/dynamic-mcp-connection.eval.tsnew file mode 100644index 000000000..407c7f61a--- /dev/null+++ b/e2e/fixtures/agent-openapi-swagger/evals/dynamic-mcp-connection.eval.ts@@ -0,0 +1,16 @@+import { defineEval } from "eve/evals";++export default defineEval({+ description: "A session-scoped dynamic MCP connection is exposed to the model.",++ async test(t) {+ if (process.env.EVE_E2E_MODEL !== "mock") {+ t.skip("Requires the deterministic mock model; the fixture MCP endpoint is non-routable.");+ }++ await t.send("DYNAMIC_MCP_CONNECTION_E2E");++ t.succeeded();+ t.messageIncludes("DYNAMIC_MCP_CONNECTION_FOUND");+ },+});diff --git a/packages/eve/extension-contracts/compatibility/connection/v8.ts b/packages/eve/extension-contracts/compatibility/connection/v8.tsnew file mode 100644index 000000000..d0b61542e--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/connection/v8.ts@@ -0,0 +1,11 @@+import { defineMcpClientConnection } from "#public/connections/index.js";++export default defineMcpClientConnection({+ description: "Call-aware MCP service",+ toolCall: {+ providedArguments: {+ requestId: ({ callId, session, toolName }) => `${session.id}:${toolName}:${callId}`,+ },+ },+ url: "https://example.com/mcp",+});diff --git a/packages/eve/extension-contracts/compatibility/tool/v21.ts b/packages/eve/extension-contracts/compatibility/tool/v21.tsnew file mode 100644index 000000000..f3e0e8878--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/tool/v21.ts@@ -0,0 +1,9 @@+import { defineTool } from "#public/tools/index.js";++export default defineTool({+ description: "Return the active tool identity.",+ inputSchema: { type: "object", properties: {} },+ execute(_input, ctx) {+ return { callId: ctx.callId, toolName: ctx.toolName };+ },+});diff --git a/packages/eve/extension-contracts/entrypoints/connection.ts b/packages/eve/extension-contracts/entrypoints/connection.tsindex cf8735f1b..a33be3144 100644--- a/packages/eve/extension-contracts/entrypoints/connection.ts+++ b/packages/eve/extension-contracts/entrypoints/connection.ts@@ -1,6 +1,7 @@export {ConnectionAuthorizationFailedError,ConnectionAuthorizationRequiredError,+ defineDynamic,defineInteractiveAuthorization,defineMcpClientConnection,defineOpenAPIConnection,diff --git a/packages/eve/extension-contracts/reports/connection/v10.json b/packages/eve/extension-contracts/reports/connection/v10.jsonnew file mode 100644index 000000000..7ec336136--- /dev/null+++ b/packages/eve/extension-contracts/reports/connection/v10.json@@ -0,0 +1,16 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "connection",+ "epoch": 10,+ "sha256": "678ca9ec725863cc15732ddc0c2efb9ff01780efb80dc774a7dde378551d48ce",+ "exports": [+ "ConnectionAuthorizationFailedError",+ "ConnectionAuthorizationRequiredError",+ "defineDynamic",+ "defineInteractiveAuthorization",+ "defineMcpClientConnection",+ "defineOpenAPIConnection",+ "isConnectionAuthorizationFailedError",+ "isConnectionAuthorizationRequiredError"+ ]+}diff --git a/packages/eve/extension-contracts/reports/connection/v9.json b/packages/eve/extension-contracts/reports/connection/v9.jsonnew file mode 100644index 000000000..048c28012--- /dev/null+++ b/packages/eve/extension-contracts/reports/connection/v9.json@@ -0,0 +1,16 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "connection",+ "epoch": 9,+ "sha256": "7a97a7962d2d7d69ec8d9ec1e485bbdf2558e4981bb60fd5c3df712f8139ea7f",+ "exports": [+ "ConnectionAuthorizationFailedError",+ "ConnectionAuthorizationRequiredError",+ "defineDynamic",+ "defineInteractiveAuthorization",+ "defineMcpClientConnection",+ "defineOpenAPIConnection",+ "isConnectionAuthorizationFailedError",+ "isConnectionAuthorizationRequiredError"+ ]+}diff --git a/packages/eve/extension-contracts/reports/tool/v22.json b/packages/eve/extension-contracts/reports/tool/v22.jsonnew file mode 100644index 000000000..914065ea2--- /dev/null+++ b/packages/eve/extension-contracts/reports/tool/v22.json@@ -0,0 +1,19 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "tool",+ "epoch": 22,+ "sha256": "d00cbc5bc1ca7f6e11b275c21f7ec5f0ffe734dc3b25a40d06eb913ca41e2251",+ "exports": [+ "defaultWebSearch",+ "defineTool",+ "disableTool",+ "experimental_workflow",+ "isDisabledToolSentinel",+ "isExperimentalWorkflowToolDefinition",+ "isWebSearchToolDefinition",+ "toolOutput",+ "toolOutputPart",+ "toolResultFrom",+ "webSearch"+ ]+}diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.tsindex 5a746641d..f8510f450 100644--- a/packages/eve/src/compiler/extension-compatibility.ts+++ b/packages/eve/src/compiler/extension-compatibility.ts@@ -22,8 +22,8 @@ interface ExtensionCapabilityContract {const EXTENSION_CAPABILITY_CONTRACTS = {extension: { current: 1, supported: [1], dropped: {} },tool: {- current: 21,- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21],+ current: 22,+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22],dropped: { 15: "TaskExec replaces stageEffect with send" },},dynamicTool: {@@ -42,9 +42,11 @@ const EXTENSION_CAPABILITY_CONTRACTS = {},},connection: {- current: 8,- supported: [1, 2, 3, 4, 5, 6, 7, 8],- dropped: {},+ current: 10,+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 10],+ dropped: {+ 9: "Dynamic connection resolvers no longer receive conversation or channel continuation data",+ },},hook: {current: 16,diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.tsindex f46ca795f..4e83f14be 100644--- a/packages/eve/src/compiler/manifest.ts+++ b/packages/eve/src/compiler/manifest.ts@@ -54,7 +54,7 @@ export const ROOT_COMPILED_AGENT_NODE_ID = "__root__";/*** Current compiled manifest schema version.*/-export const COMPILED_AGENT_MANIFEST_VERSION = 44;+export const COMPILED_AGENT_MANIFEST_VERSION = 45;/*** Compiled channel entry preserved in the compiled manifest.@@ -220,6 +220,14 @@ export type CompiledWorkspaceResourceRoot = z.infer<typeof compiledWorkspaceReso*/export type CompiledConnectionDefinition = z.infer<typeof compiledConnectionDefinitionSchema>;+/** Dynamic connection resolver source preserved for runtime evaluation. */+export interface CompiledDynamicConnectionDefinition extends ModuleSourceRef {+ readonly eventNames: readonly string[];+ /** Map results from extensions receive this mount namespace. */+ readonly extensionNamespace?: string;+ readonly slug: string;+}+/*** Normalized authored tool metadata preserved in the compiled manifest.*/@@ -798,6 +806,18 @@ const compiledConnectionDefinitionSchema = z}).strict();+const compiledDynamicConnectionDefinitionSchema: z.ZodType<CompiledDynamicConnectionDefinition> = z+ .object({+ eventNames: z.array(z.string()).readonly(),+ exportName: z.string().optional(),+ extensionNamespace: z.string().optional(),+ logicalPath: z.string(),+ slug: z.string(),+ sourceId: z.string(),+ sourceKind: z.literal("module"),+ })+ .strict();+const compiledToolDefinitionSchema = z.object({description: z.string(),@@ -896,6 +916,7 @@ const compiledAgentResourceFields = {bindings: z.record(z.string(), compiledModuleBindingSchema),channelRoutes: compiledChannelRoutePlanSchema,connections: z.array(compiledConnectionDefinitionSchema),+ dynamicConnections: z.array(compiledDynamicConnectionDefinitionSchema).default([]),diagnosticsSummary: discoverDiagnosticsSummarySchema,sourceComposition: agentSourceCompositionSchema,workflowTool: compiledWorkflowToolDefinitionSchema.optional(),@@ -1005,6 +1026,7 @@ export const compiledAgentManifestSchema = zchannelRoutes: compiledChannelRoutePlanSchema,config: compiledAgentConfigSchema,connections: z.array(compiledConnectionDefinitionSchema),+ dynamicConnections: z.array(compiledDynamicConnectionDefinitionSchema).default([]),diagnosticsSummary: discoverDiagnosticsSummarySchema,sourceComposition: agentSourceCompositionSchema,workflowTool: compiledWorkflowToolDefinitionSchema.optional(),@@ -1035,6 +1057,7 @@ export interface CreateCompiledAgentResourcesInput {readonly bindings: Readonly<Record<string, CompiledModuleBinding>>;readonly channelRoutes: CompiledChannelRoutePlan;readonly connections?: readonly CompiledConnectionDefinition[];+ readonly dynamicConnections?: readonly CompiledDynamicConnectionDefinition[];readonly diagnosticsSummary?: DiscoverDiagnosticsSummary;readonly sourceComposition: AgentSourceComposition;readonly workflowTool?: CompiledWorkflowToolDefinition;@@ -1070,6 +1093,7 @@ export function createCompiledAgentResources(shadowed: [...input.channelRoutes.shadowed],},connections: [...(input.connections ?? [])],+ dynamicConnections: [...(input.dynamicConnections ?? [])],diagnosticsSummary: input.diagnosticsSummary ?? {errors: 0,warnings: 0,@@ -1221,6 +1245,7 @@ export function createCompiledAgentManifest(input: {readonly channelRoutes: CompiledChannelRoutePlan;readonly config: CompiledAgentDefinition;readonly connections?: readonly CompiledConnectionDefinition[];+ readonly dynamicConnections?: readonly CompiledDynamicConnectionDefinition[];readonly diagnosticsSummary?: DiscoverDiagnosticsSummary;readonly sourceComposition: AgentSourceComposition;readonly workflowTool?: CompiledWorkflowToolDefinition;diff --git a/packages/eve/src/compiler/normalize-connection.ts b/packages/eve/src/compiler/normalize-connection.tsindex 7bd87d2c5..8481d054d 100644--- a/packages/eve/src/compiler/normalize-connection.ts+++ b/packages/eve/src/compiler/normalize-connection.ts@@ -3,12 +3,28 @@ import {normalizeMcpClientConnectionDefinition,normalizeOpenApiConnectionDefinition,} from "#internal/authored-definition/connection.js";-import type { CompiledConnectionDefinition } from "#compiler/manifest.js";+import type {+ CompiledConnectionDefinition,+ CompiledDynamicConnectionDefinition,+} from "#compiler/manifest.js";import {loadModuleBackedDefinition,type ModuleBackedDefinitionLoadOptions,} from "#compiler/normalize-helpers.js";import { readConnectionProtocol } from "#public/definitions/connections/protocol.js";+import {+ ALLOWED_DYNAMIC_CONNECTION_EVENTS,+ assertResolverOnlyDynamicSentinel,+ isDynamicSentinel,+ type DynamicToolEventName,+} from "#dynamic/definition.js";++export type CompiledConnectionEntry =+ | { readonly kind: "connection"; readonly definition: CompiledConnectionDefinition }+ | {+ readonly kind: "dynamic-connection";+ readonly definition: CompiledDynamicConnectionDefinition;+ };/*** Compiles one authored connection module into the serializable metadata@@ -32,16 +48,41 @@ export async function compileConnectionDefinition(_agentRoot: string,source: ConnectionSourceRef,options: ModuleBackedDefinitionLoadOptions,-): Promise<CompiledConnectionDefinition> {+): Promise<CompiledConnectionEntry> {const loaded = await loadModuleBackedDefinition({binding: options.binding,kind: "connection",loadNamespace: options.loadNamespace,source,});- const protocol = readConnectionProtocol(loaded);const message = `Expected the connection export "${source.exportName ?? "default"}" from "${source.logicalPath}" to match the public eve shape.`;+ if (isDynamicSentinel(loaded)) {+ assertResolverOnlyDynamicSentinel(loaded, message);+ const eventNames = Object.keys(loaded.events);+ const unsupportedEvent = eventNames.find(+ (eventName) => !ALLOWED_DYNAMIC_CONNECTION_EVENTS.has(eventName),+ );+ if (unsupportedEvent !== undefined) {+ throw new Error(+ `${message} Dynamic connections support only "session.started" and "turn.started" handlers. Unsupported event: "${unsupportedEvent}".`,+ );+ }+ return {+ kind: "dynamic-connection",+ definition: {+ eventNames: eventNames as DynamicToolEventName[],+ exportName: source.exportName,+ logicalPath: source.logicalPath,+ slug: source.connectionName,+ sourceId: source.sourceId,+ sourceKind: "module",+ },+ };+ }++ const protocol = readConnectionProtocol(loaded);+const shared = {connectionName: source.connectionName,exportName: source.exportName,@@ -78,7 +119,7 @@ export async function compileConnectionDefinition(compiled.vercelConnect = vercelConnect;}- return compiled;+ return { definition: compiled, kind: "connection" };}/**diff --git a/packages/eve/src/compiler/normalize-manifest.test.ts b/packages/eve/src/compiler/normalize-manifest.test.tsindex 02aa06fa7..8c9fba1a9 100644--- a/packages/eve/src/compiler/normalize-manifest.test.ts+++ b/packages/eve/src/compiler/normalize-manifest.test.ts@@ -224,6 +224,20 @@ describe("compileAgentManifest source graph", () => {}),}),},+ {+ logicalPath: "connections/accounts.ts",+ loadNamespace: async () => ({+ default: defineDynamic({+ events: {+ "turn.started": () =>+ defineMcpClientConnection({+ description: "Caller account.",+ url: "https://mcp.accounts.example",+ }),+ },+ }),+ }),+ },{logicalPath: "hooks/audit.ts",loadNamespace: async () => ({@@ -239,8 +253,16 @@ describe("compileAgentManifest source graph", () => {Object.values(compiled.bindings).map((binding) => [binding.logicalPath, binding.usage]),);+ expect(compiled.dynamicConnections).toContainEqual(+ expect.objectContaining({+ eventNames: ["turn.started"],+ logicalPath: "connections/accounts.ts",+ slug: "accounts",+ }),+ );expect(usageByLogicalPath).toMatchObject({"agent.ts": { compile: true, runtimeEntry: false },+ "connections/accounts.ts": { compile: true, runtimeEntry: true },"connections/linear.ts": { compile: true, runtimeEntry: true },"hooks/audit.ts": { compile: true, runtimeEntry: true },"instructions/dynamic.ts": { compile: true, runtimeEntry: true },@@ -256,6 +278,37 @@ describe("compileAgentManifest source graph", () => {});});+ it("rejects step-scoped dynamic connections", async () => {+ const sourceRegistry = registry([+ {+ logicalPath: "agent.ts",+ loadNamespace: async () => ({+ default: defineAgent({ model: "openai/gpt-5.4" }),+ }),+ },+ {+ logicalPath: "connections/accounts.ts",+ loadNamespace: async () => ({+ default: defineDynamic({+ events: {+ "step.started": () =>+ defineMcpClientConnection({+ description: "Caller account.",+ url: "https://mcp.accounts.example",+ }),+ },+ }),+ }),+ },+ ]);++ await expect(+ compileAgentManifest(manifest(), { sourceRegistries: [sourceRegistry] }),+ ).rejects.toThrow(+ 'Dynamic connections support only "session.started" and "turn.started" handlers.',+ );+ });+it("projects the root node once and finalizes its filesystem bindings after config", async () => {let toolSourceIterations = 0;const discovered = manifest();diff --git a/packages/eve/src/compiler/normalize-manifest.ts b/packages/eve/src/compiler/normalize-manifest.tsindex 4c4bacecd..0e5533566 100644--- a/packages/eve/src/compiler/normalize-manifest.ts+++ b/packages/eve/src/compiler/normalize-manifest.ts@@ -8,6 +8,7 @@ import {type CompiledAgentResources,type CompiledChannelDefinition,type CompiledConnectionDefinition,+ type CompiledDynamicConnectionDefinition,type CompiledDynamicInstructionsDefinition,type CompiledDynamicSkillDefinition,type CompiledDynamicToolDefinition,@@ -493,6 +494,7 @@ class AgentGraphCompiler {const instructions: CompiledInstructionsDefinition[] = [];const dynamicInstructions: CompiledDynamicInstructionsDefinition[] = [];const connections: CompiledConnectionDefinition[] = [];+ const dynamicConnections: CompiledDynamicConnectionDefinition[] = [];const memories: CompiledMemoryDefinition[] = [];const hooks: CompiledHookDefinition[] = [];const schedules: CompiledScheduleDefinition[] = [];@@ -530,15 +532,18 @@ class AgentGraphCompiler {} else channels.push(...result.definitions);break;}- case "connection":- connections.push(- await compileConnectionDefinition(input.manifest.agentRoot, entry.source, {- binding: binding!,- loadNamespace,- }),- );+ case "connection": {+ const result = await compileConnectionDefinition(input.manifest.agentRoot, entry.source, {+ binding: binding!,+ loadNamespace,+ });+ if (result.kind === "connection") connections.push(result.definition);+ else {+ dynamicConnections.push(withExtensionNamespace(result.definition, candidate.owner));+ }state.evaluation.requireRuntimeEntry(candidate.sourceId);break;+ }case "hook":hooks.push(await compileHookEntry(entry.source, {@@ -638,6 +643,7 @@ class AgentGraphCompiler {assertUniqueBy(tools, (tool) => tool.name, "tool name");assertUniqueBy(dynamicTools, (tool) => tool.slug, "dynamic tool slug");assertUniqueBy(connections, (connection) => connection.connectionName, "connection name");+ assertUniqueBy(dynamicConnections, (connection) => connection.slug, "dynamic connection slug");assertUniqueBy(skills, (skill) => skill.name, "skill name");const channelRoutes = createCompiledChannelRoutePlan({@@ -667,6 +673,7 @@ class AgentGraphCompiler {channelRoutes,connections,diagnosticsSummary: summarizeCompilerDiagnostics(this.diagnostics),+ dynamicConnections,dynamicInstructions,dynamicSkills,dynamicTools,diff --git a/packages/eve/src/compiler/validate-artifact.ts b/packages/eve/src/compiler/validate-artifact.tsindex 01be414d4..4eea73ea5 100644--- a/packages/eve/src/compiler/validate-artifact.ts+++ b/packages/eve/src/compiler/validate-artifact.ts@@ -166,6 +166,13 @@ export function validateCompiledAgentResources(node.connections.map((entry) => ({ identity: entry.connectionName, kind: "connection" })),"connection name",);+ validateUniqueIdentities(+ node.dynamicConnections.map((entry) => ({+ identity: entry.slug,+ kind: "dynamic connection",+ })),+ "dynamic connection slug",+ );validateUniqueIdentities(node.hooks.map((entry) => ({ identity: entry.slug, kind: "hook" })),"hook slug",@@ -330,6 +337,7 @@ function collectReferencedModuleSources(if (route.source.backing.kind !== "resource") add(route.source);}for (const value of node.connections) add(value);+ for (const value of node.dynamicConnections) 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);diff --git a/packages/eve/src/context/dynamic-connection-lifecycle.test.ts b/packages/eve/src/context/dynamic-connection-lifecycle.test.tsnew file mode 100644index 000000000..a9de914a6--- /dev/null+++ b/packages/eve/src/context/dynamic-connection-lifecycle.test.ts@@ -0,0 +1,376 @@+import { describe, expect, it } from "vitest";++import { ContextContainer } from "#context/container.js";+import { dispatchDynamicConnectionEvent } from "#context/dynamic-connection-lifecycle.js";+import { AuthKey, SessionIdKey } from "#context/keys.js";+import { ConnectionRegistryKey } from "#context/providers/connection-key.js";+import { defineMcpClientConnection } from "#public/definitions/connections/mcp.js";+import { defineOpenAPIConnection } from "#public/definitions/connections/openapi.js";+import { createSessionStartedEvent, createTurnStartedEvent } from "#protocol/message.js";+import { ConnectionRegistryImpl } from "#runtime/connections/registry.js";+import type {+ ResolvedConnectionDefinition,+ ResolvedDynamicConnectionResolver,+} from "#runtime/types.js";++describe("dynamic connection lifecycle", () => {+ it("resolves a mixed connection map with bare map-key names", async () => {+ const { ctx, registry } = createContext();+ const resolver = createResolver({+ handler: () => ({+ catalog: defineOpenAPIConnection({+ baseUrl: "https://catalog.example.com",+ description: "Product catalog.",+ spec: { info: { title: "Catalog", version: "1" }, openapi: "3.0.0", paths: {} },+ }),+ production: defineMcpClientConnection({+ description: "Production account.",+ url: "https://mcp.example.com/production",+ }),+ }),+ });++ await dispatchDynamicConnectionEvent({+ ctx,+ event: createSessionStartedEvent(),+ resolvers: [resolver],+ });++ expect(registry.getConnections()).toMatchObject([+ {+ connectionName: "catalog",+ description: "Product catalog.",+ protocol: "openapi",+ url: "https://catalog.example.com",+ },+ {+ connectionName: "production",+ description: "Production account.",+ protocol: "mcp",+ url: "https://mcp.example.com/production",+ },+ ]);+ });++ it("names one returned connection after its file slug", async () => {+ const { ctx, registry } = createContext();+ const resolver = createResolver({+ handler: () =>+ defineMcpClientConnection({+ description: "Current account.",+ url: "https://mcp.example.com/current",+ }),+ slug: "aws",+ });++ await dispatchDynamicConnectionEvent({+ ctx,+ event: createSessionStartedEvent(),+ resolvers: [resolver],+ });++ expect(registry.getConnectionNames()).toEqual(["aws"]);+ });++ it("lets a turn result replace the same resolver's session result", async () => {+ const { ctx, registry } = createContext();+ const resolver = createResolver({+ eventNames: ["session.started", "turn.started"],+ events: {+ "session.started": () => ({+ primary: defineMcpClientConnection({+ description: "Primary account.",+ url: "https://mcp.example.com/primary",+ }),+ }),+ "turn.started": () => null,+ },+ });++ await dispatchDynamicConnectionEvent({+ ctx,+ event: createSessionStartedEvent(),+ resolvers: [resolver],+ });+ expect(registry.getConnectionNames()).toEqual(["primary"]);++ await dispatchDynamicConnectionEvent({+ ctx,+ event: createTurnStartedEvent({ sequence: 0, turnId: "turn-1" }),+ resolvers: [resolver],+ });+ expect(registry.getConnectionNames()).toEqual([]);+ });++ it("lets a dynamic result override a static connection by name", async () => {+ const staticConnection = createStaticConnection("production");+ const { ctx, registry } = createContext([staticConnection]);+ const resolver = createResolver({+ handler: () => ({+ production: defineMcpClientConnection({+ description: "Caller production account.",+ url: "https://dynamic.example.com/mcp",+ }),+ }),+ });++ await dispatchDynamicConnectionEvent({+ ctx,+ event: createSessionStartedEvent(),+ resolvers: [resolver],+ });++ expect(registry.getConnections()).toMatchObject([+ { connectionName: "production", description: "Caller production account." },+ ]);+ });++ it("does not reveal a shadowed static connection when its resolver fails", async () => {+ const { ctx, registry } = createContext([createStaticConnection("production")]);+ const resolver = createResolver({+ eventNames: ["session.started", "turn.started"],+ events: {+ "session.started": () => ({+ production: defineMcpClientConnection({+ description: "Caller production account.",+ url: "https://dynamic.example.com/mcp",+ }),+ }),+ "turn.started": () => {+ throw new Error("account lookup failed");+ },+ },+ });++ await dispatchDynamicConnectionEvent({+ ctx,+ event: createSessionStartedEvent(),+ resolvers: [resolver],+ });++ await expect(+ dispatchDynamicConnectionEvent({+ ctx,+ event: createTurnStartedEvent({ sequence: 0, turnId: "turn-1" }),+ resolvers: [resolver],+ }),+ ).rejects.toThrow(+ 'Dynamic connection resolver "connections/accounts.ts" failed during "turn.started".',+ );+ expect(registry.getConnections()).toMatchObject([+ { connectionName: "production", description: "Caller production account." },+ ]);+ });++ it("requires an instance key for authenticated dynamic connections", async () => {+ const { ctx } = createContext();+ const resolver = createResolver({+ handler: () =>+ defineMcpClientConnection({+ auth: { getToken: async () => ({ token: "token" }) },+ description: "Current account.",+ url: "https://mcp.example.com/current",+ }),+ });++ await expect(+ dispatchDynamicConnectionEvent({+ ctx,+ event: createSessionStartedEvent(),+ resolvers: [resolver],+ }),+ ).rejects.toThrow(+ 'Dynamic connection resolver "connections/accounts.ts" failed during "session.started".',+ );+ });++ it("derives an opaque identity for authenticated dynamic connections", async () => {+ const { ctx, registry } = createContext();+ let instanceKey = "account-123";+ const resolver = createResolver({+ eventNames: ["session.started", "turn.started"],+ events: {+ "session.started": () =>+ defineMcpClientConnection({+ auth: { getToken: async () => ({ token: "token" }) },+ description: "Current account.",+ instanceKey,+ url: "https://mcp.example.com/current",+ }),+ "turn.started": () =>+ defineMcpClientConnection({+ auth: { getToken: async () => ({ token: "token" }) },+ description: "Current account.",+ instanceKey,+ url: "https://mcp.example.com/current",+ }),+ },+ });++ await dispatchDynamicConnectionEvent({+ ctx,+ event: createSessionStartedEvent(),+ resolvers: [resolver],+ });++ const firstInstanceId = registry.getConnections()[0]?.instanceId;+ expect(firstInstanceId).toMatch(/^connection:/);+ expect(firstInstanceId).not.toContain("account-123");++ instanceKey = "account-456";+ await dispatchDynamicConnectionEvent({+ ctx,+ event: createTurnStartedEvent({ sequence: 0, turnId: "turn-1" }),+ resolvers: [resolver],+ });++ expect(registry.getConnections()[0]?.instanceId).not.toBe(firstInstanceId);+ });++ it("passes connection resolvers only trusted identity and channel kind", async () => {+ const { ctx } = createContext();+ ctx.set(AuthKey, {+ attributes: {},+ authenticator: "test",+ issuer: "https://idp.example.com",+ principalId: "user-1",+ principalType: "user",+ });+ let received: unknown;+ const resolver = createResolver({+ events: {+ "session.started": (_event, resolveCtx) => {+ received = resolveCtx;+ return null;+ },+ },+ });++ await dispatchDynamicConnectionEvent({+ ctx,+ event: createSessionStartedEvent(),+ resolvers: [resolver],+ });++ expect(received).toEqual({+ channel: { kind: undefined },+ session: {+ auth: {+ current: expect.objectContaining({ principalId: "user-1" }),+ initiator: null,+ },+ id: "session-1",+ },+ });+ expect(received).not.toHaveProperty("messages");+ });++ it("rejects collisions between effective dynamic resolvers", async () => {+ const { ctx } = createContext();+ const connection = () => ({+ shared: defineMcpClientConnection({+ description: "Shared account.",+ url: "https://mcp.example.com/shared",+ }),+ });++ await expect(+ dispatchDynamicConnectionEvent({+ ctx,+ event: createSessionStartedEvent(),+ resolvers: [+ createResolver({ handler: connection, slug: "first" }),+ createResolver({ handler: connection, slug: "second" }),+ ],+ }),+ ).rejects.toThrow(+ 'Dynamic connection "shared" from resolver "second" collides with dynamic resolver "first".',+ );+ });++ it("fails closed when a handler returns an unbranded connection", async () => {+ const { ctx, registry } = createContext();+ const resolver = createResolver({+ handler: () => ({+ unsafe: {+ description: "Unbranded.",+ url: "https://mcp.example.com/unsafe",+ },+ }),+ });++ await expect(+ dispatchDynamicConnectionEvent({+ ctx,+ event: createSessionStartedEvent(),+ resolvers: [resolver],+ }),+ ).rejects.toThrow(+ 'Dynamic connection resolver "connections/accounts.ts" failed during "session.started".',+ );++ expect(registry.getConnections()).toEqual([]);+ });++ it("prefixes map keys produced by an extension resolver", async () => {+ const { ctx, registry } = createContext();+ const resolver = createResolver({+ extensionNamespace: "cloud",+ handler: () => ({+ production: defineMcpClientConnection({+ description: "Production account.",+ url: "https://mcp.example.com/production",+ }),+ }),+ });++ await dispatchDynamicConnectionEvent({+ ctx,+ event: createSessionStartedEvent(),+ resolvers: [resolver],+ });++ expect(registry.getConnectionNames()).toEqual(["cloud__production"]);+ });+});++function createContext(staticConnections: readonly ResolvedConnectionDefinition[] = []) {+ const ctx = new ContextContainer();+ ctx.set(SessionIdKey, "session-1");+ const registry = new ConnectionRegistryImpl(staticConnections);+ ctx.set(ConnectionRegistryKey, registry);+ return { ctx, registry };+}++function createResolver(+ input: {+ readonly eventNames?: readonly string[];+ readonly events?: ResolvedDynamicConnectionResolver["events"];+ readonly extensionNamespace?: string;+ readonly handler?: () => unknown;+ readonly slug?: string;+ } = {},+): ResolvedDynamicConnectionResolver {+ const slug = input.slug ?? "accounts";+ return {+ eventNames: input.eventNames ?? ["session.started"],+ events: input.events ?? { "session.started": input.handler ?? (() => null) },+ extensionNamespace: input.extensionNamespace,+ logicalPath: `connections/${slug}.ts`,+ slug,+ sourceId: `connections/${slug}`,+ sourceKind: "module",+ };+}++function createStaticConnection(name: string): ResolvedConnectionDefinition {+ return {+ connectionName: name,+ description: "Static connection.",+ logicalPath: `connections/${name}.ts`,+ protocol: "mcp",+ sourceId: `connections/${name}`,+ sourceKind: "module",+ url: `https://${name}.example.com/mcp`,+ };+}diff --git a/packages/eve/src/context/dynamic-connection-lifecycle.ts b/packages/eve/src/context/dynamic-connection-lifecycle.tsnew file mode 100644index 000000000..08b8cf1e9--- /dev/null+++ b/packages/eve/src/context/dynamic-connection-lifecycle.ts@@ -0,0 +1,137 @@+import { getAdapterKind } from "#channel/adapter.js";+import type { ContextContainer } from "#context/container.js";+import { AuthKey, InitiatorAuthKey, SessionIdKey } from "#context/keys.js";+import { ConnectionRegistryKey } from "#context/providers/connection-key.js";+import { ALLOWED_DYNAMIC_CONNECTION_EVENTS } from "#dynamic/definition.js";+import { CONNECTION_SLUG_PATTERN } from "#discover/grammar.js";+import { createLogger } from "#internal/logging.js";+import type { UnstampedMessageStreamEvent } from "#protocol/message.js";+import { readStampedConnectionProtocol } from "#public/definitions/connections/protocol.js";+import type { DynamicConnectionResolveContext } from "#public/definitions/connections/dynamic.js";+import { ConnectionRegistryImpl } from "#runtime/connections/registry.js";+import { ChannelKey } from "#runtime/sessions/runtime-context-keys.js";+import { resolveDynamicConnectionValue } from "#runtime/resolve-connection.js";+import type {+ ResolvedConnectionDefinition,+ ResolvedDynamicConnectionResolver,+} from "#runtime/types.js";+import { toErrorMessage } from "#shared/errors.js";++const log = createLogger("dynamic-connections");++function qualifyConnectionNames(+ resolver: ResolvedDynamicConnectionResolver,+ value: unknown,+): readonly { readonly name: string; readonly value: unknown }[] {+ if (readStampedConnectionProtocol(value) !== undefined) {+ return [{ name: resolver.slug, value }];+ }+ if (typeof value !== "object" || value === null || Array.isArray(value)) {+ throw new Error(+ `Dynamic connection resolver "${resolver.logicalPath}" must return a connection definition, a map of connection definitions, or null.`,+ );+ }++ const prefix =+ resolver.extensionNamespace === undefined ? "" : `${resolver.extensionNamespace}__`;+ return Object.entries(value).map(([name, entry]) => {+ if (!CONNECTION_SLUG_PATTERN.test(name)) {+ throw new Error(+ `Dynamic connection resolver "${resolver.logicalPath}" returned illegal connection name "${name}". Expected lowercase ASCII letters, digits, and dashes only, starting with a letter, up to 64 characters.`,+ );+ }+ if (readStampedConnectionProtocol(entry) === undefined) {+ throw new Error(+ `Dynamic connection resolver "${resolver.logicalPath}" returned "${name}" without defineMcpClientConnection() or defineOpenAPIConnection().`,+ );+ }+ return { name: `${prefix}${name}`, value: entry };+ });+}++async function resolveConnections(input: {+ readonly ctx: ContextContainer;+ readonly event: UnstampedMessageStreamEvent;+ readonly resolver: ResolvedDynamicConnectionResolver;+}): Promise<readonly ResolvedConnectionDefinition[]> {+ const handler = input.resolver.events[input.event.type];+ if (handler === undefined) return [];+ const value = await handler(input.event, buildConnectionResolveContext(input.ctx));+ if (value === null || value === undefined) return [];++ return qualifyConnectionNames(input.resolver, value).map(({ name, value: definition }) =>+ resolveDynamicConnectionValue(definition, {+ connectionName: name,+ exportName: input.resolver.exportName,+ logicalPath: input.resolver.logicalPath,+ sourceId: input.resolver.sourceId,+ sourceKind: "module",+ }),+ );+}++/** Resolves and replaces the dynamic connection set for one lifecycle scope. */+export async function dispatchDynamicConnectionEvent(input: {+ readonly ctx: ContextContainer;+ readonly resolvers: readonly ResolvedDynamicConnectionResolver[];+ readonly event: UnstampedMessageStreamEvent;+}): Promise<void> {+ if (!ALLOWED_DYNAMIC_CONNECTION_EVENTS.has(input.event.type)) return;+ const matching = input.resolvers.filter((resolver) =>+ resolver.eventNames.includes(input.event.type),+ );+ if (matching.length === 0) return;++ const registry = input.ctx.get(ConnectionRegistryKey);+ if (!(registry instanceof ConnectionRegistryImpl)) {+ throw new Error("Dynamic connection resolution requires the framework connection registry.");+ }++ const outcomes = await Promise.allSettled(+ matching.map(async (resolver) => ({+ connections: await resolveConnections({ ...input, resolver }),+ resolver,+ })),+ );+ const updates = new Map<string, readonly ResolvedConnectionDefinition[]>();+ let failedResolver: ResolvedDynamicConnectionResolver | undefined;+ for (let index = 0; index < outcomes.length; index += 1) {+ const outcome = outcomes[index]!;+ const resolver = matching[index]!;+ if (outcome.status === "rejected") {+ log.error(`Dynamic connection resolver (${input.event.type}) failed.`, {+ error: toErrorMessage(outcome.reason),+ logicalPath: resolver.logicalPath,+ });+ failedResolver ??= resolver;+ continue;+ }+ updates.set(outcome.value.resolver.slug, outcome.value.connections);+ }+ if (failedResolver !== undefined) {+ throw new Error(+ `Dynamic connection resolver "${failedResolver.logicalPath}" failed during "${input.event.type}".`,+ );+ }++ await registry.replaceDynamicConnections(+ input.event.type === "session.started" ? "session" : "turn",+ updates,+ );+}++function buildConnectionResolveContext(ctx: ContextContainer): DynamicConnectionResolveContext {+ const channel = ctx.get(ChannelKey);+ return {+ session: {+ id: ctx.get(SessionIdKey) ?? "",+ auth: {+ current: ctx.get(AuthKey) ?? null,+ initiator: ctx.get(InitiatorAuthKey) ?? null,+ },+ },+ channel: {+ kind: channel === undefined ? undefined : getAdapterKind(channel),+ },+ };+}diff --git a/packages/eve/src/context/providers/connection.ts b/packages/eve/src/context/providers/connection.tsindex a27ae3a6c..86aead0d1 100644--- a/packages/eve/src/context/providers/connection.ts+++ b/packages/eve/src/context/providers/connection.ts@@ -14,8 +14,12 @@ export const connectionProvider: FrameworkContextProvider<ConnectionRegistry> =const bundle = ctx.get(BundleKey);if (bundle === undefined) return undefined;const node = getActiveRuntimeNode(ctx);- const connections = node.agent?.connections;- if (!connections || connections.length === 0) return undefined;+ const agent = node.agent;+ if (agent === undefined) return undefined;+ const connections = agent.connections;+ if (connections.length === 0 && (agent.dynamicConnectionResolvers?.length ?? 0) === 0) {+ return undefined;+ }return { value: new ConnectionRegistryImpl(connections) };},diff --git a/packages/eve/src/dynamic/definition.ts b/packages/eve/src/dynamic/definition.tsindex 38f7f83fe..173b7134f 100644--- a/packages/eve/src/dynamic/definition.ts+++ b/packages/eve/src/dynamic/definition.ts@@ -33,6 +33,10 @@ export const ALLOWED_DYNAMIC_SKILL_EVENTS: ReadonlySet<string> = new Set<Dynamic"turn.started",]);+export const ALLOWED_DYNAMIC_CONNECTION_EVENTS: ReadonlySet<string> = new Set<DynamicToolEventName>(+ ["session.started", "turn.started"],+);+/*** Context passed to a dynamic resolver's event handler.*@@ -95,7 +99,7 @@ export type DynamicSentinel<TResult = unknown> = {/*** Defines a dynamic resolver evaluated at runtime from stream-event- * handlers. It is shared across tools, skills, and agent definitions;+ * handlers. It is shared across tools, skills, connections, and agent definitions;* the directory it is authored in (not this function) decides what each* handler must return and which events are honored. The file's path-derived* slug names the single-entry case; a `Record<string, ...>` return names@@ -106,12 +110,14 @@ export type DynamicSentinel<TResult = unknown> = {* `Record<string, defineTool(...)>`, or `null`.* - `agent/skills/`: return a single `defineSkill(...)`, a* `Record<string, defineSkill(...)>`, or `null`.+ * - `agent/connections/`: return one connection definition, a+ * `Record<string, connection definition>`, or `null`.* - `agent/subagents/<name>/agent.ts`: return `defineAgent(...)` to configure* and expose the subagent, or `null` to omit it.** Per-slot events: tools resolvers run at `session.started`,- * `turn.started`, and `step.started`. Skills resolvers run only at- * `session.started` and `turn.started`; the runtime never invokes a+ * `turn.started`, and `step.started`. Skills and connection resolvers run only+ * at `session.started` and `turn.started`; the runtime never invokes a* handler keyed on `step.started` in that slot. Dynamic subagents run at* `session.started` and `turn.started` only.*diff --git a/packages/eve/src/execution/authorization-callback-match.test.ts b/packages/eve/src/execution/authorization-callback-match.test.tsnew file mode 100644index 000000000..3f809ec60--- /dev/null+++ b/packages/eve/src/execution/authorization-callback-match.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it } from "vitest";+import { matchAuthorizationCallbacks } from "#execution/authorization-callback-match.js";+import type { PendingAuthorizationState } from "#harness/authorization.js";++describe("matchAuthorizationCallbacks", () => {+ it("carries the resolved connection instance into the callback result", () => {+ const pending: PendingAuthorizationState = {+ challenges: [+ {+ attemptId: "attempt-1",+ challenge: { url: "https://auth.example.com" },+ hookUrl: "https://app.example.com/callback",+ instanceId: "connection:instance-a",+ name: "crm",+ principal: { type: "app" },+ },+ ],+ };++ const result = matchAuthorizationCallbacks(pending, [+ {+ authorizationCallback: {+ attemptId: "attempt-1",+ callback: { params: { code: "callback-code" } },+ connectionName: "crm",+ },+ },+ ]);++ expect(result.matches).toHaveLength(1);+ expect(result.matches[0]?.result.instanceId).toBe("connection:instance-a");+ expect(result.remainingPayloads).toEqual([]);+ });+});diff --git a/packages/eve/src/execution/authorization-callback-match.ts b/packages/eve/src/execution/authorization-callback-match.tsindex 78d978a26..9cccc7ea2 100644--- a/packages/eve/src/execution/authorization-callback-match.ts+++ b/packages/eve/src/execution/authorization-callback-match.ts@@ -57,6 +57,7 @@ export function matchAuthorizationCallbacks(attemptId: challenge.attemptId,callback: callback.callback,hookUrl: challenge.hookUrl,+ instanceId: challenge.instanceId,name: challenge.name,principal: challenge.principal,resume: challenge.resume,diff --git a/packages/eve/src/execution/cancelled-turn-message.ts b/packages/eve/src/execution/cancelled-turn-message.tsnew file mode 100644index 000000000..8fab18c8b--- /dev/null+++ b/packages/eve/src/execution/cancelled-turn-message.ts@@ -0,0 +1,13 @@+import { stageAttachmentsToSandbox } from "#harness/attachment-staging.js";+import { normalizeUserContent } from "#harness/messages.js";+import type { HarnessSession, StepInput } from "#harness/types.js";++export async function preserveCancelledTurnMessage(+ session: HarnessSession,+ input: StepInput | undefined,+): Promise<HarnessSession> {+ const message = normalizeUserContent(input?.message);+ if (message === undefined) return session;+ const content = await stageAttachmentsToSandbox(message);+ return { ...session, history: [...session.history, { content, role: "user" }] };+}diff --git a/packages/eve/src/execution/dynamic-connections.test.ts b/packages/eve/src/execution/dynamic-connections.test.tsnew file mode 100644index 000000000..e6c772167--- /dev/null+++ b/packages/eve/src/execution/dynamic-connections.test.ts@@ -0,0 +1,91 @@+import { describe, expect, it } from "vitest";++import { ContextContainer } from "#context/container.js";+import { SessionIdKey } from "#context/keys.js";+import { ConnectionRegistryKey } from "#context/providers/connection-key.js";+import { bindDynamicConnections } from "#execution/dynamic-connections.js";+import { defineMcpClientConnection } from "#public/definitions/connections/mcp.js";+import { ConnectionRegistryImpl } from "#runtime/connections/registry.js";+import type { ResolvedDynamicConnectionResolver } from "#runtime/types.js";++describe("bindDynamicConnections", () => {+ it("rehydrates the active session and turn before a resumed step", async () => {+ const seen: string[] = [];+ const { lifecycle, registry } = createLifecycle({+ eventNames: ["session.started", "turn.started"],+ events: {+ "session.started": (event) => {+ seen.push((event as { type: string }).type);+ return { session: connection("Session account") };+ },+ "turn.started": (event) => {+ seen.push((event as { type: string }).type);+ return { turn: connection("Turn account") };+ },+ },+ });++ await lifecycle.rehydrate(+ { sequence: 3, sessionStarted: true, stepIndex: 1, turnId: "turn_3" },+ { agentId: "agent", eveVersion: "test" },+ false,+ );++ expect(seen).toEqual(["session.started", "turn.started"]);+ expect(registry.getConnectionNames()).toEqual(["turn"]);+ });++ it("rehydrates only the session while between turns", async () => {+ const seen: string[] = [];+ const { lifecycle, registry } = createLifecycle({+ eventNames: ["session.started", "turn.started"],+ events: {+ "session.started": (event) => {+ seen.push((event as { type: string }).type);+ return { session: connection("Session account") };+ },+ "turn.started": (event) => {+ seen.push((event as { type: string }).type);+ return { turn: connection("Turn account") };+ },+ },+ });++ await lifecycle.rehydrate(+ { sequence: 4, sessionStarted: true, stepIndex: 0, turnId: "" },+ { agentId: "agent", eveVersion: "test" },+ true,+ );++ expect(seen).toEqual(["session.started"]);+ expect(registry.getConnectionNames()).toEqual(["session"]);+ });+});++function createLifecycle(+ resolver: Pick<ResolvedDynamicConnectionResolver, "eventNames" | "events">,+) {+ const ctx = new ContextContainer();+ ctx.set(SessionIdKey, "session-1");+ const registry = new ConnectionRegistryImpl([]);+ ctx.set(ConnectionRegistryKey, registry);+ const lifecycle = bindDynamicConnections(ctx, {+ dynamicConnectionResolvers: [+ {+ ...resolver,+ logicalPath: "connections/accounts.ts",+ slug: "accounts",+ sourceId: "connections/accounts",+ sourceKind: "module",+ },+ ],+ });+ return { lifecycle, registry };+}++function connection(description: string) {+ return defineMcpClientConnection({+ description,+ url: "https://mcp.example.com",+ });+}diff --git a/packages/eve/src/execution/dynamic-connections.ts b/packages/eve/src/execution/dynamic-connections.tsnew file mode 100644index 000000000..c0873a241--- /dev/null+++ b/packages/eve/src/execution/dynamic-connections.ts@@ -0,0 +1,37 @@+import type { ContextContainer } from "#context/container.js";+import { dispatchDynamicConnectionEvent } from "#context/dynamic-connection-lifecycle.js";+import { activeTurnId } from "#harness/active-turn-id.js";+import type { HarnessEmissionState } from "#harness/emission.js";+import {+ createSessionStartedEvent,+ createTurnStartedEvent,+ type RuntimeIdentity,+ type UnstampedMessageStreamEvent,+} from "#protocol/message.js";+import type { ResolvedAgent } from "#runtime/types.js";++/** Binds dynamic connection lifecycle dispatch to one execution context. */+export function bindDynamicConnections(+ ctx: ContextContainer,+ agent: Pick<ResolvedAgent, "dynamicConnectionResolvers">,+) {+ const resolvers = agent.dynamicConnectionResolvers ?? [];+ const dispatch = (event: UnstampedMessageStreamEvent): Promise<void> =>+ dispatchDynamicConnectionEvent({ ctx, event, resolvers });++ return {+ dispatch,+ async rehydrate(+ state: HarnessEmissionState,+ runtime: RuntimeIdentity,+ betweenTurns: boolean,+ ): Promise<void> {+ if (!state.sessionStarted) return;+ await dispatch(createSessionStartedEvent({ runtime }));+ if (betweenTurns) return;+ await dispatch(+ createTurnStartedEvent({ sequence: state.sequence, turnId: activeTurnId(state) }),+ );+ },+ };+}diff --git a/packages/eve/src/execution/tools/connection-search.test.ts b/packages/eve/src/execution/tools/connection-search.test.tsindex 1b8527031..1b9c9c5c7 100644--- a/packages/eve/src/execution/tools/connection-search.test.ts+++ b/packages/eve/src/execution/tools/connection-search.test.ts@@ -390,6 +390,44 @@ describe("connection_search", () => {expect(notionCompletions).toBe(0);});+ it("does not pass a parked callback to a newly resolved connection instance", async () => {+ const completeAuthorization = vi.fn(async () => ({ token: "instance-b-token" }));+ const salesforce: ResolvedConnectionDefinition = {+ ...connection("salesforce"),+ authorization: {+ completeAuthorization,+ getToken: async () => ({ token: "instance-b-token" }),+ principalType: "user",+ startAuthorization: async () => ({ challenge: {} }),+ },+ instanceId: "instance-b",+ };+ const connectionRegistry = registry({+ connections: [salesforce],+ loadTools: { salesforce: async () => [] },+ });++ await expect(+ executeConnectionSearch(+ connectionRegistry,+ { connection: "salesforce", keywords: "accounts" },+ (ctx) => {+ ctx.set(PendingAuthorizationResultKey, [+ {+ attemptId: "attempt-a",+ callback: { method: "GET", params: { code: "code-a" } },+ hookUrl: "https://agent.example.com/callback",+ instanceId: "instance-a",+ name: "salesforce",+ principal: { id: "user-1", issuer: "test-idp", type: "user" },+ },+ ]);+ },+ ),+ ).rejects.toThrow("resolved connection changed while sign-in was pending");+ expect(completeAuthorization).not.toHaveBeenCalled();+ });+it("returns an authorization signal when sign-in can be started", async () => {const salesforce: ResolvedConnectionDefinition = {...connection("salesforce"),@@ -403,6 +441,7 @@ describe("connection_search", () => {challenge: { url: "https://idp.example.com/authorize" },}),},+ instanceId: "salesforce-instance",};const connectionRegistry = registry({connections: [salesforce],@@ -435,6 +474,7 @@ describe("connection_search", () => {{name: "salesforce",challenge: { url: "https://idp.example.com/authorize" },+ instanceId: "salesforce-instance",},]);});diff --git a/packages/eve/src/execution/tools/connection-search.ts b/packages/eve/src/execution/tools/connection-search.tsindex 7fb550bf0..edbaaa079 100644--- a/packages/eve/src/execution/tools/connection-search.ts+++ b/packages/eve/src/execution/tools/connection-search.ts@@ -7,6 +7,7 @@ import {type AuthorizationSignal,consumeAuthorizationResult,createAuthorizationAttempt,+ getAuthorizationResults,requestAuthorization,} from "#harness/authorization.js";import {@@ -25,6 +26,7 @@ import type { JsonValue } from "#shared/json.js";import type { JsonObject } from "#shared/json.js";import { stampDurableDynamicToolCallbacks } from "#tools/durable-callbacks.js";import { writeCachedToken } from "#runtime/connections/authorization-tokens.js";+import { connectionAuthorizationScope } from "#runtime/connections/instance-identity.js";import { principalKey, resolveConnectionPrincipal } from "#runtime/connections/principal.js";import { resolveConnectionAuthorization } from "#runtime/connections/resolve-authorization.js";import {@@ -157,10 +159,11 @@ async function completePendingAuthorizations(registry: ConnectionRegistry,connections: readonly ResolvedConnectionDefinition[],): Promise<Set<string>> {+ assertPendingConnectionAuthorizationInstances(registry);const ctx = loadContext();const completed = new Set<string>();for (const conn of connections) {- const result = consumeAuthorizationResult(conn.connectionName);+ const result = consumeAuthorizationResult(conn.connectionName, conn.instanceId);if (!result) continue;const auth = await resolveInteractiveAuth(registry, conn.connectionName);if (!auth) continue;@@ -174,7 +177,7 @@ async function completePendingAuthorizations(resume: result.resume,callback: result.callback,});- writeCachedToken(ctx, conn.connectionName, principalKey(principal), token);+ writeCachedToken(ctx, connectionAuthorizationScope(conn), principalKey(principal), token);completed.add(conn.connectionName);}return completed;@@ -252,6 +255,7 @@ async function executeConnectionSearch(name: conn.connectionName,challenge: stampChallengeDisplayName(challenge, auth),hookUrl: callbackUrl,+ instanceId: conn.instanceId,principal,resume,});@@ -387,13 +391,14 @@ async function executeDiscoveredConnectionTool(const conn = registry.getConnections().find((candidate) => candidate.connectionName === connectionName);+ assertPendingConnectionAuthorizationInstances(registry);const interactiveAuth = (await resolveInteractiveAuth(registry, connectionName)) as| InteractiveAuthorizationDefinition<JsonValue>| undefined;let justCompletedAuth = false;if (interactiveAuth) {- const authResult = consumeAuthorizationResult(connectionName);+ const authResult = consumeAuthorizationResult(connectionName, conn?.instanceId);if (authResult) {justCompletedAuth = true;const ctx = loadContext();@@ -406,7 +411,12 @@ async function executeDiscoveredConnectionTool(resume: authResult.resume,callback: authResult.callback,});- writeCachedToken(ctx, connectionName, principalKey(principal), token);+ writeCachedToken(+ ctx,+ conn === undefined ? connectionName : connectionAuthorizationScope(conn),+ principalKey(principal),+ token,+ );}}@@ -444,6 +454,7 @@ async function executeDiscoveredConnectionTool(name: connectionName,challenge: stampChallengeDisplayName(challenge, interactiveAuth),hookUrl: callbackUrl,+ instanceId: conn?.instanceId,principal,resume,},@@ -451,6 +462,19 @@ async function executeDiscoveredConnectionTool(}}+function assertPendingConnectionAuthorizationInstances(registry: ConnectionRegistry): void {+ const connections = new Map(+ registry.getConnections().map((connection) => [connection.connectionName, connection]),+ );+ for (const result of getAuthorizationResults()) {+ if (result.instanceId === undefined) continue;+ if (connections.get(result.name)?.instanceId === result.instanceId) continue;+ throw new Error(+ `Authorization for "${result.name}" cannot complete because its resolved connection changed while sign-in was pending. Start sign-in again.`,+ );+ }+}+async function requestDiscoveredConnectionToolApproval(closure: JsonObject,context: ApprovalContext,@@ -479,7 +503,10 @@ export async function resolveConnectionSearchDynamicTools() {const connections = registry.getConnections();const connectionNames = connections.map((c) => c.connectionName);- const discovered = loadContext().get(ConnectionSearchResultsKey) ?? [];+ const activeConnectionNames = new Set(connectionNames);+ const discovered = (loadContext().get(ConnectionSearchResultsKey) ?? []).filter((result) =>+ activeConnectionNames.has(result.connection),+ );const tools: Record<string, object> = {};diff --git a/packages/eve/src/execution/workflow-steps.ts b/packages/eve/src/execution/workflow-steps.tsindex d85eaf1f5..0ad164d8c 100644--- a/packages/eve/src/execution/workflow-steps.ts+++ b/packages/eve/src/execution/workflow-steps.ts@@ -51,7 +51,7 @@ import { setChannelContext } from "#execution/channel-context.js";import { observeSessionActivity } from "#execution/session-activity-projection.js";import { hasPendingInputBatch } from "#harness/input-requests.js";import { activeTurnId } from "#harness/active-turn-id.js";-import { coalesceTurnInputs, normalizeUserContent } from "#harness/messages.js";+import { coalesceTurnInputs } from "#harness/messages.js";import {getRuntimeActionKeysFromWorkflowInterrupt,isWorkflowRuntimeActionInterrupt,@@ -102,8 +102,9 @@ import { hydrateDurableSession, refreshSessionFromTurnAgent } from "#execution/simport { createExecutionHistoryView } from "#execution/history-view.js";import { resolveRuntimeCompiledArtifactsVersionedCacheKey } from "#runtime/cache-key.js";import { createWorkflowRuntime } from "#execution/workflow-runtime.js";+import { bindDynamicConnections } from "#execution/dynamic-connections.js";+import { preserveCancelledTurnMessage } from "#execution/cancelled-turn-message.js";import { TASK_UPDATE_TOOL_NAME } from "#tools/framework/task-contract.js";-import { stageAttachmentsToSandbox } from "#harness/attachment-staging.js";const TASK_DONE_WITH_PENDING_INPUT_ERROR_MESSAGE ="Task mode cannot complete while input requests remain pending.";@@ -322,6 +323,7 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu}const hookRegistry = bundle.hookRegistry;+ const dynamicConnections = bindDynamicConnections(ctx, bundle.resolvedAgent);const dynamicInstructionsResolvers = bundle.resolvedAgent.dynamicInstructionsResolvers ?? [];const dynamicSkillResolvers = bundle.resolvedAgent.dynamicSkillResolvers ?? [];const dynamicSubagentResolvers = bundle.subagentRegistry.dynamicResolvers ?? [];@@ -417,6 +419,7 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu},});}+ await dynamicConnections.dispatch(emitted);await dispatchDynamicSubagentEvent({ctx,resolvers: dynamicSubagentResolvers,@@ -459,6 +462,11 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResumode,session: enrichedSession,});+ await dynamicConnections.rehydrate(+ initialEmissionState,+ runtimeIdentity,+ isHarnessBetweenTurns(schemaSession),+ );if (completedAuths) {let emissionState = getHarnessEmissionState(schemaSession.state);if (isHarnessBetweenTurns(schemaSession)) {@@ -686,13 +694,3 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResusessionState: nextState,};}--async function preserveCancelledTurnMessage(- session: HarnessSession,- input: StepInput | undefined,-): Promise<HarnessSession> {- const message = normalizeUserContent(input?.message);- if (message === undefined) return session;- const content = await stageAttachmentsToSandbox(message);- return { ...session, history: [...session.history, { content, role: "user" }] };-}diff --git a/packages/eve/src/harness/authorization.test.ts b/packages/eve/src/harness/authorization.test.tsindex 7b75ca5f2..267f60868 100644--- a/packages/eve/src/harness/authorization.test.ts+++ b/packages/eve/src/harness/authorization.test.ts@@ -64,6 +64,37 @@ describe("authorization callback results", () => {expect(consumeAuthorizationResult("linear")).toBeUndefined();});});++ it("does not confuse same-named tool and connection callbacks", () => {+ const ctx = new ContextContainer();+ ctx.set(PendingAuthorizationResultKey, [+ {+ callback: { method: "GET", params: { code: "tool-code" } },+ hookUrl: "https://agent.example.com/tool",+ name: "linear",+ principal: { type: "app" },+ },+ {+ callback: { method: "GET", params: { code: "connection-code" } },+ hookUrl: "https://agent.example.com/connection",+ instanceId: "connection:linear-account",+ name: "linear",+ principal: { type: "app" },+ },+ ]);++ contextStorage.run(ctx, () => {+ expect(() => consumeAuthorizationResult("linear", "connection:other-account")).toThrow(+ "resolved connection changed while sign-in was pending",+ );+ expect(consumeAuthorizationResult("linear")).toMatchObject({+ callback: { params: { code: "tool-code" } },+ });+ expect(consumeAuthorizationResult("linear", "connection:linear-account")).toMatchObject({+ callback: { params: { code: "connection-code" } },+ });+ });+ });});function candidateChallenge(name: string, candidateId: string) {diff --git a/packages/eve/src/harness/authorization.ts b/packages/eve/src/harness/authorization.tsindex 5d0ca2b96..1511f65d1 100644--- a/packages/eve/src/harness/authorization.ts+++ b/packages/eve/src/harness/authorization.ts@@ -52,6 +52,8 @@ export interface AuthorizationChallenge {/** Opaque identity of this exact authorization attempt. */readonly attemptId?: string;readonly candidateId?: string;+ /** Opaque resolved connection identity; omitted for tool-hosted authorization. */+ readonly instanceId?: string;readonly name: string;readonly challenge: ConnectionAuthorizationChallenge;readonly hookUrl: string;@@ -80,6 +82,7 @@ export interface AuthorizationPendingModelOutput {export interface AuthorizationResult {readonly attemptId?: string;+ readonly instanceId?: string;readonly resume?: JsonValue;readonly callback: AuthorizationCallback;readonly hookUrl: string;@@ -104,12 +107,12 @@ export function requestAuthorization(}/**- * Returns a copy of `signal` with each challenge's `resume` value stripped.+ * Returns a model-safe copy of `signal` with runtime-only challenge state stripped.** Used for the copy the AI SDK records as a tool output. The shape stays a* valid {@link AuthorizationSignal} so every `isAuthorizationSignal` consumer- * still detects it; the park detector reads the full challenges from the- * harness's out-of-band stash.+ * still detects it; the park detector reads the full resume, principal, and+ * resolved-instance state from the harness's out-of-band stash.*/export function redactSignalResume(signal: AuthorizationSignal): AuthorizationSignal {return requestAuthorization(@@ -137,6 +140,11 @@ export function getAuthorizationResult(name?: string): AuthorizationResult | undreturn results.find((r) => r.name === name);}+/** Returns every callback result available to the active step. */+export function getAuthorizationResults(): readonly NamedAuthorizationResult[] {+ return loadContext().get(PendingAuthorizationResultKey) ?? [];+}+/*** Removes and returns one authorization callback result.*@@ -144,12 +152,26 @@ export function getAuthorizationResult(name?: string): AuthorizationResult | und* before completion prevents a failed or replayed callback from poisoning* every later tool call in the same step.*/-export function consumeAuthorizationResult(name: string): AuthorizationResult | undefined {+export function consumeAuthorizationResult(+ name: string,+ instanceId?: string,+): AuthorizationResult | undefined {const ctx = loadContext();const results = ctx.get(PendingAuthorizationResultKey);if (!results || results.length === 0) return undefined;- const index = results.findIndex((result) => result.name === name);+ const index = results.findIndex(+ (result) => result.name === name && result.instanceId === instanceId,+ );+ if (+ index === -1 &&+ instanceId !== undefined &&+ results.some((result) => result.name === name && result.instanceId !== undefined)+ ) {+ throw new Error(+ `Authorization for "${name}" cannot complete because its resolved connection changed while sign-in was pending. Start sign-in again.`,+ );+ }if (index === -1) return undefined;const result = results[index]!;diff --git a/packages/eve/src/harness/tool-interrupts.test.ts b/packages/eve/src/harness/tool-interrupts.test.tsindex ff91ab659..418e879dd 100644--- a/packages/eve/src/harness/tool-interrupts.test.ts+++ b/packages/eve/src/harness/tool-interrupts.test.ts@@ -21,6 +21,7 @@ function signalWithVerifier(): AuthorizationSignal {return requestAuthorization([{attemptId: "attempt-linear",+ instanceId: "connection:linear-account",name: "linear",challenge: { url: "https://idp.example/auth" },hookUrl: "https://app.example/cb",@@ -64,7 +65,7 @@ describe("authorizationPendingAsJsonObject", () => {});describe("redactSignalResume", () => {- it("strips resume but keeps the signal shape + other challenge fields", () => {+ it("strips runtime-only state but keeps the model-safe challenge fields", () => {const redacted = redactSignalResume(signalWithVerifier());expect(isAuthorizationSignal(redacted)).toBe(true);expect(redacted.challenges[0]).toEqual({@@ -73,6 +74,7 @@ describe("redactSignalResume", () => {challenge: { url: "https://idp.example/auth" },hookUrl: "https://app.example/cb",});+ expect(redacted.challenges[0]).not.toHaveProperty("instanceId");expect(redacted.challenges[0]).not.toHaveProperty("resume");expect(redacted.challenges[0]).not.toHaveProperty("principal");});diff --git a/packages/eve/src/internal/authored-definition/connection.test.ts b/packages/eve/src/internal/authored-definition/connection.test.tsindex afeeeca49..1d7eac241 100644--- a/packages/eve/src/internal/authored-definition/connection.test.ts+++ b/packages/eve/src/internal/authored-definition/connection.test.ts@@ -34,6 +34,15 @@ describe("normalizeMcpClientConnectionDefinition", () => {expect(typeof authProvider(result.auth).getToken).toBe("function");});+ it("preserves a stable connection instance key", () => {+ const result = normalizeMcpClientConnectionDefinition(+ validInput({ instanceKey: "account-123" }),+ MSG,+ );++ expect(result.instanceKey).toBe("account-123");+ });+it("preserves the author's getToken reference", () => {const getToken = async () => ({ token: "x" });const result = normalizeMcpClientConnectionDefinition(@@ -190,6 +199,14 @@ describe("normalizeMcpClientConnectionDefinition", () => {});});+ describe("instance key validation", () => {+ it("rejects an empty connection instance key", () => {+ expect(() =>+ normalizeMcpClientConnectionDefinition(validInput({ instanceKey: "" }), MSG),+ ).toThrow(/instanceKey/);+ });+ });+describe("auth validation", () => {it("accepts missing auth when headers are present", () => {const result = normalizeMcpClientConnectionDefinition(diff --git a/packages/eve/src/internal/authored-definition/connection.ts b/packages/eve/src/internal/authored-definition/connection.tsindex 5e903e2d4..dbe54cd47 100644--- a/packages/eve/src/internal/authored-definition/connection.ts+++ b/packages/eve/src/internal/authored-definition/connection.ts@@ -19,6 +19,7 @@ const KNOWN_TOP_LEVEL_KEYS = ["auth","description","headers",+ "instanceKey","toolCall","tools","url",@@ -29,6 +30,7 @@ const KNOWN_OPENAPI_TOP_LEVEL_KEYS = ["baseUrl","description","headers",+ "instanceKey","operations","spec","toolCall",@@ -68,6 +70,7 @@ export function normalizeMcpClientConnectionDefinition(validateUrl(record, message);validateDescription(record, message);+ validateInstanceKey(record, message);const authorization = normalizeAuthorization(record, message);const headers = normalizeHeaders(record, message);@@ -83,11 +86,17 @@ export function normalizeMcpClientConnectionDefinition(}}- const result: McpClientConnectionDefinition = {+ const result: {+ -readonly [K in keyof McpClientConnectionDefinition]: McpClientConnectionDefinition[K];+ } = {description: record.description as string,url: record.url as string,};+ if (record.instanceKey !== undefined) {+ result.instanceKey = record.instanceKey as string;+ }+if (authorization !== undefined) {result.auth = authorization;}@@ -171,6 +180,7 @@ export function normalizeOpenApiConnectionDefinition(validateSpec(record, message);validateBaseUrl(record, message);validateDescription(record, message);+ validateInstanceKey(record, message);const authorization = normalizeAuthorization(record, message);const headers = normalizeHeaders(record, message);@@ -197,6 +207,10 @@ export function normalizeOpenApiConnectionDefinition(result.baseUrl = record.baseUrl as string;}+ if (record.instanceKey !== undefined) {+ result.instanceKey = record.instanceKey as string;+ }+if (authorization !== undefined) {result.auth = authorization;}@@ -273,6 +287,13 @@ function validateDescription(record: Record<string, unknown>, message: string):}}+function validateInstanceKey(record: Record<string, unknown>, message: string): void {+ if (record.instanceKey === undefined) return;+ if (typeof record.instanceKey !== "string" || record.instanceKey.length === 0) {+ throw new Error(`${message} The "instanceKey" field must be a non-empty string.`);+ }+}+function normalizeAuthorization(record: Record<string, unknown>,message: string,diff --git a/packages/eve/src/internal/authored-definition/openapi-connection.test.ts b/packages/eve/src/internal/authored-definition/openapi-connection.test.tsindex aa2885620..f13c4457c 100644--- a/packages/eve/src/internal/authored-definition/openapi-connection.test.ts+++ b/packages/eve/src/internal/authored-definition/openapi-connection.test.ts@@ -33,6 +33,15 @@ describe("normalizeOpenApiConnectionDefinition", () => {expect(result.description).toBe("A test OpenAPI connection.");});+ it("preserves a stable connection instance key", () => {+ const result = normalizeOpenApiConnectionDefinition(+ validInput({ instanceKey: "account-123" }),+ MSG,+ );++ expect(result.instanceKey).toBe("account-123");+ });+it("accepts an inline spec object", () => {const spec = { openapi: "3.0.0", paths: {} };const result = normalizeOpenApiConnectionDefinition(validInput({ spec }), MSG);@@ -70,6 +79,12 @@ describe("normalizeOpenApiConnectionDefinition", () => {});describe("validation", () => {+ it("rejects an empty connection instance key", () => {+ expect(() =>+ normalizeOpenApiConnectionDefinition(validInput({ instanceKey: "" }), MSG),+ ).toThrow(/instanceKey/);+ });+it("accepts an omitted baseUrl (falls back to the spec servers at runtime)", () => {const result = normalizeOpenApiConnectionDefinition(validInput({ baseUrl: undefined }), MSG);diff --git a/packages/eve/src/public/connections/index.ts b/packages/eve/src/public/connections/index.tsindex 13597de94..7fcaed163 100644--- a/packages/eve/src/public/connections/index.ts+++ b/packages/eve/src/public/connections/index.ts@@ -17,6 +17,15 @@ export type {} from "#shared/connection-types.js";export { defineInteractiveAuthorization } from "#shared/connection-types.js";export type { JsonValue } from "#public/types/json.js";+export {+ defineDynamic,+ type DynamicConnectionDefinition,+ type DynamicConnectionEvents,+ type DynamicConnectionResolveContext,+ type DynamicConnectionResult,+ type DynamicConnectionSet,+} from "#public/definitions/connections/dynamic.js";+export type { DynamicResolveContext, DynamicSentinel } from "#dynamic/definition.js";export {defineMcpClientConnection,type McpClientConnectionDefinition,diff --git a/packages/eve/src/public/definitions/connections/dynamic.test.ts b/packages/eve/src/public/definitions/connections/dynamic.test.tsnew file mode 100644index 000000000..7e0fcf3e1--- /dev/null+++ b/packages/eve/src/public/definitions/connections/dynamic.test.ts@@ -0,0 +1,19 @@+import { describe, expect, it } from "vitest";++import { defineDynamic } from "#public/definitions/connections/dynamic.js";+import { defineMcpClientConnection } from "#public/definitions/connections/mcp.js";++describe("defineDynamic connections", () => {+ it("creates the shared dynamic sentinel", () => {+ const handler = () =>+ defineMcpClientConnection({+ description: "Current account.",+ url: "https://mcp.example.com/current",+ });++ expect(defineDynamic({ events: { "session.started": handler } })).toMatchObject({+ events: { "session.started": handler },+ kind: "eve:dynamic",+ });+ });+});diff --git a/packages/eve/src/public/definitions/connections/dynamic.ts b/packages/eve/src/public/definitions/connections/dynamic.tsnew file mode 100644index 000000000..5bdf3fb34--- /dev/null+++ b/packages/eve/src/public/definitions/connections/dynamic.ts@@ -0,0 +1,46 @@+import { stampDefinitionKey } from "#internal/authored-definition/source-identity.js";+import type { McpClientConnectionDefinition } from "#public/definitions/connections/mcp.js";+import type { OpenAPIConnectionDefinition } from "#public/definitions/connections/openapi.js";+import {+ DYNAMIC_SENTINEL_KIND,+ type DynamicResolveContext,+ type DynamicSentinel,+} from "#dynamic/definition.js";+import type { ExactDefinition } from "#public/definitions/exact.js";++/** One connection returned by a dynamic connection resolver. */+export type DynamicConnectionDefinition =+ | McpClientConnectionDefinition+ | OpenAPIConnectionDefinition;++/** A runtime connection set whose keys become connection names. */+export type DynamicConnectionSet = Readonly<Record<string, DynamicConnectionDefinition>>;++/** Supported return value for a dynamic connection resolver. */+export type DynamicConnectionResult = DynamicConnectionDefinition | DynamicConnectionSet | null;++/** Trusted session identity and minimal channel metadata available to connection resolvers. */+export interface DynamicConnectionResolveContext {+ readonly session: DynamicResolveContext["session"];+ readonly channel: Pick<DynamicResolveContext["channel"], "kind">;+}++/** Session and turn handlers supported by dynamic connections. */+export type DynamicConnectionEvents = {+ readonly [K in "session.started" | "turn.started"]?: (+ event: unknown,+ ctx: DynamicConnectionResolveContext,+ ) => DynamicConnectionResult | Promise<DynamicConnectionResult>;+};++/** Defines a runtime connection resolver for session and turn boundaries. */+export function defineDynamic<const TEvents extends DynamicConnectionEvents>(definition: {+ readonly events: ExactDefinition<TEvents, DynamicConnectionEvents>;+}): DynamicSentinel<DynamicConnectionResult> {+ const sentinel = {+ kind: DYNAMIC_SENTINEL_KIND,+ events: definition.events,+ } as DynamicSentinel<DynamicConnectionResult>;+ stampDefinitionKey(sentinel, `dynamic-connections:${Object.keys(definition.events).join(",")}`);+ return sentinel;+}diff --git a/packages/eve/src/public/definitions/connections/mcp.ts b/packages/eve/src/public/definitions/connections/mcp.tsindex 020c8d004..59f8198e3 100644--- a/packages/eve/src/public/definitions/connections/mcp.ts+++ b/packages/eve/src/public/definitions/connections/mcp.ts@@ -52,6 +52,14 @@ export interface McpClientConnectionDefinition {* Optional when `headers` is provided for non-Bearer auth schemes.*/auth?: ConnectionAuthDefinition;+ /**+ * Stable, non-secret identity for the resolved connection instance.+ *+ * Authenticated dynamic connections must set this to an account or tenant+ * identifier that changes whenever the endpoint or auth provider changes.+ * eve hashes the value before storing it in durable authorization state.+ */+ readonly instanceKey?: string;/*** Optional per-connection approval gate for connection tool calls.*diff --git a/packages/eve/src/public/definitions/connections/openapi.ts b/packages/eve/src/public/definitions/connections/openapi.tsindex defa56101..01634c0b2 100644--- a/packages/eve/src/public/definitions/connections/openapi.ts+++ b/packages/eve/src/public/definitions/connections/openapi.ts@@ -75,6 +75,14 @@ export interface OpenAPIConnectionDefinition {* Optional when `headers` is provided for non-Bearer auth schemes.*/auth?: ConnectionAuthDefinition;+ /**+ * Stable, non-secret identity for the resolved connection instance.+ *+ * Authenticated dynamic connections must set this to an account or tenant+ * identifier that changes whenever the endpoint or auth provider changes.+ * eve hashes the value before storing it in durable authorization state.+ */+ readonly instanceKey?: string;/*** Optional per-connection approval gate for connection tool calls.*diff --git a/packages/eve/src/public/definitions/connections/protocol.ts b/packages/eve/src/public/definitions/connections/protocol.tsindex 6ad6e8344..515d12474 100644--- a/packages/eve/src/public/definitions/connections/protocol.ts+++ b/packages/eve/src/public/definitions/connections/protocol.ts@@ -24,11 +24,17 @@ export function stampConnectionProtocol(definition: object, protocol: Connection* marker existed continue to compile as MCP connections.*/export function readConnectionProtocol(definition: unknown): ConnectionProtocol {- if (typeof definition === "object" && definition !== null && PROTOCOL_KEY in definition) {- const stamped = (definition as Record<symbol, ConnectionProtocol | undefined>)[PROTOCOL_KEY];- if (stamped !== undefined) {- return stamped;- }+ return readStampedConnectionProtocol(definition) ?? "mcp";+}++/**+ * Reads the protocol marker without applying the legacy MCP fallback.+ * Dynamic connection resolvers use this to distinguish one branded+ * connection definition from a map of branded definitions.+ */+export function readStampedConnectionProtocol(definition: unknown): ConnectionProtocol | undefined {+ if (typeof definition !== "object" || definition === null || !(PROTOCOL_KEY in definition)) {+ return undefined;}- return "mcp";+ return (definition as Record<symbol, ConnectionProtocol | undefined>)[PROTOCOL_KEY];}diff --git a/packages/eve/src/runtime/connections/authorization-tokens.ts b/packages/eve/src/runtime/connections/authorization-tokens.tsindex cfae84f94..ffcba8428 100644--- a/packages/eve/src/runtime/connections/authorization-tokens.ts+++ b/packages/eve/src/runtime/connections/authorization-tokens.ts@@ -1,8 +1,9 @@/*** Per-step cache of resolved connection authorization tokens.*- * Keyed by `(connectionName, principalKey)` so two users on the same- * session never share a user-scoped token. Stored as a virtual+ * Keyed by `(authorizationScope, principalKey)` so two users on the same+ * session never share a user-scoped token and two resolved connection+ * instances never share credentials. Stored as a virtual* context value and wiped between workflow steps, so bearer tokens* are never serialized into the durable step payload. Cross-step* reuse is delegated to the upstream authorization provider (for@@ -18,12 +19,12 @@ import { ContextKey } from "#context/key.js";import type { TokenResult } from "#shared/connection-types.js";/**- * Inner map of `principalKey` → {@link TokenResult} for one connection.+ * Inner map of `principalKey` → {@link TokenResult} for one authorization scope.*/type PrincipalTokenCache = Readonly<Record<string, TokenResult>>;/**- * Virtual context key mapping connection name to a per-principal+ * Virtual context key mapping authorization scope to a per-principal* {@link TokenResult} cache.** The principal sub-key is produced by@@ -37,16 +38,16 @@ export const ConnectionAuthorizationTokensKey = new ContextKey</*** Returns the cached {@link TokenResult} for- * `(connectionName, principalKey)` when the entry is still valid+ * `(authorizationScope, principalKey)` when the entry is still valid* (not expired). Expired entries are treated as a cache miss so* callers re-run the authorization flow.*/export function readCachedToken(ctx: AlsContext,- connectionName: string,+ authorizationScope: string,principalKey: string,): TokenResult | undefined {- const entry = ctx.get(ConnectionAuthorizationTokensKey)?.[connectionName]?.[principalKey];+ const entry = ctx.get(ConnectionAuthorizationTokensKey)?.[authorizationScope]?.[principalKey];if (entry === undefined) return undefined;if (entry.expiresAt !== undefined && entry.expiresAt <= Date.now()) {return undefined;@@ -56,28 +57,28 @@ export function readCachedToken(/*** Persists a freshly resolved {@link TokenResult} on the cache under- * `(connectionName, principalKey)`. Existing entries for other- * principals on the same connection are left in place.+ * `(authorizationScope, principalKey)`. Existing entries for other+ * principals in the same scope are left in place.** Writes to the virtual context slot so the bearer is never serialized* into the durable step payload. See the module docblock.*/export function writeCachedToken(ctx: AlsContext,- connectionName: string,+ authorizationScope: string,principalKey: string,token: TokenResult,): void {const existing = ctx.get(ConnectionAuthorizationTokensKey) ?? {};- const perConnection = existing[connectionName] ?? {};+ const perScope = existing[authorizationScope] ?? {};asContainer(ctx).setVirtualContext(ConnectionAuthorizationTokensKey, {...existing,- [connectionName]: { ...perConnection, [principalKey]: token },+ [authorizationScope]: { ...perScope, [principalKey]: token },});}/**- * Drops the cached {@link TokenResult} for `(connectionName, principalKey)`,+ * Drops the cached {@link TokenResult} for `(authorizationScope, principalKey)`,* if present. Used when the remote server rejects an already-resolved* bearer (HTTP 401) so the subsequent re-authorization attempt does not* re-read the stale token from the per-step cache. No-op when nothing is@@ -85,18 +86,18 @@ export function writeCachedToken(*/export function evictCachedToken(ctx: AlsContext,- connectionName: string,+ authorizationScope: string,principalKey: string,): void {const existing = ctx.get(ConnectionAuthorizationTokensKey);- const perConnection = existing?.[connectionName];- if (existing === undefined || perConnection === undefined) return;- if (perConnection[principalKey] === undefined) return;+ const perScope = existing?.[authorizationScope];+ if (existing === undefined || perScope === undefined) return;+ if (perScope[principalKey] === undefined) return;- const { [principalKey]: _removed, ...rest } = perConnection;+ const { [principalKey]: _removed, ...rest } = perScope;asContainer(ctx).setVirtualContext(ConnectionAuthorizationTokensKey, {...existing,- [connectionName]: rest,+ [authorizationScope]: rest,});}diff --git a/packages/eve/src/runtime/connections/instance-identity.ts b/packages/eve/src/runtime/connections/instance-identity.tsnew file mode 100644index 000000000..c23dc5b61--- /dev/null+++ b/packages/eve/src/runtime/connections/instance-identity.ts@@ -0,0 +1,31 @@+import { createHash } from "node:crypto";++import type { ConnectionProtocol } from "#shared/connection-types.js";+import type { ResolvedConnectionDefinition } from "#runtime/types.js";++/** Builds the opaque, reconstruction-stable identity for one resolved connection instance. */+export function createConnectionInstanceId(input: {+ readonly connectionName: string;+ readonly instanceKey?: string;+ readonly protocol: ConnectionProtocol;+ readonly sourceId: string;+ readonly url: string;+}): string {+ const digest = createHash("sha256")+ .update(+ JSON.stringify([+ input.sourceId,+ input.connectionName,+ input.protocol,+ input.url,+ input.instanceKey ?? "",+ ]),+ )+ .digest("base64url");+ return `connection:${digest}`;+}++/** Returns the cache and callback scope for one resolved connection. */+export function connectionAuthorizationScope(connection: ResolvedConnectionDefinition): string {+ return connection.instanceId ?? connection.connectionName;+}diff --git a/packages/eve/src/runtime/connections/mcp-client.test.ts b/packages/eve/src/runtime/connections/mcp-client.test.tsindex 0ac4ed4a9..157934fc1 100644--- a/packages/eve/src/runtime/connections/mcp-client.test.ts+++ b/packages/eve/src/runtime/connections/mcp-client.test.ts@@ -764,6 +764,30 @@ describe("resolveHeaders with an active context (principal resolution + cache)",expect(cached).toEqual({ linear: { "user:idp:alice": { token: "t-1" } } });});+ it("isolates cached tokens for same-named resolved connection instances", async () => {+ const ctx = ctxWithAuth(userAuth("alice"));+ const instanceA = makeConnection({+ authorization: staticToken("token-a"),+ connectionName: "linear",+ instanceId: "instance-a",+ });+ const instanceB = makeConnection({+ authorization: staticToken("token-b"),+ connectionName: "linear",+ instanceId: "instance-b",+ });++ await contextStorage.run(ctx, async () => {+ await expect(resolveHeaders(instanceA)).resolves.toEqual({ Authorization: "Bearer token-a" });+ await expect(resolveHeaders(instanceB)).resolves.toEqual({ Authorization: "Bearer token-b" });+ });++ expect(ctx.get(ConnectionAuthorizationTokensKey)).toEqual({+ "instance-a": { app: { token: "token-a" } },+ "instance-b": { app: { token: "token-b" } },+ });+ });+it("uses separate cache slots for two users on the same connection", async () => {const tokens: Record<string, string> = {alice: "alice-token",diff --git a/packages/eve/src/runtime/connections/mcp-client.ts b/packages/eve/src/runtime/connections/mcp-client.tsindex a7b1d325f..474e9a18a 100644--- a/packages/eve/src/runtime/connections/mcp-client.ts+++ b/packages/eve/src/runtime/connections/mcp-client.ts@@ -258,6 +258,7 @@ export class McpConnectionClient implements ConnectionClient {await evictScopedToken({authorization,connection: { url: this.#connection.url },+ instanceId: this.#connection.instanceId,scope: this.#connection.connectionName,});}@@ -409,7 +410,7 @@ export async function resolveHeaders(/*** Resolves a connection's bearer token via the shared scoped-token path,- * keyed by the connection name. See+ * keyed by the resolved connection instance. See* {@link resolveScopedToken} for the cache and principal semantics.*/async function resolveToken(@@ -419,6 +420,7 @@ async function resolveToken(return await resolveScopedToken({authorization,connection: { url: connection.url },+ instanceId: connection.instanceId,scope: connection.connectionName,});}diff --git a/packages/eve/src/runtime/connections/registry.ts b/packages/eve/src/runtime/connections/registry.tsindex a1853b3ab..bcb67c436 100644--- a/packages/eve/src/runtime/connections/registry.ts+++ b/packages/eve/src/runtime/connections/registry.ts@@ -15,11 +15,68 @@ import type { ConnectionRegistry } from "#runtime/connections/registry-types.js"export class ConnectionRegistryImpl implements ConnectionRegistry {#clients = new Map<string, ConnectionClient>();#connections: readonly ResolvedConnectionDefinition[];+ readonly #staticConnections: readonly ResolvedConnectionDefinition[];+ #sessionDynamicConnections = new Map<string, readonly ResolvedConnectionDefinition[]>();+ #turnDynamicConnections = new Map<string, readonly ResolvedConnectionDefinition[]>();constructor(connections: readonly ResolvedConnectionDefinition[]) {+ this.#staticConnections = connections;this.#connections = connections;}+ /** Replaces one complete dynamic scope and closes clients whose definition changed. */+ async replaceDynamicConnections(+ scope: "session" | "turn",+ connectionsByResolver: ReadonlyMap<string, readonly ResolvedConnectionDefinition[]>,+ ): Promise<void> {+ const session =+ scope === "session" ? new Map(connectionsByResolver) : this.#sessionDynamicConnections;+ const turn = scope === "turn" ? new Map(connectionsByResolver) : this.#turnDynamicConnections;+ const next = this.#buildEffectiveConnections(session, turn);+ const previousByName = new Map(+ this.#connections.map((connection) => [connection.connectionName, connection]),+ );+ const nextByName = new Map(next.map((connection) => [connection.connectionName, connection]));+ const staleClients: ConnectionClient[] = [];++ for (const [name, client] of this.#clients) {+ if (previousByName.get(name) === nextByName.get(name)) continue;+ this.#clients.delete(name);+ staleClients.push(client);+ }++ this.#sessionDynamicConnections = session;+ this.#turnDynamicConnections = turn;+ this.#connections = next;+ await Promise.allSettled(staleClients.map((client) => client.close()));+ }++ #buildEffectiveConnections(+ session: ReadonlyMap<string, readonly ResolvedConnectionDefinition[]>,+ turn: ReadonlyMap<string, readonly ResolvedConnectionDefinition[]>,+ ): readonly ResolvedConnectionDefinition[] {+ const effectiveResolvers = new Map(session);+ for (const [slug, definitions] of turn) effectiveResolvers.set(slug, definitions);++ const dynamicNames = new Map<string, string>();+ const connections = new Map(+ this.#staticConnections.map((connection) => [connection.connectionName, connection]),+ );+ for (const [resolverSlug, definitions] of effectiveResolvers) {+ for (const definition of definitions) {+ const previousOwner = dynamicNames.get(definition.connectionName);+ if (previousOwner !== undefined && previousOwner !== resolverSlug) {+ throw new Error(+ `Dynamic connection "${definition.connectionName}" from resolver "${resolverSlug}" collides with dynamic resolver "${previousOwner}". Namespace the map key manually.`,+ );+ }+ dynamicNames.set(definition.connectionName, resolverSlug);+ connections.set(definition.connectionName, definition);+ }+ }+ return [...connections.values()];+ }+/*** Returns the client for the named connection, creating it on first* access. The connection's `protocol` selects the client type.diff --git a/packages/eve/src/runtime/connections/scoped-authorization.ts b/packages/eve/src/runtime/connections/scoped-authorization.tsindex 67d1f9b13..83819b406 100644--- a/packages/eve/src/runtime/connections/scoped-authorization.ts+++ b/packages/eve/src/runtime/connections/scoped-authorization.ts@@ -2,9 +2,10 @@* Scope-parameterized authorization flow shared by MCP connections and* authored tools that declare `auth`.*- * A *scope* is the stable identifier the per-step token cache and the- * framework-owned callback URL are keyed by — a connection name for an- * MCP connection, a tool name for tool-hosted auth. Everything else+ * A *scope* names the framework-owned callback URL — a connection name for+ * an MCP connection, a tool name for tool-hosted auth. Connection-hosted+ * authorization also carries an opaque instance ID that keys its token cache+ * and pins callback completion to the exact resolved connection. Everything else* (principal resolution, the park/resume webhook dance, the loop guard)* is identical across both, so it lives here once instead of being* duplicated per caller.@@ -48,6 +49,8 @@ const LOCAL_HTTP_VERCEL_CONNECT_HOSTNAMES: ReadonlySet<string> = new Set(["127.0*/export interface ScopedAuthorization {readonly boundResponder?: SessionAuthContext;+ /** Opaque resolved instance identity for connection-hosted authorization. */+ readonly instanceId?: string;readonly scope: string;readonly authorization: Readonly<AuthorizationDefinition>;readonly connection: ConnectionAuthorizationContext;@@ -57,9 +60,10 @@ export interface ScopedAuthorization {* Resolves a bearer token for one scope, consulting the per-step token* cache before invoking the authored `getToken`.*- * The cache is keyed by `(scope, principalKey(principal))` so concurrent- * users on one session never alias onto each other's bearer. Outside a- * runtime scope the cache is unavailable, but `getToken` still runs with+ * The cache is keyed by `(instanceId ?? scope, principalKey(principal))` so+ * concurrent users and resolved connection instances never alias onto each+ * other's bearer. Outside a runtime scope the cache is unavailable, but+ * `getToken` still runs with* a framework-resolved principal so ad-hoc `"app"`-scoped use keeps* working; `"user"`-scoped strategies without a context fail fast inside* {@link resolveConnectionPrincipal}.@@ -69,6 +73,7 @@ export interface ScopedAuthorization {*/export async function resolveScopedToken(input: ScopedAuthorization): Promise<TokenResult> {const { scope, authorization, connection } = input;+ const cacheScope = input.instanceId ?? scope;// Reading `contextStorage.getStore()` directly keeps this the only// place that tolerates a missing context; authored code uses@@ -81,11 +86,11 @@ export async function resolveScopedToken(input: ScopedAuthorization): Promise<To}const key = principalKey(principal);- const cached = readCachedToken(ctx, scope, key);+ const cached = readCachedToken(ctx, cacheScope, key);if (cached !== undefined) return cached;const result = await authorization.getToken({ connection, principal });- writeCachedToken(ctx, scope, key, result);+ writeCachedToken(ctx, cacheScope, key, result);return result;}@@ -108,12 +113,13 @@ export async function resolveScopedToken(input: ScopedAuthorization): Promise<To*/export async function evictScopedToken(input: ScopedAuthorization): Promise<void> {const { scope, authorization, connection } = input;+ const cacheScope = input.instanceId ?? scope;const ctx = contextStorage.getStore();if (ctx === undefined) return;let principal;try {principal = resolveScopedPrincipal(input, ctx);- evictCachedToken(ctx, scope, principalKey(principal));+ evictCachedToken(ctx, cacheScope, principalKey(principal));} catch {// Eviction is best-effort; without a principal we can drop neither// cache layer, so bail rather than mask the authorization error.@@ -142,7 +148,7 @@ export async function completeScopedAuthorization(input: ScopedAuthorization): Pconst { scope, authorization, connection } = input;if (!supportsInteractiveAuthorization(authorization)) return false;- const result = consumeAuthorizationResult(scope);+ const result = consumeAuthorizationResult(scope, input.instanceId);if (result === undefined) return false;const interactive = authorization as InteractiveAuthorizationDefinition<JsonValue>;@@ -155,7 +161,7 @@ export async function completeScopedAuthorization(input: ScopedAuthorization): Presume: result.resume,callback: result.callback,});- writeCachedToken(ctx, scope, principalKey(principal), token);+ writeCachedToken(ctx, input.instanceId ?? scope, principalKey(principal), token);return true;}@@ -192,6 +198,7 @@ export async function startScopedAuthorization(attemptId: attempt.attemptId,challenge: stampChallengeDisplayName(challenge, authorization),hookUrl: callbackUrl,+ instanceId: input.instanceId,name: scope,principal,resume,diff --git a/packages/eve/src/runtime/resolve-agent.ts b/packages/eve/src/runtime/resolve-agent.tsindex 33fa7e418..6e69ae57b 100644--- a/packages/eve/src/runtime/resolve-agent.ts+++ b/packages/eve/src/runtime/resolve-agent.ts@@ -13,6 +13,7 @@ import { resolveChannelDefinition } from "#runtime/resolve-channel.js";export { ResolveAgentError } from "#runtime/resolve-helpers.js";import { resolveConnectionDefinition } from "#runtime/resolve-connection.js";+import { resolveDynamicConnectionDefinition } from "#runtime/resolve-dynamic-connection.js";import { resolveHookDefinition } from "#runtime/resolve-hook.js";import { createResolvedModuleSourceRef } from "#runtime/resolve-helpers.js";import { resolveSandboxDefinition } from "#runtime/resolve-sandbox.js";@@ -66,6 +67,11 @@ export async function resolveAgent(input: ResolveAgentInput): Promise<ResolvedAg),),);+ const resolvedDynamicConnectionResolvers = await Promise.all(+ input.manifest.dynamicConnections.map((definition) =>+ resolveDynamicConnectionDefinition(definition, input.moduleMap, input.nodeId),+ ),+ );const resolvedDynamicInstructionsResolvers = await Promise.all((input.manifest.dynamicInstructions ?? []).map((def) =>resolveDynamicInstructionsDefinition(def, input.moduleMap, input.nodeId),@@ -111,6 +117,7 @@ export async function resolveAgent(input: ResolveAgentInput): Promise<ResolvedAgconst resolvedAgent: ResolvedAgent = {channels: resolvedChannels,connections: resolvedConnections,+ dynamicConnectionResolvers: resolvedDynamicConnectionResolvers,workflowTool:input.manifest.workflowTool === undefined? undefineddiff --git a/packages/eve/src/runtime/resolve-connection.ts b/packages/eve/src/runtime/resolve-connection.tsindex 423e50a32..6760326a1 100644--- a/packages/eve/src/runtime/resolve-connection.ts+++ b/packages/eve/src/runtime/resolve-connection.ts@@ -2,6 +2,11 @@ import type { CompiledConnectionDefinition } from "#compiler/manifest.js";import type { CompiledModuleMap } from "#compiler/module-map.js";import { expectObjectRecord } from "#internal/authored-module.js";import type { ConnectionToolCallDefinition } from "#public/definitions/connections/tool-call.js";+import {+ normalizeMcpClientConnectionDefinition,+ normalizeOpenApiConnectionDefinition,+} from "#internal/authored-definition/connection.js";+import { readStampedConnectionProtocol } from "#public/definitions/connections/protocol.js";import {registerDefinitionSource,stampDefinitionKey,@@ -15,6 +20,8 @@ import type {import { normalizeAuthorizationSpec } from "#shared/validate-authorization.js";import { loadResolvedModuleExport, ResolveAgentError } from "#runtime/resolve-helpers.js";import type { ResolvedConnectionDefinition } from "#runtime/types.js";+import type { ModuleSourceRef } from "#shared/source-ref.js";+import { createConnectionInstanceId } from "#runtime/connections/instance-identity.js";/*** Resolves one compiled connection entry into a runtime-owned definition@@ -73,6 +80,7 @@ export async function resolveConnectionDefinition(description: string;exportName: typeof definition.exportName;headers?: Readonly<HeadersDefinition>;+ instanceId: string;logicalPath: string;protocol: ResolvedConnectionDefinition["protocol"];sourceId: string;@@ -86,6 +94,14 @@ export async function resolveConnectionDefinition(description: definition.description,exportName: definition.exportName,logicalPath: definition.logicalPath,+ instanceId: createConnectionInstanceId({+ connectionName: definition.connectionName,+ instanceKey:+ typeof resolvedRecord.instanceKey === "string" ? resolvedRecord.instanceKey : undefined,+ protocol: definition.protocol,+ sourceId: definition.sourceId,+ url: definition.url,+ }),protocol: definition.protocol,sourceId: definition.sourceId,sourceKind: "module",@@ -144,3 +160,94 @@ export async function resolveConnectionDefinition();}}++/** Resolves one branded connection returned by a dynamic connection handler. */+export function resolveDynamicConnectionValue(+ value: unknown,+ source: Readonly<ModuleSourceRef & { readonly connectionName: string }>,+): ResolvedConnectionDefinition {+ const protocol = readStampedConnectionProtocol(value);+ const message =+ `Dynamic connection "${source.connectionName}" from "${source.logicalPath}" must be created by ` ++ "defineMcpClientConnection() or defineOpenAPIConnection().";+ if (protocol === undefined) {+ throw new Error(message);+ }++ const sourceEntry = {+ kind: "connection",+ logicalPath: source.logicalPath,+ name: source.connectionName,+ } as const;+ const sourceKey = `dynamic-connection-source:${source.sourceId}:${source.connectionName}`;+ stampDefinitionKey(value as object, sourceKey);+ registerDefinitionSource(sourceKey, sourceEntry);++ if (protocol === "openapi") {+ const normalized = normalizeOpenApiConnectionDefinition(value, message);+ assertAuthenticatedDynamicInstanceKey(normalized.auth, normalized.instanceKey, message);+ return omitUndefined({+ approval: normalized.approval,+ authorization: normalized.auth as ResolvedConnectionDefinition["authorization"],+ connectionName: source.connectionName,+ description: normalized.description,+ exportName: source.exportName,+ headers: normalized.headers,+ instanceId: createConnectionInstanceId({+ connectionName: source.connectionName,+ instanceKey: normalized.instanceKey,+ protocol,+ sourceId: source.sourceId,+ url: normalized.baseUrl ?? "",+ }),+ logicalPath: source.logicalPath,+ protocol,+ sourceId: source.sourceId,+ sourceKind: "module" as const,+ spec: normalized.spec,+ toolCall: normalized.toolCall,+ tools: normalized.operations,+ url: normalized.baseUrl ?? "",+ });+ }++ const normalized = normalizeMcpClientConnectionDefinition(value, message);+ assertAuthenticatedDynamicInstanceKey(normalized.auth, normalized.instanceKey, message);+ return omitUndefined({+ approval: normalized.approval,+ authorization: normalized.auth as ResolvedConnectionDefinition["authorization"],+ connectionName: source.connectionName,+ description: normalized.description,+ exportName: source.exportName,+ headers: normalized.headers,+ instanceId: createConnectionInstanceId({+ connectionName: source.connectionName,+ instanceKey: normalized.instanceKey,+ protocol,+ sourceId: source.sourceId,+ url: normalized.url,+ }),+ logicalPath: source.logicalPath,+ protocol,+ sourceId: source.sourceId,+ sourceKind: "module" as const,+ toolCall: normalized.toolCall,+ tools: normalized.tools,+ url: normalized.url,+ });+}++function assertAuthenticatedDynamicInstanceKey(+ authorization: unknown,+ instanceKey: string | undefined,+ message: string,+): void {+ if (authorization === undefined || instanceKey !== undefined) return;+ throw new Error(+ `${message} Authenticated dynamic connections must set "instanceKey" to a stable, non-secret account or tenant identifier.`,+ );+}++function omitUndefined<T extends Record<string, unknown>>(value: T): T {+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined)) as T;+}diff --git a/packages/eve/src/runtime/resolve-dynamic-connection.test.ts b/packages/eve/src/runtime/resolve-dynamic-connection.test.tsnew file mode 100644index 000000000..62ea62c00--- /dev/null+++ b/packages/eve/src/runtime/resolve-dynamic-connection.test.ts@@ -0,0 +1,41 @@+import { describe, expect, it } from "vitest";++import {+ ROOT_COMPILED_AGENT_NODE_ID,+ type CompiledDynamicConnectionDefinition,+} from "#compiler/manifest.js";+import type { CompiledModuleMap } from "#compiler/module-map.js";+import { defineDynamic } from "#public/definitions/connections/dynamic.js";+import { resolveDynamicConnectionDefinition } from "#runtime/resolve-dynamic-connection.js";++describe("resolveDynamicConnectionDefinition", () => {+ it("reattaches the authored event handlers", async () => {+ const handler = () => null;+ const definition: CompiledDynamicConnectionDefinition = {+ eventNames: ["session.started"],+ logicalPath: "connections/accounts.ts",+ slug: "accounts",+ sourceId: "connections/accounts",+ sourceKind: "module",+ };+ const moduleMap: CompiledModuleMap = {+ nodes: {+ [ROOT_COMPILED_AGENT_NODE_ID]: {+ modules: {+ [definition.sourceId]: {+ default: defineDynamic({ events: { "session.started": handler } }),+ },+ },+ },+ },+ };++ await expect(+ resolveDynamicConnectionDefinition(definition, moduleMap, undefined),+ ).resolves.toMatchObject({+ eventNames: ["session.started"],+ events: { "session.started": handler },+ slug: "accounts",+ });+ });+});diff --git a/packages/eve/src/runtime/resolve-dynamic-connection.ts b/packages/eve/src/runtime/resolve-dynamic-connection.tsnew file mode 100644index 000000000..e794cd9bd--- /dev/null+++ b/packages/eve/src/runtime/resolve-dynamic-connection.ts@@ -0,0 +1,58 @@+import type { CompiledDynamicConnectionDefinition } from "#compiler/manifest.js";+import type { CompiledModuleMap } from "#compiler/module-map.js";+import { isDynamicSentinel } from "#dynamic/definition.js";+import { expectFunction, expectObjectRecord } from "#internal/authored-module.js";+import { loadResolvedModuleExport, ResolveAgentError } from "#runtime/resolve-helpers.js";+import type { ResolvedDynamicConnectionResolver } from "#runtime/types.js";+import { toErrorMessage } from "#shared/errors.js";++/** Reattaches live event handlers for one compiled dynamic connection source. */+export async function resolveDynamicConnectionDefinition(+ definition: CompiledDynamicConnectionDefinition,+ moduleMap: CompiledModuleMap,+ nodeId: string | undefined,+): Promise<ResolvedDynamicConnectionResolver> {+ try {+ const value = await loadResolvedModuleExport({+ definition,+ kindLabel: "dynamic connection",+ moduleMap,+ nodeId,+ });+ const record = expectObjectRecord(value, describe(definition, "to return an object"));+ if (!isDynamicSentinel(record)) {+ throw new Error(describe(definition, "to be created by defineDynamic()"));+ }+ const events = expectObjectRecord(+ record.events,+ describe(definition, "to provide an events object"),+ );+ const handlers: Record<string, Function> = {};+ for (const eventName of definition.eventNames) {+ handlers[eventName] = expectFunction(+ events[eventName],+ describe(definition, `to provide a handler for event "${eventName}"`),+ );+ }+ return {+ eventNames: [...definition.eventNames],+ events: handlers as ResolvedDynamicConnectionResolver["events"],+ exportName: definition.exportName,+ extensionNamespace: definition.extensionNamespace,+ logicalPath: definition.logicalPath,+ slug: definition.slug,+ sourceId: definition.sourceId,+ sourceKind: "module",+ };+ } catch (error) {+ if (error instanceof ResolveAgentError) throw error;+ throw new ResolveAgentError(+ `Failed to resolve dynamic connection from "${definition.logicalPath}": ${toErrorMessage(error)}`,+ { logicalPath: definition.logicalPath, sourceId: definition.sourceId },+ );+ }+}++function describe(definition: CompiledDynamicConnectionDefinition, predicate: string): string {+ return `Expected the dynamic connection export "${definition.exportName ?? "default"}" from "${definition.logicalPath}" ${predicate}.`;+}diff --git a/packages/eve/src/runtime/types.ts b/packages/eve/src/runtime/types.tsindex 1fb87d99a..6a7eccd8b 100644--- a/packages/eve/src/runtime/types.ts+++ b/packages/eve/src/runtime/types.ts@@ -106,6 +106,8 @@ export interface ResolvedConnectionDefinition extends ResolvedModuleSourceRef {readonly connectionName: string;readonly description: string;readonly headers?: Readonly<HeadersDefinition>;+ /** Opaque identity used to pin authorization and credential state to this resolved instance. */+ readonly instanceId?: string;readonly toolCall?: Readonly<ConnectionToolCallDefinition>;/*** Wire protocol. Selects the runtime client implementation. `tools`@@ -372,6 +374,17 @@ export interface ResolvedDynamicToolResolver extends Readonly<ModuleSourceRef> {readonly extensionNamespace?: string;}+/** Runtime resolver for dynamic connections declared in `agent/connections/`. */+export interface ResolvedDynamicConnectionResolver extends Readonly<ModuleSourceRef> {+ readonly slug: string;+ readonly eventNames: readonly string[];+ readonly events: Readonly<+ Record<string, (event: unknown, ctx: unknown) => unknown | Promise<unknown>>+ >;+ /** Map results from extensions receive this mount namespace. */+ readonly extensionNamespace?: string;+}+export type ResolvedMemoryDefinition = Readonly<MemoryDefinition &ModuleSourceRef & {@@ -418,6 +431,7 @@ export interface ResolvedAgent {readonly channels: readonly ResolvedChannelDefinition[];readonly config?: ResolvedAgentDefinition;readonly connections: readonly ResolvedConnectionDefinition[];+ readonly dynamicConnectionResolvers?: readonly ResolvedDynamicConnectionResolver[];/*** Configuration for the experimental framework `Workflow` orchestration* tool. Present when an authored tool module exportsdiff --git a/research/dynamic-connections.md b/research/dynamic-connections.mdnew file mode 100644index 000000000..d12580efb--- /dev/null+++ b/research/dynamic-connections.md@@ -0,0 +1,78 @@+---+issue: https://github.com/vercel/eve/issues/1711+status: implemented+last_updated: "2026-08-29"+---++# Dynamic connections++## Decision++Allow a module under `connections/` to export `defineDynamic({ events })` from+`eve/connections`. Session and turn handlers return one+`defineMcpClientConnection(...)` or `defineOpenAPIConnection(...)`, a map of+connection definitions, or `null`.++```ts+// agent/connections/accounts.ts+import { defineDynamic, defineMcpClientConnection } from "eve/connections";++export default defineDynamic({+ events: {+ "session.started": async (_event, ctx) =>+ Object.fromEntries(+ (await listAccounts(ctx.session.auth.current)).map((account) => [+ account.slug,+ defineMcpClientConnection({+ description: account.description,+ url: account.mcpUrl,+ }),+ ]),+ ),+ },+});+```++A single result uses the file's path-derived name. Map keys are bare connection+names and must satisfy the existing connection-name grammar. Extension map+results receive the mount namespace. A turn result shadows the same resolver's+session result, including `null`.++Dynamic connections override same-named static connections. Two effective+dynamic resolvers emitting the same name fail as ambiguous. Invalid or throwing+resolvers fail the lifecycle without rebuilding the registry.++Connection resolvers receive authenticated session identity and channel kind,+but no conversation history, delivery payload, tool input, model output,+continuation token, or free-form channel metadata. Authenticated dynamic+definitions provide a stable, non-secret `instanceKey`. eve hashes that key+with the path-derived connection identity and endpoint, then uses the result to+pin parked authorization callbacks and token cache entries to the reconstructed+instance.++## Runtime boundary++The compiler classifies the module and retains its event handlers as runtime+entries. Resolved definitions enter the existing per-step connection registry,+so `connection_search`, qualified connection tools, auth, approval, filters,+headers, and provided arguments use the ordinary connection pipeline.++Connection definitions contain live callbacks that cannot enter durable+workflow state. When an active turn resumes in a new durable step, eve reruns+its effective session and turn resolvers before authorization or tool execution.+Resolvers must therefore be idempotent. The durable state continues to store no+connection credentials or live functions.++```text+session/turn event ─> dynamic resolver ─> resolved connection set+ │+durable resume ─────> rerun active resolvers ─┤+ v+ per-step connection registry+ │+ connection_search + qualified tools+```++Dynamic connections do not support `step.started`. Changing the connection set+between individual model calls would make discovered tool identity and parked+authorization unstable within a turn.