The Open Framework for Building Agents
feat: run Connect-managed MCP event callbacks in eve sessions (#4487)
Allen Zhou3aa7dc5fadde
diff --git a/.changeset/experimental-managed-connection-events.md b/.changeset/experimental-managed-connection-events.mdnew file mode 100644index 000000000..050d4ab87--- /dev/null+++ b/.changeset/experimental-managed-connection-events.md@@ -0,0 +1,7 @@+---+"eve": patch+---++Add experimental Connect-managed event subscriptions and per-connection webhook receivers. Durable event handlers run independently of conversation sessions; only an explicit `attachSession(...).send(...)` enters a session. Each watch saves its binding before subscribing, and each delivery runs independently under that binding. Subscribe with `ttlMs` in milliseconds or `null` to watch until stopped; `expiresAt` is returned as the calculated deadline. Requires `@vercel/[email protected]` or later.++Return immediately from the durable sleep tool when steering has already interrupted its execution.diff --git a/apps/package-artifacts/lib/pack.mjs b/apps/package-artifacts/lib/pack.mjsindex b1705646f..c67399e2b 100644--- a/apps/package-artifacts/lib/pack.mjs+++ b/apps/package-artifacts/lib/pack.mjs@@ -40,7 +40,7 @@ export async function packPackage(packageRoot, version, env = process.env) {`Expected packed version ${version}, received ${String(packResult.version)}.`,);}- return readFile(join(finalDirectory, packResult.filename));+ return await readFile(join(finalDirectory, packResult.filename));} finally {await rm(workDirectory, { force: true, recursive: true });}diff --git a/docs/connections/mcp.mdx b/docs/connections/mcp.mdxindex 0a99c75b6..698e75d0f 100644--- a/docs/connections/mcp.mdx+++ b/docs/connections/mcp.mdx@@ -205,65 +205,123 @@ An MCP tool call returns the tool's `structuredContent` when the server sends itWhen a remote tool returns more data than the model needs, narrow the result at the MCP server. Prefer a purpose-built search or summary tool, or return a stable handle that another call can use to fetch a smaller slice. If you do not control the server and an equivalent upstream API is available, replace only that operation with an authored tool that stores the full payload outside model context and projects the needed fields through `toModelOutput`. Block the original MCP operation through [`tools.block`](#tool-filters) so the model does not see duplicate tools.-## Troubleshooting+## Events (experimental)-| Symptom | Check |-| ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |-| `principal_required` | A user-scoped `connect("...")` ran without an authenticated user. Return `principalType: "user"` from route auth, or use app-scoped auth. |-| The model does not find the remote tool | Improve the connection `description`, then check `tools.allow` / `tools.block`. |-| OAuth works locally but fails after deploy | Attach the Connect connector to the deployed Vercel project and verify the UID in `connect("...")`. |-| The server rejects requests | Confirm the MCP URL, transport support, auth scheme, required headers, and application-provided arguments. |+An MCP connection can watch the server's events and run your code when one arrives. Vercel Connect holds the upstream subscription and forwards each event to your agent; eve runs your callback.-## What to read next+Requirements:-- [Connections](../connections): shared auth, headers, approval, and per-caller patterns.-- [OpenAPI connections](./openapi): generate tools from OpenAPI operations.-- [Authentication](../guides/auth-and-route-protection): establish the caller identity required by user-scoped auth.-- [Security model](../concepts/security-model): how connection credentials stay out of the model's reach.+- A statically authored MCP connection with a static `connect()` auth provider. Dynamic connections and auth resolvers are not supported.+- `@vercel/[email protected]` or later.+- An MCP server that supports events over Streamable HTTP.-## Events (experimental)+### Handle events-The experimental connection event contract accepts separate callbacks:+Add `experimental_events` to the connection. In this example, a user asks the agent to "watch the support inbox and draft replies to new bug reports". The model subscribes to Bird's `email_mailbox.message_received` event for that mailbox. Each new email then starts a turn in the same conversation, with instructions to triage it:-```ts-import { defineMcpClientConnection } from "eve/connections";+```ts title="agent/connections/bird.ts"import { connect } from "@vercel/connect/eve";+import { defineMcpClientConnection } from "eve/connections";export default defineMcpClientConnection({- url: "https://issues.example/mcp",- description: "Search and watch issues",- auth: connect("oauth/issues"),+ url: "https://mcp.bird.com/",+ description: "Bird: email, SMS, and contacts. Can watch a mailbox for new mail.",+ auth: connect("bird/bird"),experimental_events: {async onEvent({ event, origin, auth, attachSession }) {+ if (event.name !== "email_mailbox.message_received") return;await attachSession(origin.sessionId).send(- `Review this issue event: ${JSON.stringify(event.data)}`,+ [+ "A new email arrived in the mailbox you are watching:",+ JSON.stringify(event.data),+ "If it is a bug report, look up the sender's earlier threads, draft a reply " ++ "that says what we know and what happens next, and ask me before sending it. " ++ "Otherwise, summarize it in one line.",+ ].join("\n\n"),{ auth, turnPolicy: "queue" },);},- async onGap({ origin, cursor }) {- // Reconcile the source before assuming a contiguous event stream.- },- async onTerminated({ origin, error }) {- // Decide whether to notify the session or request another subscription.- },},});```-This contract is experimental and requires the matching managed-events runtime-and Connect SDK releases. Defining callbacks does not create a subscription or-start a model turn. `onEvent` is required; lifecycle callbacks are optional.-`experimental_events` opts this connection into event handling. The `connect()`-auth provider supplies the backend that manages subscriptions and verifies-deliveries using the same authorized account. Using `connect()` alone does not-enable event handling or create subscriptions.-Use a statically authored MCP connection and a static `connect()` auth provider-that exposes the events bridge. Dynamic connections and auth resolvers are not-supported by this first version because the receiver must be mounted at build-time. The provider still resolves the current authorized user or app for each-subscription operation.--`origin` and `auth` come from eve's saved subscription binding. Provider event-payloads never select the execution principal. Callback code chooses whether-to send input to an existing session. A session attachment never creates a-replacement session.+The model does the work with the connection's own tools: it reads the thread, drafts the reply, and waits for the user's approval in the conversation. `turnPolicy: "queue"` lets a burst of emails run one turn after another instead of interrupting the user.++`onEvent` is required. Defining it does not subscribe to anything: the model subscribes at runtime.++Callbacks run outside any conversation, as the user who subscribed (`auth`). Nothing enters a session unless you call `attachSession(sessionId).send(...)`, and `attachSession` never creates a session.++Each delivery runs in its own durable workflow, so callbacks can run concurrently, out of order, and more than once. Use `deliveryId` to deduplicate side effects:++```ts+async onEvent({ event, deliveryId }) {+ await fetch("https://crm.example/notes", {+ method: "POST",+ headers: { "Idempotency-Key": deliveryId },+ body: JSON.stringify(event.data),+ });+},+```++### Handle missed events and ended subscriptions++```ts+experimental_events: {+ async onEvent({ event }) {+ // ...+ },+ async onGap({ origin, auth, attachSession }) {+ // The server could not deliver every event. Re-read the source.+ await attachSession(origin.sessionId).send(+ "Some Bird events were missed. Re-check the mailbox.",+ { auth },+ );+ },+ async onTerminated({ origin, auth, error, attachSession }) {+ // The upstream subscription ended. The watch ends when this returns.+ await attachSession(origin.sessionId).send(+ `The Bird watch ended: ${error.message}`,+ { auth },+ );+ },+},+```++### What the model can call++`eve__search` lists three kinds of actions for the connection:++| Action | Input | Result |+| ------------------------- | ---------------------- | --------------------------------------- |+| `events_subscribe_<hash>` | `{ arguments, ttlMs }` | `{ id, status, expiresAt, ... }` |+| `events_get_subscription` | `{ id }` | The subscription, or unknown once ended |+| `events_unsubscribe` | `{ id }` | `{ id, status: "stopping" }` |++There is one subscribe action per event the server offers; its description names the event. `ttlMs` is required: an integer from `120000` (2 minutes) to `31536000000` (365 days), or `null` to watch until stopped. `expiresAt` is the resulting deadline, or `null`.++- **Pending.** If Connect has not confirmed in time, subscribe returns the `id` with `status: "pending"`. Call get with that `id` later.+- **Repeats.** Subscribing again to the same event with the same arguments from the same session returns the existing watch. Another session gets its own watch.+- **Stopping.** Get and stop accept the `id` from any of the creator's sessions. After stop, eve keeps retrying Connect's unsubscribe until cleanup completes; until then get still reports the watch and stop can be called again.+- **Lifetime.** A watch outlives the session that created it. It ends on stop, at `expiresAt`, or when the upstream subscription terminates.++`tools.allow` and `tools.block` apply to these actions. An allow list hides any event action it does not name, so copy the exact `events_subscribe_<hash>` names from `eve__search`. `toolCall.providedArguments` does not apply to event actions.++### Receiver++eve mounts `POST /eve/v1/hooks/:connectionName`, under any configured agent or public prefix. It accepts only Connect's delivery token and only deliveries for a live watch's subscription; it answers `410` once the watch has ended. The callback's identity always comes from the saved watch, never from the event payload.++## Troubleshooting++| Symptom | Check |+| ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |+| `principal_required` | A user-scoped `connect("...")` ran without an authenticated user. Return `principalType: "user"` from route auth, or use app-scoped auth. |+| The model does not find the remote tool | Improve the connection `description`, then check `tools.allow` / `tools.block`. |+| OAuth works locally but fails after deploy | Attach the Connect connector to the deployed Vercel project and verify the UID in `connect("...")`. |+| The server rejects requests | Confirm the MCP URL, transport support, auth scheme, required headers, and application-provided arguments. |++## What to read next++- [Connections](../connections): shared auth, headers, approval, and per-caller patterns.+- [OpenAPI connections](./openapi): generate tools from OpenAPI operations.+- [Authentication](../guides/auth-and-route-protection): establish the caller identity required by user-scoped auth.+- [Security model](../concepts/security-model): how connection credentials stay out of the model's reach.diff --git a/packages/eve/extension-contracts/reports/connection/v50.json b/packages/eve/extension-contracts/reports/connection/v50.jsonindex 577af7cf5..1aee4c0f9 100644--- a/packages/eve/extension-contracts/reports/connection/v50.json+++ b/packages/eve/extension-contracts/reports/connection/v50.json@@ -2,7 +2,7 @@"kind": "eve-extension-capability-contract","capability": "connection","epoch": 50,- "sha256": "81fa5ad1c041ca6e156f502c5740a804bd48bc5434eaa92d19005ba4d60dd901",+ "sha256": "b62089fb119ec4c4992a05746c88e0db455c8fd2092f1782ae5de51d7f8cd806","exports": ["ConnectionAuthorizationFailedError","ConnectionAuthorizationRequiredError",diff --git a/packages/eve/extension-contracts/reports/dynamicTool/v86.json b/packages/eve/extension-contracts/reports/dynamicTool/v86.jsonindex 2ed939cb6..669f42965 100644--- a/packages/eve/extension-contracts/reports/dynamicTool/v86.json+++ b/packages/eve/extension-contracts/reports/dynamicTool/v86.json@@ -2,7 +2,7 @@"kind": "eve-extension-capability-contract","capability": "dynamicTool","epoch": 86,- "sha256": "8c403d23eed21dd4e06fe15cba9a5c2cae846662a7d453bec459584a2254103a",+ "sha256": "e5d8e5bccfd1501204771774b3bae2a761113feeab0f5042b3488a1211b92ed0","exports": ["DynamicToolEntry","DynamicToolEvents",diff --git a/packages/eve/extension-contracts/reports/tool/v92.json b/packages/eve/extension-contracts/reports/tool/v92.jsonindex 3e51a11c5..c7f835c81 100644--- a/packages/eve/extension-contracts/reports/tool/v92.json+++ b/packages/eve/extension-contracts/reports/tool/v92.json@@ -2,7 +2,7 @@"kind": "eve-extension-capability-contract","capability": "tool","epoch": 92,- "sha256": "3e7dccca7e440ac2f146df824d8a95b4aba6b5f1e96d47d099b42f057da61477",+ "sha256": "614609a9eac43cef751e5de67132ea67578e4661ed12c633bf416206ed8a2020","exports": ["AgentRouterInput","AgentRouterTool",diff --git a/packages/eve/src/compiler/normalize-manifest.test.ts b/packages/eve/src/compiler/normalize-manifest.test.tsindex 6b4b19088..b1fb53320 100644--- a/packages/eve/src/compiler/normalize-manifest.test.ts+++ b/packages/eve/src/compiler/normalize-manifest.test.ts@@ -1382,3 +1382,62 @@ describe("compileAgentManifest source graph", () => {expect(binding.backing.kind).toBe("programmatic");});});++it("rejects subagent event connections whose receiver cannot resolve their scope", async () => {+ const root = manifest();+ const child = createAgentSourceManifest({+ agentId: "child",+ agentRoot: `${root.agentRoot}/subagents/child`,+ appRoot: root.appRoot,+ });+ root.subagents.push(+ createLocalSubagentSourceRef({+ entryPath: child.agentRoot,+ logicalPath: "subagents/child",+ manifest: child,+ rootPath: child.agentRoot,+ subagentId: "child",+ }),+ );+ const source = defineProgrammaticAgentSource({+ id: "test:events",+ revision: "v1",+ modules: [+ {+ logicalPath: "connections/issues.ts",+ loadNamespace: async () => ({+ default: defineMcpClientConnection({+ url: "https://issues.example/mcp",+ description: "Issues",+ auth: {+ getToken: async () => ({ token: "credential" }),+ vercelConnect: {+ connector: "oauth/issues",+ experimental_events: {+ createAdapter: vi.fn(),+ verify: vi.fn(),+ },+ },+ },+ experimental_events: { onEvent() {} },+ }),+ }),+ },+ ],+ });+ await expect(+ compileAgentManifest(root, {+ sourceRegistries: [+ registry([+ {+ logicalPath: "agent.ts",+ loadNamespace: async () => ({+ default: defineAgent({ model: "openai/gpt-5.4" }),+ }),+ },+ ]),+ createAgentSourceRegistry([{ applyTo: "all-local-nodes", source }]),+ ],+ }),+ ).rejects.toThrow("root-agent connection");+});diff --git a/packages/eve/src/compiler/normalize-manifest.ts b/packages/eve/src/compiler/normalize-manifest.tsindex 8567d0711..3204d0d07 100644--- a/packages/eve/src/compiler/normalize-manifest.ts+++ b/packages/eve/src/compiler/normalize-manifest.ts@@ -500,8 +500,15 @@ class AgentGraphCompiler {binding: binding!,loadNamespace,});- if (result.kind === "connection") connections.push(result.definition);- else {+ if (result.kind === "connection") {+ if (+ result.definition.experimental_events === true &&+ input.nodeId !== ROOT_COMPILED_AGENT_NODE_ID+ ) {+ throw new Error("experimental_events currently requires a root-agent connection.");+ }+ connections.push(result.definition);+ } else {dynamicConnections.push(withExtensionNamespace(result.definition, candidate.owner));}state.evaluation.requireRuntimeEntry(candidate.sourceId);diff --git a/packages/eve/src/execution/catalog/connection-auth.test.ts b/packages/eve/src/execution/catalog/connection-auth.test.tsnew file mode 100644index 000000000..d54a8a375--- /dev/null+++ b/packages/eve/src/execution/catalog/connection-auth.test.ts@@ -0,0 +1,103 @@+import { expect, it, vi } from "vitest";+import { ConnectionAuthorizationRequiredError } from "#connections/errors.js";+import { listToolMetadata } from "#execution/catalog/connection-auth.js";+import type { ConnectionClient, ConnectionToolMetadata } from "#shared/connection-types.js";++const remote: ConnectionToolMetadata = { name: "search", description: "Search", inputSchema: {} };+const management: ConnectionToolMetadata = {+ name: "events_unsubscribe",+ description: "Stop",+ inputSchema: {},+};++const issues = { connectionName: "issues" };++function client(): ConnectionClient {+ return {+ close: vi.fn(async () => {}),+ connect: vi.fn(async () => {}),+ executeTool: vi.fn(async () => {}),+ getToolMetadata: vi.fn(async () => [remote]),+ eventActions: {+ ownsName: (name) => name === management.name,+ metadata: vi.fn(async () => [management]),+ recoveryMetadata: () => [management],+ execute: vi.fn(async () => {}),+ },+ };+}++it("keeps ordinary MCP tools available when event discovery fails", async () => {+ const connection = client();+ vi.mocked(connection.eventActions!.metadata).mockRejectedValue(new Error("Events unavailable"));+ expect(await listToolMetadata(issues, connection)).toEqual([remote, management]);+});++it("keeps management actions available when MCP tool discovery fails", async () => {+ const connection = client();+ vi.mocked(connection.getToolMetadata).mockRejectedValue(new Error("MCP unavailable"));+ expect(await listToolMetadata(issues, connection)).toEqual([management]);+});++it.each([+ { remote: true, events: true },+ { remote: true, events: false },+ { remote: false, events: true },+])("preserves sign-in when discovery requires authorization: %j", async (required) => {+ const connection = client();+ const error = new ConnectionAuthorizationRequiredError("issues");+ if (required.remote) vi.mocked(connection.getToolMetadata).mockRejectedValue(error);+ if (required.events) vi.mocked(connection.eventActions!.metadata).mockRejectedValue(error);+ await expect(listToolMetadata(issues, connection)).rejects.toBe(error);+});++it("does not let hung event discovery hide responsive MCP tools", async () => {+ vi.useFakeTimers();+ try {+ const connection = client();+ vi.mocked(connection.eventActions!.metadata).mockReturnValue(new Promise(() => {}));+ const listing = listToolMetadata(issues, connection);+ await vi.advanceTimersByTimeAsync(10_000);+ expect(await listing).toEqual([remote, management]);+ } finally {+ vi.useRealTimers();+ }+});++it("offers event actions that take longer than half the listing deadline to discover", async () => {+ vi.useFakeTimers();+ try {+ const connection = client();+ const subscribe = { name: "events_subscribe_issue", description: "Watch", inputSchema: {} };+ vi.mocked(connection.eventActions!.metadata).mockReturnValue(+ new Promise((resolve) => setTimeout(() => resolve([subscribe, management]), 7_000)),+ );+ const listing = listToolMetadata(issues, connection);+ await vi.advanceTimersByTimeAsync(7_000);+ expect(await listing).toEqual([remote, subscribe, management]);+ } finally {+ vi.useRealTimers();+ }+});++it("rejects ambiguous catalog names without routing a remote tool to an event action", async () => {+ const connection = client();+ vi.mocked(connection.getToolMetadata).mockResolvedValue([management]);+ await expect(listToolMetadata(issues, connection)).rejects.toThrow("event action namespace");+ expect(connection.eventActions!.execute).toHaveBeenCalledTimes(0);+});++it.each([+ { tools: { block: ["events_unsubscribe"] }, listed: [remote] },+ { tools: { allow: ["search"] }, listed: [remote] },+ { tools: { allow: ["events_unsubscribe"] }, listed: [management] },+])("applies the connection's tool filter to event actions too: %j", async ({ tools, listed }) => {+ expect(await listToolMetadata({ ...issues, tools }, client())).toEqual(listed);+});++it("applies the connection's tool filter to ordinary tools when event discovery is off", async () => {+ const connection = { ...client(), eventActions: undefined };+ expect(await listToolMetadata({ ...issues, tools: { block: ["search"] } }, connection)).toEqual(+ [],+ );+});diff --git a/packages/eve/src/execution/catalog/connection-auth.ts b/packages/eve/src/execution/catalog/connection-auth.tsindex 330ca8b08..b049742cd 100644--- a/packages/eve/src/execution/catalog/connection-auth.ts+++ b/packages/eve/src/execution/catalog/connection-auth.ts@@ -7,6 +7,7 @@ import {import { getAuthorizationResults } from "#harness/authorization.js";import { createLogger } from "#internal/logging.js";import type { ConnectionRegistry } from "#runtime/connections/registry-types.js";+import { passesToolFilter } from "#runtime/connections/mcp-client.js";import { resolveConnectionAuthorization } from "#runtime/connections/resolve-authorization.js";import {createAuthorizationExecution,@@ -16,6 +17,7 @@ import type { ResolvedConnectionDefinition } from "#runtime/types.js";import {supportsInteractiveAuthorization,type ConnectionClient,+ type ConnectionEventActionHandler,type ConnectionToolMetadata,} from "#shared/connection-types.js";import { toErrorMessage } from "#shared/errors.js";@@ -64,7 +66,7 @@ export async function listConnectionTools(): Promise<ConnectionListing> {const name = connection.connectionName;try {- return { tools: await listToolMetadata(name, client) };+ return { tools: await listToolMetadata(connection, client) };} catch (error) {if (!isConnectionAuthorizationRequiredError(error)) {log.warn("failed to load connection tools", { connection: name, error });@@ -93,14 +95,17 @@ class ListingTimeoutError extends Error {}* {@link LISTING_TIMEOUT_MS}, so one hung server can't stall a step. Clients* share one in-flight listing and take no signal, so this stops waiting rather* than cancelling: a late result fills only that client's cache, and the race- * handles a late rejection.+ * handles a late rejection. Event discovery runs under the same deadline.+ * The connection's `tools` filter applies to everything listed, remote tools+ * and eve's event actions alike, and a call only runs a listed tool.*/export async function listToolMetadata(- connectionName: string,+ connection: Pick<ResolvedConnectionDefinition, "connectionName" | "tools">,client: ConnectionClient,): Promise<readonly ConnectionToolMetadata[]> {+ const { connectionName } = connection;let timer: ReturnType<typeof setTimeout> | undefined;- const timeout = new Promise<never>((_, reject) => {+ const deadline = new Promise<never>((_, reject) => {timer = setTimeout(() => {reject(new ListingTimeoutError(@@ -110,12 +115,56 @@ export async function listToolMetadata(}, LISTING_TIMEOUT_MS);});try {- return await Promise.race([client.getToolMetadata(), timeout]);+ const tools = await listConnectionMetadata(connectionName, client, deadline);+ return tools.filter((tool) => passesToolFilter(tool.name, connection.tools));} finally {clearTimeout(timer);}}+async function listConnectionMetadata(+ connectionName: string,+ client: ConnectionClient,+ deadline: Promise<never>,+): Promise<readonly ConnectionToolMetadata[]> {+ const remoteListing = Promise.race([client.getToolMetadata(), deadline]);+ const actions = client.eventActions;+ if (actions === undefined) return remoteListing;+ const [remoteResult, actionResult] = await Promise.allSettled([+ remoteListing,+ listEventActions(connectionName, actions, deadline),+ ]);+ // An auth challenge must reach the sign-in flow, not become a partial catalog.+ for (const result of [remoteResult, actionResult]) {+ if (result.status === "rejected" && isConnectionAuthorizationRequiredError(result.reason))+ throw result.reason;+ }+ const generated = actionResult.status === "fulfilled" ? actionResult.value : [];+ if (remoteResult.status === "rejected") {+ if (generated.length > 0) return generated;+ throw remoteResult.reason;+ }+ const remote = remoteResult.value;+ if (remote.some((tool) => actions.ownsName(tool.name)))+ throw new Error("Remote tool names conflict with eve's event action namespace.");+ return [...remote, ...generated];+}++/** Event discovery that fails or misses the listing's deadline keeps get and stop for existing watches. */+async function listEventActions(+ connectionName: string,+ actions: ConnectionEventActionHandler,+ deadline: Promise<never>,+): Promise<readonly ConnectionToolMetadata[]> {+ try {+ return await Promise.race([actions.metadata(), deadline]);+ } catch (error) {+ if (isConnectionAuthorizationRequiredError(error)) throw error;+ log.warn("failed to discover connection events", { connection: connectionName, error });+ return actions.recoveryMetadata();+ }+}+/** Why a connection's tools could not be listed, for a failure other than a needed sign-in. */export function listingFailureMessage(connectionName: string, error: unknown): string {if (error instanceof ListingTimeoutError) return error.message;diff --git a/packages/eve/src/execution/catalog/connection-entry.ts b/packages/eve/src/execution/catalog/connection-entry.tsindex 8df9ccc7a..666bd0840 100644--- a/packages/eve/src/execution/catalog/connection-entry.ts+++ b/packages/eve/src/execution/catalog/connection-entry.ts@@ -151,12 +151,18 @@ async function callConnectionTool(return await auth.handleError(listing.error, listing.authorization);}// Validation may have run before a sign-in made the tools listable.- const checked = await checkCall(connection, listing.tools, toolName, rawInput);+ const isEventAction = client.eventActions?.ownsName(toolName) === true;+ const checked = await checkCall(connection, listing.tools, toolName, rawInput, !isEventAction);if ("issues" in checked) throw new Error(issuesMessage(checked.issues));const { input, tool } = checked;let raw: unknown;try {+ if (isEventAction)+ return await client.eventActions!.execute(tool.name, input, {+ abortSignal: options.abortSignal,+ callId: options.toolCallId,+ });raw = await client.executeTool(tool.name, input, {abortSignal: options.abortSignal,callId: options.toolCallId,@@ -177,18 +183,22 @@ async function checkInput(toolName: string,input: unknown,): Promise<StandardSchemaV1.Result<unknown>> {+ const client = registry.getClient(connection.connectionName);let tools: readonly ConnectionToolMetadata[];try {- tools = await listToolMetadata(- connection.connectionName,- registry.getClient(connection.connectionName),- );+ tools = await listToolMetadata(connection, client);} catch (error) {// Only the call itself can start the sign-in that makes its tools listable.if (isConnectionAuthorizationRequiredError(error)) return { value: input };return { issues: [{ message: listingFailureMessage(connection.connectionName, error) }] };}- const checked = await checkCall(connection, tools, toolName, input);+ const checked = await checkCall(+ connection,+ tools,+ toolName,+ input,+ client.eventActions?.ownsName(toolName) !== true,+ );return "issues" in checked ? { issues: checked.issues } : { value: checked.input };}@@ -202,13 +212,14 @@ async function checkCall(tools: readonly ConnectionToolMetadata[],toolName: string,input: unknown,+ remote = true,): Promise<CallCheck> {const tool = tools.find((entry) => entry.name === toolName);if (tool === undefined) {return { issues: [{ message: unknownToolMessage(connection, toolName, tools) }] };}// Provided values replace these keys at execution, so a model value for one is dropped, not rejected.- const provided = connection.toolCall?.providedArguments ?? {};+ const provided = remote ? (connection.toolCall?.providedArguments ?? {}) : {};const modelInput = Object.fromEntries(Object.entries(isObject(input) ? input : {}).filter(([key]) => !Object.hasOwn(provided, key)),);@@ -308,10 +319,7 @@ async function toolAnnotations(toolName: string,): Promise<ConnectionToolAnnotations | undefined> {try {- const tools = await listToolMetadata(- connection.connectionName,- registry.getClient(connection.connectionName),- );+ const tools = await listToolMetadata(connection, registry.getClient(connection.connectionName));return tools.find((tool) => tool.name === toolName)?.annotations;} catch {// Input validation already reported a listing failure; a sign-in the call needs comes later.diff --git a/packages/eve/src/execution/stable-workflow-names.ts b/packages/eve/src/execution/stable-workflow-names.tsindex 1e6da0f64..8b5c81f52 100644--- a/packages/eve/src/execution/stable-workflow-names.ts+++ b/packages/eve/src/execution/stable-workflow-names.ts@@ -7,10 +7,14 @@ const TURN_WORKFLOW_NAME = "turnWorkflow";export const WORKFLOW_ENTRY_NAME = "workflowEntry";export const SESSION_TIMEOUT_WORKFLOW_NAME = "sessionTimeoutWorkflow";export const WORKFLOW_TOOL_RUN_WORKFLOW_NAME = "workflowToolRunWorkflow";+export const CONNECTION_EVENT_WORKFLOW_NAME = "connectionEventWorkflow";+export const CONNECTION_EVENT_DELIVERY_WORKFLOW_NAME = "connectionEventDeliveryWorkflow";export const STABLE_WORKFLOW_NAMES: ReadonlySet<string> = new Set([WORKFLOW_ENTRY_NAME,TURN_WORKFLOW_NAME,SESSION_TIMEOUT_WORKFLOW_NAME,WORKFLOW_TOOL_RUN_WORKFLOW_NAME,+ CONNECTION_EVENT_WORKFLOW_NAME,+ CONNECTION_EVENT_DELIVERY_WORKFLOW_NAME,]);diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.tsindex 7893a5be9..ef6aa4de9 100644--- a/packages/eve/src/execution/workflow-runtime.ts+++ b/packages/eve/src/execution/workflow-runtime.ts@@ -88,6 +88,8 @@ import {SESSION_TIMEOUT_WORKFLOW_NAME,WORKFLOW_TOOL_RUN_WORKFLOW_NAME,WORKFLOW_ENTRY_NAME,+ CONNECTION_EVENT_WORKFLOW_NAME,+ CONNECTION_EVENT_DELIVERY_WORKFLOW_NAME,} from "#execution/stable-workflow-names.js";const EVE_PACKAGE_INFO = resolveInstalledPackageInfo();@@ -123,6 +125,14 @@ export const workflowToolRunWorkflowReference = {workflowId: `workflow//${STABLE_ID_BASE}//${WORKFLOW_TOOL_RUN_WORKFLOW_NAME}`,};+export const connectionEventWorkflowReference = {+ workflowId: `workflow//${STABLE_ID_BASE}//${CONNECTION_EVENT_WORKFLOW_NAME}`,+};++export const connectionEventDeliveryWorkflowReference = {+ workflowId: `workflow//${STABLE_ID_BASE}//${CONNECTION_EVENT_DELIVERY_WORKFLOW_NAME}`,+};+/*** Creates a workflow-backed runtime whose current owner executes turns and* whose original run retains the public event stream across owner handoffs.diff --git a/packages/eve/src/internal/nitro/host/application-route-registry.test.ts b/packages/eve/src/internal/nitro/host/application-route-registry.test.tsindex 3f060f5ae..b807a9a26 100644--- a/packages/eve/src/internal/nitro/host/application-route-registry.test.ts+++ b/packages/eve/src/internal/nitro/host/application-route-registry.test.ts@@ -64,3 +64,56 @@ describe("createApplicationRouteRegistry", () => {expect(registry.routes.filter((route) => route.kind === "workflow")).toHaveLength(1);});});++it("mounts only opted-in connection receivers from the compiled manifest", async () => {+ const { manifest } = await compileFromMemory({+ model: "openai/gpt-5.4",+ modules: [+ {+ logicalPath: "connections/issues.ts",+ loadNamespace: async () => ({+ default: {+ url: "https://issues.example/mcp",+ description: "Issues",+ auth: {+ getToken: async () => ({ token: "credential" }),+ vercelConnect: {+ connector: "oauth/issues",+ experimental_events: {+ createAdapter: async () => {+ throw new Error("must not run during build");+ },+ verify: async () => {+ throw new Error("must not run during build");+ },+ },+ },+ },+ experimental_events: { onEvent() {} },+ },+ }),+ },+ ],+ });+ const registry = createApplicationRouteRegistry({ compileResult: { manifest } });+ expect(registry.routes.filter((route) => route.kind === "connection-event")).toEqual([+ {+ kind: "connection-event",+ method: "POST",+ path: "/eve/v1/hooks/issues",+ connectionName: "issues",+ },+ ]);+ expect(manifest.connections[0]!.vercelConnect).toEqual({ connector: "oauth/issues" });+ const optedOut = {+ ...manifest,+ connections: manifest.connections.map(+ ({ experimental_events: _events, ...connection }) => connection,+ ),+ };+ expect(+ createApplicationRouteRegistry({ compileResult: { manifest: optedOut } }).routes.some(+ (route) => route.kind === "connection-event",+ ),+ ).toBe(false);+});diff --git a/packages/eve/src/internal/nitro/host/application-route-registry.ts b/packages/eve/src/internal/nitro/host/application-route-registry.tsindex bc219a5e0..c599a1d0b 100644--- a/packages/eve/src/internal/nitro/host/application-route-registry.ts+++ b/packages/eve/src/internal/nitro/host/application-route-registry.ts@@ -1,3 +1,4 @@+import { connectionEventRoute } from "#runtime/connections/events/path.js";import type { NormalizedChannelCorsOptions } from "#channel/cors.js";import type { CompiledAgentManifest } from "#compiler/manifest.js";import type { ChannelRouteMethod } from "#public/definitions/channel.js";@@ -28,6 +29,12 @@ export interface ApplicationChannelPreflightRoute {}export type ApplicationRouteRegistration =+ | {+ readonly kind: "connection-event";+ readonly method: "POST";+ readonly path: string;+ readonly connectionName: string;+ }| ApplicationChannelPreflightRoute| ApplicationChannelRoute| {@@ -54,7 +61,8 @@ export interface ApplicationRouteRegistry {interface ApplicationRouteRegistryHost {readonly compileResult: {- readonly manifest: Pick<CompiledAgentManifest, "channelRoutes">;+ readonly manifest: Pick<CompiledAgentManifest, "channelRoutes"> &+ Partial<Pick<CompiledAgentManifest, "connections">>;};}@@ -84,6 +92,18 @@ export function createApplicationRouteRegistry(})),];const routes: ApplicationRouteRegistration[] = [...channelRoutes];+ for (const connection of preparedHost.compileResult.manifest.connections ?? []) {+ if (connection.experimental_events !== true) continue;+ const path = connectionEventRoute(connection.connectionName);+ if (routes.some((route) => route.path === path))+ throw new Error(`Connection event receiver conflicts with an existing route: ${path}`);+ routes.push({+ kind: "connection-event",+ method: "POST",+ path,+ connectionName: connection.connectionName,+ });+ }if (options.development === true) {routes.push(diff --git a/packages/eve/src/internal/nitro/host/configure-nitro-routes.ts b/packages/eve/src/internal/nitro/host/configure-nitro-routes.tsindex 18f9faa34..043dffaeb 100644--- a/packages/eve/src/internal/nitro/host/configure-nitro-routes.ts+++ b/packages/eve/src/internal/nitro/host/configure-nitro-routes.ts@@ -259,6 +259,18 @@ function registerApplicationRoutes(): void {for (const route of registry.routes) {switch (route.kind) {+ case "connection-event": {+ addHostVirtualHandler(nitro, {+ args: JSON.stringify({ artifactsConfig, connectionName: route.connectionName }),+ handlerExport: "handleConnectionEventRequest",+ method: route.method,+ modulePath: resolvePackageSourceFilePath(+ "src/internal/nitro/routes/connection-events.ts",+ ),+ route: route.path,+ });+ break;+ }case "channel":case "channel-preflight": {registerChannelVirtualHandlers(nitro, {diff --git a/packages/eve/src/internal/nitro/routes/channel-request-instrumentation.ts b/packages/eve/src/internal/nitro/routes/channel-request-instrumentation.tsindex 6a2909d88..091d7263e 100644--- a/packages/eve/src/internal/nitro/routes/channel-request-instrumentation.ts+++ b/packages/eve/src/internal/nitro/routes/channel-request-instrumentation.ts@@ -1,3 +1,4 @@+import { connectionEventDestination } from "#runtime/connections/events/path.js";import {context,propagation,@@ -5,13 +6,15 @@ import {SpanKind,SpanStatusCode,type TextMapGetter,+ type Span,+ type SpanContext,} from "#compiled/@opentelemetry/api/index.js";import { getInstrumentationRuntime } from "#instrumentation/runtime.js";import { withErrorContent } from "#compiled/@eve/tracing/otel.js";import { markAgentTraceContext } from "#tracing/eve/agent-trace-context.js";export interface ChannelRequestTrace {- readonly reference: import("@opentelemetry/api").SpanContext;+ readonly reference: SpanContext;channel(input: { channelName?: string; channelKind?: string }): void;}const headersGetter: TextMapGetter<Headers> = {@@ -23,6 +26,45 @@ const headersGetter: TextMapGetter<Headers> = {export async function traceChannelRequest<T extends Response>(input: { readonly request: Request; readonly routeKey: string },handler: (operation: ChannelRequestTrace | undefined) => Promise<T>,+): Promise<T> {+ return traceRequest({ ...input, spanName: "agent.channel.request" }, (span) =>+ handler(+ span === undefined+ ? undefined+ : {+ reference: span.spanContext(),+ channel(input) {+ if (input.channelName !== undefined) {+ span.setAttribute("agent.channel.name", input.channelName);+ span.setAttribute("eve.channel.name", input.channelName);+ }+ if (input.channelKind !== undefined) {+ span.setAttribute("agent.channel.kind", input.channelKind);+ span.setAttribute("eve.channel.kind", input.channelKind);+ }+ },+ },+ ),+ );+}++export async function traceConnectionEventRequest(+ request: Request,+ handler: (span: Span | undefined) => Promise<Response>,+): Promise<Response> {+ return traceRequest(+ {+ request,+ routeKey: `POST ${connectionEventDestination(":connectionName").replace("%3AconnectionName", ":connectionName")}`,+ spanName: "agent.connection.event.request",+ },+ handler,+ );+}++async function traceRequest<T extends Response>(+ input: { request: Request; routeKey: string; spanName: string },+ handler: (span: Span | undefined) => Promise<T>,): Promise<T> {if (getInstrumentationRuntime()?.otelSettings?.traceChannelRequests !== true)return handler(undefined);@@ -34,12 +76,12 @@ export async function traceChannelRequest<T extends Response>(url = new URL(request.url);} catch {}const span = trace.getTracer("eve.channel").startSpan(- "agent.channel.request",+ input.spanName,{kind: SpanKind.SERVER,attributes: {- "operation.name": "agent.channel.request",- "resource.name": "agent.channel.request",+ "operation.name": input.spanName,+ "resource.name": input.spanName,"http.request.method": request.method,"http.route": separator === -1 ? routeKey : routeKey.slice(separator + 1),"url.scheme": url?.protocol.replace(/:$/, ""),@@ -48,21 +90,10 @@ export async function traceChannelRequest<T extends Response>(},parent,);- const operation: ChannelRequestTrace = {- reference: span.spanContext(),- channel(input) {- if (input.channelName !== undefined)- span.setAttribute("agent.channel.name", input.channelName);- if (input.channelName !== undefined) span.setAttribute("eve.channel.name", input.channelName);- if (input.channelKind !== undefined)- span.setAttribute("agent.channel.kind", input.channelKind);- if (input.channelKind !== undefined) span.setAttribute("eve.channel.kind", input.channelKind);- },- };try {const response = await context.with(markAgentTraceContext(withErrorContent(trace.setSpan(parent, span), false)),- () => handler(operation),+ () => handler(span),);span.setAttribute("http.response.status_code", response.status);if (response.status >= 500) span.setStatus({ code: SpanStatusCode.ERROR });diff --git a/packages/eve/src/internal/nitro/routes/connection-events.integration.test.ts b/packages/eve/src/internal/nitro/routes/connection-events.integration.test.tsnew file mode 100644index 000000000..575e84823--- /dev/null+++ b/packages/eve/src/internal/nitro/routes/connection-events.integration.test.ts@@ -0,0 +1,165 @@+import { eventTracing } from "#internal/testing/event-tracing.js";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { handleConnectionEventRequest } from "#internal/nitro/routes/connection-events.js";++const { verify, start, load } = vi.hoisted(() => ({+ verify: vi.fn(),+ start: vi.fn(),+ load: vi.fn(),+}));+vi.mock("#runtime/connections/events/owner.js", () => ({+ startConnectionEventDelivery: start,+}));+vi.mock("#runtime/sessions/compiled-agent-cache.js", () => ({+ getCompiledRuntimeAgentBundle: load,+}));+vi.mock("#internal/nitro/routes/runtime-artifacts.js", () => ({+ resolveNitroCompiledArtifactsSource: () => ({ kind: "disk", appRoot: "/virtual/events" }),+}));+const input = {+ artifactsConfig: { kind: "production" as const, sandboxScope: "fixture" },+ connectionName: "issues",+};+const envelope = {+ context: { eve: { version: 1, sessionId: "session-1", bindingId: "a".repeat(64) } },+ subscriptionId: "sub_1",+ deliveryId: "del_1",+};+function request() {+ return new Request("https://agent.example/eve/v1/hooks/issues", {+ method: "POST",+ body: "untouched-body",+ });+}+beforeEach(() => {+ verify.mockResolvedValue(envelope);+ start.mockResolvedValue(true);+ load.mockResolvedValue({+ resolvedAgent: {+ connections: [+ {+ connectionName: "issues",+ experimental_events: { backend: { verify } },+ },+ ],+ },+ });+});+afterEach(() => {+ vi.resetAllMocks();+ vi.unstubAllEnvs();+});++it("verifies the untouched request and acknowledges only durable handler acceptance", async () => {+ vi.stubEnv("EVE_PUBLIC_ROUTE_PREFIX", "/eve/support");+ let accepted!: () => void;+ let accepting!: () => void;+ const started = new Promise<void>((resolve) => {+ accepting = resolve;+ });+ start.mockImplementation(() => {+ accepting();+ return new Promise<boolean>((resolve) => {+ accepted = () => resolve(true);+ });+ });+ const req = request();+ let settled = false;+ const response = handleConnectionEventRequest(input, req).then((result) => {+ settled = true;+ return result;+ });+ await started;+ expect(settled).toBe(false);+ expect(verify).toHaveBeenCalledWith(req, { path: "/eve/support/v1/hooks/issues" });+ expect(start).toHaveBeenCalledWith(+ expect.objectContaining({+ kind: "connection-event",+ bindingId: "a".repeat(64),+ connectionName: "issues",+ delivery: envelope,+ }),+ expect.anything(),+ );+ accepted();+ expect((await response).status).toBe(202);+});++it.each([+ [{ code: "invalid_delivery" }, 401],+ [{ code: "verification_unavailable" }, 503],+ [{ code: "configuration_error" }, 503],+])("does not enqueue unverified deliveries: %j", async (error, status) => {+ verify.mockRejectedValue(error);+ expect((await handleConnectionEventRequest(input, request())).status).toBe(status);+ expect(start).not.toHaveBeenCalled();+});++it("tells Connect an ended watch is gone and leaves failed starts retryable", async () => {+ start.mockResolvedValueOnce(false);+ expect((await handleConnectionEventRequest(input, request())).status).toBe(410);+ start.mockRejectedValueOnce(new Error("temporarily unavailable"));+ expect((await handleConnectionEventRequest(input, request())).status).toBe(503);+});++it("does not expose a receiver when the connection has not opted in", async () => {+ load.mockResolvedValue({ resolvedAgent: { connections: [] } });+ expect((await handleConnectionEventRequest(input, request())).status).toBe(404);+ expect(verify).not.toHaveBeenCalled();+});++it("traces verified acceptance and propagates a serializable request parent to the durable inbox", async () => {+ const tracing = eventTracing();+ tracing.enable();+ try {+ const req = request();+ req.headers.set("traceparent", `00-${"1".repeat(32)}-${"2".repeat(16)}-01`);+ expect((await handleConnectionEventRequest(input, req)).status).toBe(202);+ const spans = tracing.exporter.getFinishedSpans();+ expect(spans).toHaveLength(1);+ const span = spans[0]!;+ expect(span.name).toBe("agent.connection.event.request");+ expect(span.parentSpanContext?.spanId).toBe("2".repeat(16));+ expect(span.attributes).toMatchObject({+ "http.response.status_code": 202,+ "agent.connection.name": "issues",+ "agent.run.id": "session-1",+ "connect.delivery.id": "del_1",+ });+ expect(JSON.parse(JSON.stringify(start.mock.calls[0]![0])).requestTraceContext).toEqual({+ traceId: span.spanContext().traceId,+ spanId: span.spanContext().spanId,+ traceFlags: 1,+ });+ expect(JSON.stringify(span.attributes)).not.toContain("untouched-body");+ } finally {+ await tracing.close();+ }+});++it("keeps unverified identifiers and error content out of request spans while preserving retry responses", async () => {+ const tracing = eventTracing();+ tracing.enable();+ const logging = vi.spyOn(console, "error").mockImplementation(() => {});+ verify.mockRejectedValue(+ Object.assign(new Error("secret-provider-response"), { code: "ETIMEDOUT" }),+ );+ try {+ const response = await handleConnectionEventRequest(input, request());+ expect(response.status).toBe(503);+ expect(response.headers.get("Retry-After")).toBe("5");+ expect(await response.text()).toBe("");+ const span = tracing.exporter.getFinishedSpans()[0]!;+ expect(span.status.code).toBe(2);+ expect(JSON.stringify(logging.mock.calls)).toContain("ETIMEDOUT");+ expect(JSON.stringify(logging.mock.calls)).toContain("verify");+ expect(span.attributes["agent.connection.name"]).toBeUndefined();+ expect(span.attributes["agent.run.id"]).toBeUndefined();+ expect(+ JSON.stringify([span.attributes, span.events, span.status, logging.mock.calls]),+ ).not.toContain("secret-provider-response");+ } finally {+ logging.mockRestore();+ await tracing.close();+ }+});diff --git a/packages/eve/src/internal/nitro/routes/connection-events.ts b/packages/eve/src/internal/nitro/routes/connection-events.tsnew file mode 100644index 000000000..0ecddae54--- /dev/null+++ b/packages/eve/src/internal/nitro/routes/connection-events.ts@@ -0,0 +1,81 @@+import { traceConnectionEventRequest } from "#internal/nitro/routes/channel-request-instrumentation.js";+import {+ connectionEventAttributes,+ connectionEventError,+ connectionEventTraceContext,+} from "#tracing/eve/connection-events.js";+import { createLogger, logError } from "#internal/logging.js";+import type { NitroArtifactsConfig } from "#internal/nitro/routes/runtime-artifacts.js";+import { resolveNitroCompiledArtifactsSource } from "#internal/nitro/routes/runtime-artifacts.js";+import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";+import { connectionEventDestination } from "#runtime/connections/events/path.js";+import { startConnectionEventDelivery } from "#runtime/connections/events/owner.js";+import { isObject } from "#shared/guards.js";++export async function handleConnectionEventRequest(+ input: { artifactsConfig: NitroArtifactsConfig; connectionName: string },+ request: Request,+): Promise<Response> {+ return traceConnectionEventRequest(request, async (span) => {+ if (request.method !== "POST") return new Response(null, { status: 405 });+ let stage = "load";+ let identifiers: Record<string, string> = {};+ try {+ const bundle = await getCompiledRuntimeAgentBundle({+ compiledArtifactsSource: resolveNitroCompiledArtifactsSource(input.artifactsConfig),+ });+ const events = bundle.resolvedAgent.connections.find(+ (connection) => connection.connectionName === input.connectionName,+ )?.experimental_events;+ if (events === undefined) return new Response(null, { status: 404 });+ stage = "verify";+ const delivery = await events.backend.verify(request, {+ path: connectionEventDestination(input.connectionName),+ });+ const origin = delivery.context.eve;+ if (+ !isObject(origin) ||+ origin.version !== 1 ||+ typeof origin.sessionId !== "string" ||+ origin.sessionId.length === 0 ||+ origin.sessionId.length > 256 ||+ origin.sessionId.includes(":") ||+ typeof origin.bindingId !== "string" ||+ !/^[a-f0-9]{64}$/.test(origin.bindingId)+ )+ return new Response(null, { status: 400 });+ identifiers = connectionEventAttributes({+ connectionName: input.connectionName,+ sessionId: origin.sessionId,+ deliveryId: delivery.deliveryId,+ subscriptionId: delivery.subscriptionId,+ });+ for (const [key, value] of Object.entries(identifiers)) span?.setAttribute(key, value);+ stage = "handler";+ const requestTraceContext = connectionEventTraceContext(span?.spanContext());+ // Context locates the watch. The binding its hook carries authorizes execution.+ const started = await startConnectionEventDelivery(+ {+ kind: "connection-event",+ connectionName: input.connectionName,+ bindingId: origin.bindingId,+ delivery,+ requestTraceContext,+ },+ bundle,+ );+ // 410 tells Connect the watch has ended, so it stops delivering.+ return new Response(null, { status: started ? 202 : 410 });+ } catch (error) {+ if (isObject(error) && error.code === "invalid_delivery")+ return new Response(null, { status: 401 });+ logError(+ createLogger("connection.events.receiver"),+ "connection event receipt failed",+ connectionEventError(error),+ { ...identifiers, stage },+ );+ return new Response(null, { status: 503, headers: { "Retry-After": "5" } });+ }+ });+}diff --git a/packages/eve/src/internal/testing/event-tracing.ts b/packages/eve/src/internal/testing/event-tracing.tsnew file mode 100644index 000000000..f48eb1bb2--- /dev/null+++ b/packages/eve/src/internal/testing/event-tracing.ts@@ -0,0 +1,45 @@+import { context, propagation, trace } from "@opentelemetry/api";+import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks";+import { W3CTraceContextPropagator } from "@opentelemetry/core";+import {+ BasicTracerProvider,+ InMemorySpanExporter,+ SimpleSpanProcessor,+} from "@opentelemetry/sdk-trace-base";+import { createInstrumentationHooks } from "#instrumentation/lifecycle.js";+import { registerInstrumentationRuntime } from "#instrumentation/runtime-global.js";+import type { TraceCapturePolicy } from "#shared/trace-policy.js";++export function eventTracing() {+ const exporter = new InMemorySpanExporter();+ const provider = new BasicTracerProvider({ spanProcessors: [new SimpleSpanProcessor(exporter)] });+ context.setGlobalContextManager(new AsyncLocalStorageContextManager().enable());+ propagation.setGlobalPropagator(new W3CTraceContextPropagator());+ trace.setGlobalTracerProvider(provider);+ const runtime = registerInstrumentationRuntime({+ forceFlush: async () => provider.forceFlush(),+ hooks: createInstrumentationHooks([]),+ otelSettings: undefined,+ runInContext: (_operation, execute) => execute(),+ shutdown: async () => undefined,+ });+ return {+ exporter,+ enable(tracePolicy?: TraceCapturePolicy, requests = true) {+ runtime.otelSettings = {+ functionId: undefined,+ recordInputs: false,+ recordOutputs: false,+ tracePolicy,+ traceChannelRequests: requests,+ };+ },+ async close() {+ runtime.otelSettings = undefined;+ await provider.shutdown();+ trace.disable();+ propagation.disable();+ context.disable();+ },+ };+}diff --git a/packages/eve/src/internal/workflow-bundle/builder.scenario.test.ts b/packages/eve/src/internal/workflow-bundle/builder.scenario.test.tsindex f386687ca..c087345c8 100644--- a/packages/eve/src/internal/workflow-bundle/builder.scenario.test.ts+++ b/packages/eve/src/internal/workflow-bundle/builder.scenario.test.ts@@ -141,6 +141,7 @@ describe("WorkflowBundleBuilder", () => {expect(builder.snapshot.dirs).toEqual([resolvePackageSourceDirectoryPath("src/execution"),resolvePackageSourceDirectoryPath("src/runtime/subagents"),+ resolvePackageSourceDirectoryPath("src/runtime/connections/events"),resolvePackageSourceDirectoryPath("src/subagents"),resolvePackageSourceDirectoryPath("src/tools/provided"),]);@@ -664,6 +665,11 @@ describe("WorkflowBundleBuilder", () => {["sleep tool", "src/tools/provided/sleep-workflow.ts", "executeSleepTool"],["session owner", "src/execution/session/entry.ts", "nextTurnDelivery"],["workflow tool owner", "src/execution/tools/workflow/workflow.ts", "workflowToolRunWorkflow"],+ [+ "connection event owner",+ "src/runtime/connections/events/workflow.ts",+ "connectionEventWorkflow",+ ],])("keeps the %s schemas out of the workflow driver", async (_name, sourcePath, marker) => {const tempRoot = await mkdtemp(join(tmpdir(), "eve-workflow-bundle-no-schemas-"));const outDir = join(tempRoot, "workflow-build");diff --git a/packages/eve/src/internal/workflow-bundle/builder.ts b/packages/eve/src/internal/workflow-bundle/builder.tsindex cef526c56..0f7189c6d 100644--- a/packages/eve/src/internal/workflow-bundle/builder.ts+++ b/packages/eve/src/internal/workflow-bundle/builder.ts@@ -67,6 +67,7 @@ export class WorkflowBundleBuilder {const dirs = [resolvePackageSourceDirectoryPath("src/execution"),resolvePackageSourceDirectoryPath("src/runtime/subagents"),+ resolvePackageSourceDirectoryPath("src/runtime/connections/events"),resolvePackageSourceDirectoryPath("src/subagents"),resolvePackageSourceDirectoryPath("src/tools/provided"),];diff --git a/packages/eve/src/internal/workflow-bundle/workflow-builders.test.ts b/packages/eve/src/internal/workflow-bundle/workflow-builders.test.tsindex 3c5fa1dc2..fcae071f7 100644--- a/packages/eve/src/internal/workflow-bundle/workflow-builders.test.ts+++ b/packages/eve/src/internal/workflow-bundle/workflow-builders.test.ts@@ -74,6 +74,7 @@ describe("applyWorkflowTransform", () => {it.each([["workflowEntry", "src/execution/session/entry.ts"],+ ["connectionEventWorkflow", "src/runtime/connections/events/workflow.ts"],["turnWorkflow", "src/execution/legacy-session/turn-workflow.ts"],])("keeps %s stable across package versions and source moves", async (name, filename) => {const transformed = await applyWorkflowTransform(diff --git a/packages/eve/src/runtime/connections/events/actions.ts b/packages/eve/src/runtime/connections/events/actions.tsnew file mode 100644index 000000000..2b855d617--- /dev/null+++ b/packages/eve/src/runtime/connections/events/actions.ts@@ -0,0 +1,339 @@+import { createMcpTraceFetch } from "#runtime/connections/mcp-tracing.js";+import { createMcpTracing } from "#tracing/eve/mcp.js";+import { withConnectionEventSpan } from "#tracing/eve/connection-events.js";+import { principalOf } from "#execution/session/principal.js";+import { defineJsonSchema, toInputSchema } from "#tools/schema.js";+import { createHash } from "node:crypto";+import {+ createMCPClient,+ type Experimental_MCPEventDefinition as EventDefinition,+ type Experimental_MCPEvents as MCPEvents,+} from "#compiled/@ai-sdk/mcp/index.js";+import { contextStorage } from "#context/container.js";+import { AuthKey, SessionIdKey, SessionTraceSeedKey } from "#context/keys.js";+import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";+import type { ResolvedConnectionDefinition, ResolvedConnectionEvents } from "#runtime/types.js";+import type {+ ConnectionToolExecuteOptions,+ ConnectionToolMetadata,+} from "#shared/connection-types.js";+import type { ManagedEventSubscribeInput } from "#shared/connection-events.js";+import { parseJsonObject } from "#shared/json.js";+import { principalKey, resolveConnectionPrincipal } from "#runtime/connections/principal.js";+import { connectionEventDestination } from "#runtime/connections/events/path.js";+import {+ sameEventOwner,+ type EventBinding,+ type EventOwner,+} from "#runtime/connections/events/state.js";+import type { ManagedEventSubscription } from "#shared/connection-events.js";++const GET = "events_get_subscription";+const STOP = "events_unsubscribe";+const PREFIX = "events_subscribe_";+const MIN_TTL_MS = 120_000;+/** The longest finite watch Connect accepts, in milliseconds. */+const MAX_TTL_MS = 31_536_000_000;+type EventCatalog = Pick<MCPEvents, "list">;+const SUBSCRIBE_INPUT_SCHEMA = defineJsonSchema<+ Pick<ManagedEventSubscribeInput, "arguments" | "ttlMs">+>(parseJsonObject(subscribeInputSchema()));++export function isEventAction(name: string): boolean {+ return name === GET || name === STOP || name.startsWith(PREFIX);+}++export class ConnectionEventActions {+ private readonly connection: ResolvedConnectionDefinition;+ private readonly events: ResolvedConnectionEvents;+ private readonly headers: () => Promise<Record<string, string>>;+ private readonly transportFetch: typeof fetch | undefined;+ constructor(+ connection: ResolvedConnectionDefinition,+ events: ResolvedConnectionEvents,+ headers: () => Promise<Record<string, string>>,+ transportFetch?: typeof fetch,+ ) {+ this.connection = connection;+ this.events = events;+ this.headers = headers;+ this.transportFetch = transportFetch;+ }++ private scope() {+ const ctx = contextStorage.getStore();+ if (ctx === undefined) throw new Error("Event subscriptions require an active eve session.");+ if (ctx.get(BundleKey)?.nodeId !== undefined)+ throw new Error(+ "Experimental event subscriptions currently require a root-agent connection.",+ );+ const { authorization, backend, connector } = this.events;+ const principal = resolveConnectionPrincipal(+ this.connection.connectionName,+ authorization,+ ctx,+ );+ const sessionId = ctx.require(SessionIdKey);+ const owner = principalKey(principal);+ const executionPrincipal = principalOf(ctx.get(AuthKey));+ const caller: EventOwner = {+ connectionName: this.connection.connectionName,+ instanceId: this.connection.instanceId,+ connector,+ principalKey: owner,+ executionPrincipal,+ };+ return {+ ctx,+ principal,+ sessionId,+ owner,+ executionPrincipal,+ caller,+ backend,+ connector,+ };+ }++ private async withClient<T>(run: (events: EventCatalog) => Promise<T>): Promise<T> {+ this.scope();+ // A fresh authenticated transport keeps catalogs isolated between people sharing a session.+ let client: Awaited<ReturnType<typeof createMCPClient>> | undefined;+ const config = {+ transport: {+ type: "http" as const,+ fetch: createMcpTraceFetch({+ connectionName: this.connection.connectionName,+ fetcher: this.transportFetch,+ getProtocolVersion: () => client?.initializeResult?.protocolVersion,+ }),+ url: this.connection.url,+ headers: await this.headers(),+ },+ protocolVersionDiscovery: this.connection.protocolVersionDiscovery,+ };+ client = await createMCPClient(config);+ try {+ return await run(client.experimental_events);+ } finally {+ await client.close();+ }+ }++ private async catalog(events: EventCatalog): Promise<EventDefinition[]> {+ const result: EventDefinition[] = [];+ const seen = new Set<string>();+ let cursor: string | undefined;+ let discovered = 0;+ for (let pageIndex = 0; pageIndex < 20; pageIndex++) {+ const page = await withConnectionEventSpan(+ {+ ctx: this.scope().ctx,+ connectionName: this.connection.connectionName,+ operation: "catalog",+ },+ () =>+ createMcpTracing().list({+ connectionName: this.connection.connectionName,+ method: "events/list",+ execute: () => events.list({ params: { cursor }, options: { timeout: 15_000 } }),+ }),+ );+ discovered += page.events.length;+ if (discovered > 1000) throw new Error("MCP event catalog exceeds the 1000-event limit.");+ result.push(...page.events.filter((event) => event.delivery.includes("webhook")));+ cursor = page.nextCursor ?? undefined;+ if (cursor === undefined) return result;+ if (seen.has(cursor)) throw new Error("MCP event catalog returned a repeated cursor.");+ seen.add(cursor);+ }+ throw new Error("MCP event catalog exceeds the 20-page limit.");+ }++ async metadata(): Promise<ConnectionToolMetadata[]> {+ return this.withClient(async (events) => {+ const catalog = await this.catalog(events);+ return [+ ...catalog.map((event) => ({+ name: actionName(event.name),+ description: `Watch ${event.name}. ${event.description ?? ""} Events reach this connection's authored callback for ttlMs milliseconds or until stopped. Set ttlMs to null to watch indefinitely. Watching the same event with the same arguments again returns the existing watch.`,+ inputSchema: subscribeInputSchema(event.inputSchema),+ })),+ ...managementMetadata(),+ ];+ });+ }++ /** Existing watches must remain stoppable when upstream discovery fails. */+ recoveryMetadata(): ConnectionToolMetadata[] {+ this.scope();+ return managementMetadata().map((tool) => ({+ ...tool,+ description: `MCP discovery is unavailable. ${tool.description}`,+ }));+ }++ async execute(+ name: string,+ input: unknown,+ options: ConnectionToolExecuteOptions,+ ): Promise<unknown> {+ const args = parseJsonObject(input);+ const { ctx, principal, backend, sessionId, owner, executionPrincipal, caller } = this.scope();+ // Discovery also runs in the harness. Load the workflow runtime only when executing an action.+ const { findConnectionEventOwner, startConnectionEventOwner, retireConnectionEventOwner } =+ await import("#runtime/connections/events/owner.js");+ if (name === GET || name === STOP) {+ if (typeof args.id !== "string") throw new Error("id must be a subscription id.");+ const bindingId = args.id;+ const handler = await findConnectionEventOwner(bindingId);+ if (handler === undefined || !sameEventOwner(handler.owner, caller))+ throw new Error("Unknown subscription for this caller and account.");+ // The watch's run unsubscribes, and repeats it until Connect finishes cleaning up.+ if (name === STOP) {+ if (!(await retireConnectionEventOwner(bindingId)))+ throw new Error("Unknown subscription for this caller and account.");+ return { id: bindingId, status: "stopping" as const };+ }+ if (handler.subscription === undefined) return pendingResult(handler.owner);+ const subscriptionId = handler.subscription.id;+ const events = await backend.createAdapter({+ principal,+ connection: { url: this.connection.url },+ destination: { path: connectionEventDestination(this.connection.connectionName) },+ });+ const subscription = await withConnectionEventSpan(+ {+ ctx,+ connectionName: this.connection.connectionName,+ bindingId,+ subscriptionId,+ operation: "get",+ },+ () => events.getSubscription({ id: subscriptionId, options: { timeout: 30_000 } }),+ );+ return subscriptionResult(bindingId, subscription);+ }+ return this.withClient(async (events) => {+ const definition = (await this.catalog(events)).find(+ (event) => actionName(event.name) === name,+ );+ if (definition === undefined)+ throw new Error("Unknown event subscription action for this account.");+ // Unsupported provider schemas can pass through validation. Keep eve's input checks+ // independent, and validate provider arguments with their original local $ref root.+ const inputResult = await SUBSCRIBE_INPUT_SCHEMA["~standard"].validate(args);+ if (inputResult.issues !== undefined)+ throw new Error(+ `Invalid subscription input: ${inputResult.issues.map(({ message }) => message).join("; ")}`,+ );+ const { arguments: inputArguments, ttlMs } = inputResult.value;+ const schema =+ typeof definition.inputSchema === "boolean"+ ? { allOf: [definition.inputSchema] }+ : definition.inputSchema;+ const valid = await toInputSchema(schema)["~standard"].validate(+ parseJsonObject(inputArguments),+ );+ if (valid.issues !== undefined)+ throw new Error("Event arguments do not match the authorized catalog schema.");+ const eventArguments = parseJsonObject(valid.value);+ // The id names what is watched, not the tool call, so asking again after a+ // cancelled or timed-out call reaches the same watch and its subscription.+ const id = createHash("sha256")+ .update(+ canonicalJson([+ sessionId,+ this.connection.instanceId,+ this.connection.connectionName,+ owner,+ executionPrincipal,+ definition.name,+ eventArguments,+ ]),+ )+ .digest("hex");+ const binding: EventBinding = {+ ...caller,+ id,+ sessionId,+ auth: structuredClone(ctx.get(AuthKey) ?? null),+ traceSeed: ctx.get(SessionTraceSeedKey),+ request: {+ name: definition.name,+ arguments: structuredClone(eventArguments) as ManagedEventSubscribeInput["arguments"],+ ttlMs,+ context: { eve: { version: 1, sessionId, bindingId: id } },+ },+ };+ // A watch already running under this id answers instead of a new one.+ const subscription = await startConnectionEventOwner(+ binding,+ ctx.require(BundleKey),+ options.abortSignal,+ );+ return subscription === undefined+ ? pendingResult(binding)+ : subscriptionResult(id, subscription);+ });+ }+}++function subscribeInputSchema(+ argumentsSchema: EventDefinition["inputSchema"] = { type: "object" },+) {+ return {+ type: "object",+ additionalProperties: false,+ required: ["arguments", "ttlMs"],+ properties: {+ arguments: argumentsSchema,+ ttlMs: {+ type: ["integer", "null"],+ minimum: MIN_TTL_MS,+ maximum: MAX_TTL_MS,+ description: `How long to watch, in milliseconds (${MIN_TTL_MS} to ${MAX_TTL_MS}), or null until stopped`,+ },+ },+ };+}++/** Model-facing ids are eve's binding ids: they locate the handler that owns the watch. */+function subscriptionResult(bindingId: string, subscription: ManagedEventSubscription) {+ return { ...subscription, id: bindingId, subscriptionId: subscription.id };+}++/** A watch whose subscribe is still in flight: its id already works with get and stop. */+function pendingResult(binding: EventBinding) {+ const { name, arguments: eventArguments } = binding.request;+ return { id: binding.id, name, arguments: eventArguments, status: "pending" as const };+}++/** JSON with object keys sorted, so equal arguments hash equally. */+function canonicalJson(value: unknown): string {+ return JSON.stringify(value, (_key, entry: unknown) =>+ entry !== null && typeof entry === "object" && !Array.isArray(entry)+ ? Object.fromEntries(Object.entries(entry).sort(([left], [right]) => (left < right ? -1 : 1)))+ : entry,+ );+}++function actionName(eventName: string): string {+ return `${PREFIX}${createHash("sha256").update(eventName).digest("hex").slice(0, 24)}`;+}++function managementMetadata(): ConnectionToolMetadata[] {+ return [GET, STOP].map((name) => ({+ name,+ description:+ name === GET+ ? "Get one of this caller's subscriptions, by the id its subscribe call returned, with Connect's current status."+ : "Stop one of this caller's subscriptions, by the id its subscribe call returned. The watch then cancels upstream and ends; get reports it until it has.",+ inputSchema: {+ type: "object",+ properties: { id: { type: "string" } },+ required: ["id"],+ additionalProperties: false,+ },+ }));+}diff --git a/packages/eve/src/runtime/connections/events/delivery.ts b/packages/eve/src/runtime/connections/events/delivery.tsnew file mode 100644index 000000000..295f8a32d--- /dev/null+++ b/packages/eve/src/runtime/connections/events/delivery.ts@@ -0,0 +1,11 @@+import type { SpanContext } from "#compiled/@opentelemetry/api/index.js";+import type { ConnectionEventDelivery } from "#shared/connection-events.js";++/** Only the verified receiver constructs this event-handler delivery. */+export interface ConnectionEventPayload {+ readonly kind: "connection-event";+ readonly connectionName: string;+ readonly bindingId: string;+ readonly requestTraceContext?: SpanContext;+ readonly delivery: ConnectionEventDelivery;+}diff --git a/packages/eve/src/runtime/connections/events/dispatch-step.ts b/packages/eve/src/runtime/connections/events/dispatch-step.tsnew file mode 100644index 000000000..88a7f2dd2--- /dev/null+++ b/packages/eve/src/runtime/connections/events/dispatch-step.ts@@ -0,0 +1,116 @@+import { deserializeContext } from "#context/serialize.js";+import { AuthKey } from "#context/keys.js";+import { withConnectionEventSpan } from "#tracing/eve/connection-events.js";+import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";+import { createWorkflowRuntime } from "#execution/workflow-runtime.js";+import { createAttachSessionFn } from "#channel/session.js";+import type { EventBinding } from "#runtime/connections/events/state.js";+import { retireConnectionEventOwner } from "#runtime/connections/events/owner.js";+import type { ConnectionEventPayload } from "#runtime/connections/events/delivery.js";+import {+ principalKey,+ resolveConnectionPrincipalFromAuth,+} from "#runtime/connections/principal.js";+import type { AlsContext } from "#context/container.js";++/** Re-checks the run's saved binding against the deployed connection before any work runs as its creator. */+export function resolveBinding(ctx: AlsContext, binding: EventBinding) {+ const connection = ctx+ .require(BundleKey)+ .resolvedAgent.connections.find(+ (connection) => connection.connectionName === binding.connectionName,+ );+ const events = connection?.experimental_events;+ if (+ connection === undefined ||+ events === undefined ||+ binding.instanceId !== connection.instanceId ||+ events.connector !== binding.connector+ )+ return undefined;+ const principal = resolveConnectionPrincipalFromAuth(+ binding.connectionName,+ events.authorization,+ binding.auth,+ );+ if (principalKey(principal) !== binding.principalKey) return undefined;+ return { binding, connection, events, principal };+}++/** The hook token already routed this delivery to its binding; its content must still match. */+function accepts(binding: EventBinding, payload: ConnectionEventPayload): boolean {+ const { delivery } = payload;+ return (+ payload.connectionName === binding.connectionName &&+ !("event" in delivery && delivery.event.name !== binding.request.name)+ );+}++/**+ * Runs one delivery's callback as the watch's creator. A crash before the+ * step completes re-runs the callback, so callbacks are idempotent on+ * deliveryId. A `terminated` delivery then retires the watch.+ */+export async function dispatchConnectionEventStep(input: {+ readonly serializedContext: Record<string, unknown>;+ readonly binding: EventBinding;+ readonly payload: ConnectionEventPayload;+}): Promise<void> {+ "use step";+ const ctx = await deserializeContext(input.serializedContext);+ const { delivery } = input.payload;+ // The receiver or the watch's run already matched the delivery's subscription.+ const resolved = accepts(input.binding, input.payload)+ ? resolveBinding(ctx, input.binding)+ : undefined;+ if (resolved === undefined) return;+ const { binding, connection } = resolved;+ const bundle = ctx.require(BundleKey);+ const { callbacks } = resolved.events;+ // The callback runs as its creator without replacing the last conversational caller.+ ctx.setVirtualContext(AuthKey, binding.auth);+ const operation =+ "event" in delivery ? "onEvent" : delivery.control.type === "gap" ? "onGap" : "onTerminated";+ await withConnectionEventSpan(+ {+ ctx,+ connectionName: connection.connectionName,+ operation,+ bindingId: binding.id,+ subscriptionId: delivery.subscriptionId,+ deliveryId: delivery.deliveryId,+ requestTraceContext: input.payload.requestTraceContext,+ },+ async (reference) => {+ const common = {+ auth: binding.auth,+ deliveryId: delivery.deliveryId,+ origin: {+ sessionId: binding.sessionId,+ connectionName: binding.connectionName,+ subscriptionId: delivery.subscriptionId,+ },+ attachSession: createAttachSessionFn(+ createWorkflowRuntime({ compiledArtifactsSource: bundle.compiledArtifactsSource }),+ {+ turnPolicy: "queue",+ channelKind: "mcp-events",+ channelName: binding.connectionName,+ requestId: delivery.deliveryId,+ requestTraceContext: reference,+ },+ ),+ };+ if ("event" in delivery) await callbacks.onEvent({ ...common, event: delivery.event });+ else if (delivery.control.type === "gap")+ await callbacks.onGap?.({+ ...common,+ cursor: delivery.control.cursor,+ truncated: delivery.control.truncated,+ });+ else await callbacks.onTerminated?.({ ...common, error: delivery.control.error });+ },+ );+ if ("control" in delivery && delivery.control.type === "terminated")+ await retireConnectionEventOwner(binding.id);+}diff --git a/packages/eve/src/runtime/connections/events/events.integration.test.ts b/packages/eve/src/runtime/connections/events/events.integration.test.tsnew file mode 100644index 000000000..88e4d1133--- /dev/null+++ b/packages/eve/src/runtime/connections/events/events.integration.test.ts@@ -0,0 +1,1022 @@+import * as workflowRuntime from "#execution/workflow-runtime.js";+import { eventTracing } from "#internal/testing/event-tracing.js";+import { trace } from "@opentelemetry/api";+import { connectionEntry } from "#execution/catalog/connection-entry.js";+import { ConnectionRegistryImpl } from "#runtime/connections/registry.js";+import { compileFromMemory } from "#internal/testing/compile-from-memory.js";+import { resolveRuntimeAgentGraph } from "#runtime/resolve-agent-graph.js";+import { createRuntimeAdapterRegistry } from "#runtime/channels/registry.js";+import { defineMcpClientConnection } from "#public/definitions/connections/mcp.js";+import { afterEach, beforeEach, expect, it, vi, onTestFinished } from "vitest";+import { ContextContainer, contextStorage, loadContext } from "#context/container.js";+import { AuthKey, SessionIdKey, SessionTraceSeedKey } from "#context/keys.js";+import { serializeContext } from "#context/serialize.js";+import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";+import type { CompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";+import { ConnectionEventActions } from "#runtime/connections/events/actions.js";+import { startConnectionEventOwner } from "#runtime/connections/events/owner.js";+import type { EventBinding } from "#runtime/connections/events/state.js";+import {+ openConnectionEventStep,+ subscribeConnectionEvent,+ unsubscribeConnectionEventStep,+} from "#runtime/connections/events/lifecycle-step.js";+import { isMcpAuthRequiredError } from "#runtime/connections/mcp-client.js";+import { dispatchConnectionEventStep } from "#runtime/connections/events/dispatch-step.js";+import type { ConnectionEventPayload } from "#runtime/connections/events/delivery.js";+import { listToolMetadata } from "#execution/catalog/connection-auth.js";+import type { ResolvedConnectionDefinition } from "#runtime/types.js";+import type {+ ConnectionEventsAdapter,+ ManagedEventSubscribeInput,+ ManagedEventSubscription,+} from "#shared/connection-events.js";++const { createClient, loadBundle, handlers, retired, workflowRunId } = vi.hoisted(() => ({+ createClient: vi.fn(),+ workflowRunId: { current: "wrun_1" },+ loadBundle: vi.fn(),+ // Stands in for live handler runs: what each run holds in its own input and state.+ // A subscription is undefined while its watch's subscribe is still in flight.+ handlers: new Map<+ string,+ { binding: EventBinding; subscription: ManagedEventSubscription | undefined }+ >(),+ retired: new Set<string>(),+}));+vi.mock("#compiled/@workflow/core/index.js", async (importOriginal) => ({+ ...(await importOriginal<object>()),+ getWorkflowMetadata: () => ({ workflowRunId: workflowRunId.current }),+ getWritable: () => new WritableStream(),+}));+vi.mock("#compiled/@ai-sdk/mcp/index.js", () => ({ createMCPClient: createClient }));+vi.mock("#runtime/connections/events/owner.js", () => ({+ // Subscribes the way the handler run's first step does.+ startConnectionEventOwner: vi.fn(async (binding: EventBinding, bundle: unknown) => {+ // A second run for the same binding conflicts on its hook and reads the first.+ const existing = handlers.get(binding.id);+ if (existing !== undefined) return existing.subscription;+ const { subscribeConnectionEvent } =+ await import("#runtime/connections/events/lifecycle-step.js");+ const { subscriptionFromOutcome } = await vi.importActual<+ typeof import("#runtime/connections/events/owner.js")+ >("#runtime/connections/events/owner.js");+ // The binding id stands in for the run's own idempotency key.+ const subscription = subscriptionFromOutcome(+ await subscribeConnectionEvent(handlerContext(binding, bundle), binding, binding.id),+ );+ handlers.set(binding.id, { binding, subscription });+ return subscription;+ }),+ findConnectionEventOwner: vi.fn(async (bindingId: string) => {+ const handler = handlers.get(bindingId);+ return handler && { owner: handler.binding, subscription: handler.subscription };+ }),+ // The run unsubscribes and ends on its own; this records that it was asked to.+ retireConnectionEventOwner: vi.fn(async (bindingId: string) => {+ if (!handlers.has(bindingId)) return false;+ retired.add(bindingId);+ return true;+ }),+}));+vi.mock("#runtime/sessions/compiled-agent-cache.js", () => ({+ getCompiledRuntimeAgentBundle: loadBundle,+}));+vi.mock("#execution/terminal-session-completion-step.js", () => ({+ emitTerminalSessionCompletionStep: vi.fn(),+}));+let ctx: ContextContainer;+let actions: ConnectionEventActions;+let connection: ResolvedConnectionDefinition;+let requested: ManagedEventSubscribeInput[];+let adapter: ConnectionEventsAdapter;+let saved: Map<string, ManagedEventSubscription>;+let subscriber: ReturnType<typeof vi.fn<ConnectionEventsAdapter["subscribe"]>>;+let callback: ReturnType<typeof vi.fn<(...args: unknown[]) => Promise<void>>>;+let gap: ReturnType<typeof vi.fn<(...args: unknown[]) => Promise<void>>>;+let terminated: ReturnType<typeof vi.fn<(...args: unknown[]) => Promise<void>>>;+let initial: {+ serializedContext: Record<string, unknown>;+ binding: EventBinding | undefined;+};+let eventSchema: Record<string, unknown>;++beforeEach(async () => {+ eventSchema = {+ type: "object",+ properties: { project: { type: "string" } },+ required: ["project"],+ additionalProperties: false,+ };+ requested = [];+ saved = new Map();+ handlers.clear();+ retired.clear();+ callback = vi.fn(async () => {});+ gap = vi.fn(async () => {});+ terminated = vi.fn(async () => {});+ subscriber = vi.fn(async (input: ManagedEventSubscribeInput) => {+ requested.push(input);+ const existing = saved.get(input.idempotencyKey);+ if (existing) return existing;+ const subscription: ManagedEventSubscription = {+ id: `sub_${saved.size}`,+ name: input.name,+ arguments: input.arguments,+ status: "active",+ expiresAt: null,+ };+ saved.set(input.idempotencyKey, subscription);+ return subscription;+ });+ adapter = {+ subscribe: subscriber,+ getSubscription: vi.fn(),+ unsubscribe: vi.fn(async () => ({+ ...saved.values().next().value!,+ status: "stopped" as const,+ })),+ };+ connection = {+ connectionName: "issues",+ instanceId: "issues-v1",+ description: "Issue events",+ url: "https://issues.example/mcp",+ protocol: "mcp",+ logicalPath: "connections/issues.ts",+ sourceId: "issues",+ sourceKind: "module",+ authorization: {+ principalType: "user",+ getToken: vi.fn(async () => ({ token: "test-token" })),+ vercelConnect: {+ connector: "oauth/issues",+ experimental_events: { createAdapter: vi.fn(async () => adapter), verify: vi.fn() },+ },+ },+ };+ const { manifest, moduleMap } = await compileFromMemory({+ model: "openai/gpt-5.4",+ modules: [+ {+ logicalPath: "connections/issues.ts",+ loadNamespace: async () => ({+ default: defineMcpClientConnection({+ url: connection.url,+ description: connection.description,+ auth: connection.authorization,+ experimental_events: { onEvent: callback, onGap: gap, onTerminated: terminated },+ }),+ }),+ },+ ],+ });+ const graph = await resolveRuntimeAgentGraph({ manifest, moduleMap });+ const root = graph.root;+ connection = root.agent.connections[0]!;+ const bundle: CompiledRuntimeAgentBundle = {+ adapterRegistry: createRuntimeAdapterRegistry({ channels: root.channels }),+ compiledArtifactsSource: { kind: "disk", appRoot: "/virtual/events" },+ graph,+ moduleMap,+ resolvedAgent: root.agent,+ hookRegistry: root.hookRegistry,+ subagentRegistry: root.subagentRegistry,+ toolRegistry: root.toolRegistry,+ turnAgent: root.turnAgent,+ };+ loadBundle.mockResolvedValue(bundle);+ createClient.mockImplementation(async (config) => ({+ close: vi.fn(),+ listTools: async () => ({ tools: [] }),+ toolsFromDefinitions: () => ({}),+ experimental_events: {+ list: async () => ({+ events: [+ {+ name: `${config.transport.headers.account}.issue.created`,+ delivery: ["webhook"],+ inputSchema: eventSchema,+ },+ ],+ }),+ },+ }));+ ctx = new ContextContainer();+ ctx.set(BundleKey, bundle);+ ctx.set(SessionIdKey, "session-1");+ setUser("alice");+ actions = new ConnectionEventActions(connection, connection.experimental_events!, async () => ({+ account: ctx.require(AuthKey)!.principalId,+ }));+ initial = {+ serializedContext: {},+ binding: undefined,+ };+});+afterEach(() => {+ vi.restoreAllMocks();+ vi.clearAllMocks();+ vi.unstubAllEnvs();+});++it.each([3_600_000, null])(+ "discovers through the released AI SDK and subscribes through the backend with ttlMs=%s",+ async (ttlMs) => {+ const tracing = eventTracing();+ tracing.enable();+ onTestFinished(() => tracing.close());+ const traceparents: string[] = [];+ const { createMCPClient } = await vi.importActual<+ typeof import("#compiled/@ai-sdk/mcp/index.js")+ >("#compiled/@ai-sdk/mcp/index.js");+ createClient.mockImplementation(createMCPClient);+ const methods: string[] = [];+ const transportFetch: typeof fetch = async (_url, init) => {+ if (init?.method !== "POST") return new Response(null, { status: 405 });+ const request = JSON.parse(String(init.body));+ methods.push(request.method);+ if (request.id === undefined) return new Response(null, { status: 202 });+ let result;+ if (request.method === "initialize") {+ result = {+ protocolVersion: "2025-11-25",+ serverInfo: { name: "test-events", version: "1" },+ capabilities: { events: {} },+ };+ } else if (request.method === "events/list") {+ traceparents.push(request.params?._meta?.traceparent);+ result = {+ events: [+ {+ name: "issue.created",+ delivery: ["webhook"],+ inputSchema: eventSchema,+ payloadSchema: { type: "object" },+ },+ ],+ };+ } else {+ throw new Error(`Unexpected upstream request: ${request.method}`);+ }+ return Response.json({ jsonrpc: "2.0", id: request.id, result });+ };+ actions = new ConnectionEventActions(+ connection,+ connection.experimental_events!,+ async () => ({ Authorization: "Bearer test" }),+ transportFetch,+ );+ await watch("watch-1", ttlMs);+ expect(methods.filter((method) => method === "events/list")).toHaveLength(2);+ expect(methods).not.toContain("events/subscribe");+ const catalogSpans = tracing.exporter+ .getFinishedSpans()+ .filter((span) => span.name === "events/list");+ expect(catalogSpans).toHaveLength(2);+ expect(traceparents).toEqual(+ catalogSpans.map(+ (span) => `00-${span.spanContext().traceId}-${span.spanContext().spanId}-01`,+ ),+ );+ expect(catalogSpans.map((span) => span.attributes["mcp.method.name"])).toEqual([+ "events/list",+ "events/list",+ ]);+ expect(+ tracing.exporter+ .getFinishedSpans()+ .find((span) => span.name === "agent.connection.event.subscribe")?.attributes,+ ).toMatchObject({+ "connect.subscription.id": "sub_0",+ "connect.subscription.status": "active",+ });+ expect(subscriber).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ name: "issue.created", arguments: { project: "ABC" }, ttlMs }),+ );+ expect(handlers.get(initial.binding!.id)?.subscription?.id).toBe("sub_0");+ },+);++it.each([120_000, 31_536_000_000, null])(+ "subscribes with the requested ttlMs=%s and preserves it in the handler's input",+ async (ttlMs) => {+ await watch("watch-1", ttlMs);+ expect(requested[0]).toMatchObject({ ttlMs, idempotencyKey: initial.binding!.id });+ expect(requested[0]).not.toHaveProperty("expiresAt");+ expect(initial.binding!.request.ttlMs).toBe(ttlMs);+ const [tool] = await contextStorage.run(ctx, () => actions.metadata());+ const { toInputSchema } = await import("#tools/schema.js");+ const schema = toInputSchema(tool!.inputSchema);+ expect(+ await schema["~standard"].validate({ arguments: { project: "ABC" }, ttlMs }),+ ).not.toHaveProperty("issues");+ },+);++it.each([+ {},+ { expiresAt: null },+ { ttlMs: 119_999 },+ { ttlMs: 120_000.5 },+ { ttlMs: 31_536_000_001 },+ { ttlMs: "120000" },+ { ttlMs: 120_000, expiresAt: null },+])("rejects invalid subscription input %j before starting a watch", async (lifetime) => {+ const [tool] = await contextStorage.run(ctx, () => actions.metadata());+ const input = { arguments: { project: "ABC" }, ...lifetime };+ const { toInputSchema } = await import("#tools/schema.js");+ expect(await toInputSchema(tool!.inputSchema)["~standard"].validate(input)).toHaveProperty(+ "issues",+ );+ await expect(+ contextStorage.run(ctx, () => actions.execute(tool!.name, input, { callId: "invalid" })),+ ).rejects.toThrow("Invalid subscription input");+ expect(subscriber).not.toHaveBeenCalled();+ expect(handlers.size).toBe(0);+});++it.each([{ ttlMs: 1 }, { ttlMs: 120_000, expiresAt: null }])(+ "rejects invalid subscription input %j even when the provider schema cannot be validated",+ async (lifetime) => {+ eventSchema = { type: "object", properties: { project: { type: "provider-specific" } } };+ const [tool] = await contextStorage.run(ctx, () => actions.metadata());+ await expect(+ contextStorage.run(ctx, () =>+ actions.execute(+ tool!.name,+ { arguments: { project: "ABC" }, ...lifetime },+ { callId: "invalid" },+ ),+ ),+ ).rejects.toThrow("Invalid subscription input");+ expect(subscriber).not.toHaveBeenCalled();+ expect(handlers.size).toBe(0);+ },+);++it.each(["available", "provided arguments", "catalog unavailable", "connection unavailable"])(+ "returns subscription results through eve's connection tool entry with MCP %s",+ async (availability) => {+ connection = { ...connection, headers: { account: "alice" } };+ if (availability === "provided arguments")+ connection = {+ ...connection,+ toolCall: { providedArguments: { arguments: () => ({ project: "REMOTE_ONLY" }) } },+ };+ const registry = new ConnectionRegistryImpl([connection]);+ try {+ await contextStorage.run(ctx, async () => {+ const [tool] = await listToolMetadata(+ connection,+ registry.getClient(connection.connectionName),+ );+ const execute = (name: string, input: unknown) =>+ connectionEntry(registry, connection, name).execute!(input, {+ toolCallId: name,+ messages: [],+ });+ const created = (await execute(tool!.name, {+ arguments: { project: "ABC" },+ ttlMs: TTL_MS,+ })) as { id: string };+ expect(created).toMatchObject({ subscriptionId: "sub_0", status: "active" });+ expect(requested[0]!.arguments).toEqual({ project: "ABC" });+ if (availability.includes("unavailable")) {+ if (availability === "connection unavailable") await registry.dispose();+ createClient.mockRejectedValue(new Error("MCP unavailable"));+ }+ vi.mocked(adapter.getSubscription).mockResolvedValue(saved.values().next().value!);+ expect(await execute("events_get_subscription", { id: created.id })).toMatchObject({+ id: created.id,+ subscriptionId: "sub_0",+ });+ if (availability.includes("unavailable")) {+ setUser("bob");+ await expect(execute("events_get_subscription", { id: created.id })).rejects.toThrow(+ "Unknown subscription",+ );+ setUser("alice");+ }+ expect(await execute("events_unsubscribe", { id: created.id })).toEqual({+ id: created.id,+ status: "stopping",+ });+ expect(retired.has(created.id)).toBe(true);+ });+ } finally {+ await registry.dispose();+ }+ },+);++it.each([+ { filter: { block: ["events_unsubscribe"] }, hidden: ["events_unsubscribe"] },+ { filter: { allow: ["events_get_subscription"] }, hidden: ["subscribe", "events_unsubscribe"] },+])(+ "hides and refuses event actions the connection's tool filter excludes: %j",+ async ({ filter, hidden }) => {+ connection = { ...connection, headers: { account: "alice" }, tools: filter };+ const registry = new ConnectionRegistryImpl([connection]);+ try {+ await contextStorage.run(ctx, async () => {+ const unfiltered = await listToolMetadata(+ { connectionName: connection.connectionName },+ registry.getClient(connection.connectionName),+ );+ const subscribe = unfiltered.find((tool) =>+ tool.name.startsWith("events_subscribe_"),+ )!.name;+ const names = hidden.map((name) => (name === "subscribe" ? subscribe : name));+ const listed = await listToolMetadata(+ connection,+ registry.getClient(connection.connectionName),+ );+ for (const name of names) {+ expect(listed.some((tool) => tool.name === name)).toBe(false);+ await expect(+ connectionEntry(registry, connection, name).execute!(+ { id: "watch", arguments: { project: "ABC" }, ttlMs: TTL_MS },+ { toolCallId: name, messages: [] },+ ),+ ).rejects.toThrow(`has no tool named "${name}"`);+ }+ expect(subscriber).not.toHaveBeenCalled();+ expect(retired.size).toBe(0);+ });+ } finally {+ await registry.dispose();+ }+ },+);++it("runs callbacks in the creator's eve context", async () => {+ await watch();+ setUser("bob");+ initial = { ...initial, serializedContext: serializeContext(ctx) };+ callback.mockImplementation(async () => {+ expect(loadContext().require(AuthKey)?.principalId).toBe("alice");+ });+ await dispatch(payload());+ expect(callback).toHaveBeenCalledTimes(1);+});++it("uses eve tool schema defaults and treats format as an annotation for event arguments", async () => {+ eventSchema = {+ type: "object",+ $defs: {+ project: { type: "string", format: "email" },+ includeArchived: { type: "boolean", default: false },+ },+ properties: {+ project: { $ref: "#/$defs/project" },+ includeArchived: { $ref: "#/$defs/includeArchived" },+ },+ };+ await watch();+ expect(requested[0]!.arguments).toEqual({ project: "ABC", includeArchived: false });+});+function setUser(id: string) {+ ctx.set(AuthKey, {+ principalId: id,+ principalType: "user",+ authenticator: "test",+ issuer: "https://identity.example",+ attributes: {},+ });+}+const TTL_MS = 3_600_000;+async function watch(callId = "watch-1", ttlMs: number | null = TTL_MS) {+ return contextStorage.run(ctx, async () => {+ const tools = await actions.metadata();+ try {+ return (await actions.execute(+ tools[0]!.name,+ { arguments: { project: "ABC" }, ttlMs },+ { callId },+ )) as ManagedEventSubscription & { subscriptionId: string };+ } finally {+ // Deliveries run under the binding the watch's hook carries, not session state.+ initial = { ...initial, binding: [...handlers.values()].at(-1)?.binding };+ }+ });+}+/** The context a handler run starts with: its creator, never the current caller. */+function handlerContext(binding: EventBinding, bundle: unknown): Record<string, unknown> {+ const handler = new ContextContainer();+ handler.set(BundleKey, bundle as CompiledRuntimeAgentBundle);+ handler.set(AuthKey, binding.auth);+ handler.set(SessionIdKey, binding.sessionId);+ return serializeContext(handler);+}+function payload(): ConnectionEventPayload {+ const binding = initial.binding!;+ return {+ kind: "connection-event",+ connectionName: "issues",+ bindingId: binding.id,+ delivery: {+ version: 1,+ deliveryId: "delivery-1",+ subscriptionId: "sub_0",+ source: { type: "mcp", connectorId: "connector" },+ context: binding.request.context!,+ event: {+ eventId: "event-1",+ name: binding.request.name,+ timestamp: "2026-10-07T00:00:00Z",+ data: { issue: "ABC-1" },+ cursor: null,+ },+ },+ };+}+async function dispatch(message: ConnectionEventPayload) {+ await dispatchConnectionEventStep({+ serializedContext: initial.serializedContext,+ binding: initial.binding!,+ payload: message,+ });+}++it.each(["user", "app"] as const)(+ "isolates subscription management between users sharing a %s credential",+ async (principalType) => {+ const auth = connection.authorization;+ if (auth === undefined || typeof auth === "function") throw new Error("Missing fixture auth");+ const authorization = {+ principalType,+ getToken: auth.getToken,+ vercelConnect: auth.vercelConnect,+ };+ connection = {+ ...connection,+ authorization,+ experimental_events: { ...connection.experimental_events!, authorization },+ };+ // The handler re-checks its binding against the deployed connection.+ (ctx.require(BundleKey).resolvedAgent.connections as ResolvedConnectionDefinition[])[0] =+ connection;+ actions = new ConnectionEventActions(connection, connection.experimental_events!, async () => ({+ account: ctx.require(AuthKey)!.principalId,+ }));+ const { id } = await watch();+ setUser("bob");+ const tools = await contextStorage.run(ctx, () => actions.metadata());+ expect(tools[0]!.description).toContain("bob.issue.created");+ for (const action of ["events_get_subscription", "events_unsubscribe"])+ await expect(+ contextStorage.run(ctx, () => actions.execute(action, { id }, { callId: action })),+ ).rejects.toThrow("Unknown subscription");+ expect(adapter.unsubscribe).not.toHaveBeenCalled();+ setUser("alice");+ await watch();+ expect(subscriber).toHaveBeenCalledTimes(1);+ },+);++it("rejects invalid event arguments before subscription and fixes destination/identity outside model input", async () => {+ await contextStorage.run(ctx, async () => {+ const [tool] = await actions.metadata();+ await expect(+ actions.execute(+ tool!.name,+ { arguments: { project: 42 }, ttlMs: TTL_MS },+ { callId: "invalid" },+ ),+ ).rejects.toThrow("catalog schema");+ });+ expect(subscriber).not.toHaveBeenCalled();+ await watch();+ expect(requested[0]!.context).toMatchObject({ eve: { version: 1, sessionId: "session-1" } });+});++it("keeps a 401 from subscribe classifiable as a sign-in request", async () => {+ subscriber.mockRejectedValueOnce(Object.assign(new Error("Unauthorized"), { status: 401 }));+ const failure = await watch().catch((error: unknown) => error);+ expect(isMcpAuthRequiredError(failure)).toBe(true);+ expect(handlers.size).toBe(0);+});++it("throws when a subscribe response is lost, so the step retries with the same key", async () => {+ await watch();+ const binding: EventBinding = { ...initial.binding!, id: "lost" };+ const context = handlerContext(binding, ctx.require(BundleKey));+ const subscribe = subscriber.getMockImplementation()!;+ // Connect creates the subscription, but its response never arrives.+ subscriber.mockImplementationOnce(async (input) => {+ await subscribe(input);+ throw new Error("The operation timed out.");+ });+ await expect(subscribeConnectionEvent(context, binding, "lost")).rejects.toThrow("timed out");+ expect(await subscribeConnectionEvent(context, binding, "lost")).toEqual({+ subscription: saved.get("lost"),+ });+});++it("fails the subscribe action with Connect's error, and a retry reuses its idempotency key", async () => {+ subscriber.mockRejectedValueOnce(new Error("MCP Events provider request failed."));+ await expect(watch()).rejects.toThrow("MCP Events provider request failed.");+ expect(handlers.size).toBe(0);+ // A retry of the same tool call subscribes again with the same idempotency key.+ await watch();+ const [failed, retried] = subscriber.mock.calls.map(([input]) => input);+ expect(failed?.idempotencyKey).toBe(retried?.idempotencyKey);+});++it("runs callbacks as the creator under the run's saved binding", async () => {+ await watch();+ const message = payload();+ setUser("bob");+ initial = { ...initial, serializedContext: serializeContext(ctx) };+ await dispatch(message);+ expect(callback).toHaveBeenCalledWith(+ expect.objectContaining({+ auth: expect.objectContaining({ principalId: "alice" }),+ origin: { sessionId: "session-1", connectionName: "issues", subscriptionId: "sub_0" },+ }),+ );+});++it("does not run a delivery whose connection or event name differs from its binding", async () => {+ await watch();+ initial = { ...initial, serializedContext: serializeContext(ctx) };+ const message = payload();+ // The binding id only finds the watch; the delivery must still match what it watches.+ for (const candidate of [+ { ...message, connectionName: "other" },+ {+ ...message,+ delivery: {+ ...message.delivery,+ event: { ...(message.delivery as { event: object }).event, name: "other.event" },+ },+ },+ ])+ await dispatch(candidate as ConnectionEventPayload);+ expect(callback).not.toHaveBeenCalled();+});++it("returns the same watch when the same event and arguments are watched again", async () => {+ eventSchema = {+ type: "object",+ properties: { project: { type: "string" }, team: { type: "string" } },+ additionalProperties: false,+ };+ const ask = (callId: string, eventArguments: Record<string, string>) =>+ contextStorage.run(ctx, async () => {+ const [tool] = await actions.metadata();+ return (await actions.execute(+ tool!.name,+ { arguments: eventArguments, ttlMs: TTL_MS },+ { callId },+ )) as { id: string };+ });+ // A cancelled call's id is never seen; asking again with a new call reaches its watch.+ const first = await ask("cancelled", { project: "ABC", team: "core" });+ const again = await ask("retry", { team: "core", project: "ABC" });+ expect(again.id).toBe(first.id);+ expect(subscriber).toHaveBeenCalledTimes(1);+ const other = await ask("other", { project: "XYZ", team: "core" });+ expect(other.id).not.toBe(first.id);+});++it("keys Connect's subscribe by watch and run, so a step retry reuses it and a later run does not", async () => {+ await watch();+ const binding = initial.binding!;+ const open = () =>+ openConnectionEventStep({+ serializedContext: handlerContext(binding, ctx.require(BundleKey)),+ binding,+ });+ workflowRunId.current = "wrun_1";+ const first = await open();+ const retried = await open();+ workflowRunId.current = "wrun_2";+ const later = await open();+ const keys = requested.slice(-3).map((input) => input.idempotencyKey);+ expect(keys[1]).toBe(keys[0]);+ expect(keys[2]).not.toBe(keys[0]);+ expect(retried).toEqual(first);+ expect(later).not.toEqual(first);+});++it("returns a subscribe that outlasts the wait as pending under its id, which get later resolves", async () => {+ // The watch run keeps subscribing after the tool stops waiting for it.+ vi.mocked(startConnectionEventOwner).mockImplementationOnce(async (binding) => {+ handlers.set(binding.id, { binding, subscription: undefined });+ return undefined;+ });+ const pending = await watch();+ expect(pending).toEqual({+ id: initial.binding!.id,+ name: initial.binding!.request.name,+ arguments: { project: "ABC" },+ status: "pending",+ });+ const { id } = pending;+ const late = { ...saved.values().next().value, id: "sub_late", status: "active" as const };+ await contextStorage.run(ctx, async () => {+ expect(await actions.execute("events_get_subscription", { id }, { callId: "get" })).toEqual(+ pending,+ );+ handlers.set(id, { binding: initial.binding!, subscription: late as ManagedEventSubscription });+ vi.mocked(adapter.getSubscription).mockResolvedValue(late as ManagedEventSubscription);+ expect(+ await actions.execute("events_get_subscription", { id }, { callId: "get-again" }),+ ).toMatchObject({ id, subscriptionId: "sub_late", status: "active" });+ });+ // The model's next call reuses the id it was given: Connect saw one subscribe.+ expect(adapter.getSubscription).toHaveBeenCalledWith(expect.objectContaining({ id: "sub_late" }));+});++it("takes a stop while the subscribe is still in flight, for the watch's run to carry out", async () => {+ vi.mocked(startConnectionEventOwner).mockImplementationOnce(async (binding) => {+ handlers.set(binding.id, { binding, subscription: undefined });+ return undefined;+ });+ const { id } = await watch();+ await contextStorage.run(ctx, async () => {+ expect(await actions.execute("events_unsubscribe", { id }, { callId: "stop" })).toEqual({+ id,+ status: "stopping",+ });+ });+ expect(retired.has(id)).toBe(true);+});++it("ends the watch after its terminated callback", async () => {+ await watch();+ initial = { ...initial, serializedContext: serializeContext(ctx) };+ const normal = payload();+ const { event: _event, ...envelope } = normal.delivery as Extract<+ typeof normal.delivery,+ { event: unknown }+ >;+ const message: ConnectionEventPayload = {+ ...normal,+ delivery: {+ ...envelope,+ control: { type: "terminated", error: { code: 1, message: "Ended" } },+ },+ };+ await dispatch(message);+ expect(terminated).toHaveBeenCalledTimes(1);+ expect(retired.has(initial.binding!.id)).toBe(true);+ expect(callback).not.toHaveBeenCalled();+});++it("fails the step when a callback fails, so its delivery run retries it", async () => {+ await watch();+ initial = { ...initial, serializedContext: serializeContext(ctx) };+ const message = payload();+ callback.mockRejectedValueOnce(new Error("temporary failure"));+ await expect(dispatch(message)).rejects.toThrow("temporary failure");+ await dispatch(message);+ expect(callback).toHaveBeenCalledTimes(2);+ expect(retired.size).toBe(0);+});++it("lets the creator stop a watch from a later session by its id", async () => {+ const { id } = await watch();+ ctx.set(SessionIdKey, "session-2");+ await contextStorage.run(ctx, async () => {+ expect(await actions.execute("events_unsubscribe", { id }, { callId: "stop" })).toEqual({+ id,+ status: "stopping",+ });+ });+ // The action only asks the watch's run to stop; the run unsubscribes.+ expect(adapter.unsubscribe).not.toHaveBeenCalled();+ expect(retired.has(id)).toBe(true);+});++it("reports a stopped watch until its run finishes Connect's cleanup", async () => {+ const { id } = await watch();+ const cleaning = {+ ...saved.values().next().value!,+ status: "stopped" as const,+ cleanupStatus: "pending" as const,+ };+ vi.mocked(adapter.getSubscription).mockResolvedValue(cleaning);+ await contextStorage.run(ctx, async () => {+ await actions.execute("events_unsubscribe", { id }, { callId: "stop" });+ expect(+ await actions.execute("events_get_subscription", { id }, { callId: "get" }),+ ).toMatchObject({ id, cleanupStatus: "pending" });+ });+ // Once the run has ended, its hook is gone and the id is unknown.+ handlers.delete(id);+ await contextStorage.run(ctx, async () => {+ await expect(+ actions.execute("events_get_subscription", { id }, { callId: "get-after" }),+ ).rejects.toThrow("Unknown subscription");+ await expect(+ actions.execute("events_unsubscribe", { id }, { callId: "stop-after" }),+ ).rejects.toThrow("Unknown subscription");+ });+});++it.each([+ ["pending", { cleanupStatus: "pending" as const }, "pending"],+ ["complete", { cleanupStatus: "complete" as const }, "done"],+ ["already removed", Object.assign(new Error("Not found"), { status: 404 }), "done"],+ ["gone", Object.assign(new Error("Gone"), { status: 410 }), "done"],+ // Cleanup that has not happened keeps the watch, so a later attempt can finish it.+ ["unauthorized", Object.assign(new Error("Unauthorized"), { status: 401 }), "pending"],+ ["forbidden", Object.assign(new Error("Forbidden"), { status: 403 }), "pending"],+ ["unavailable", Object.assign(new Error("Connect unavailable"), { status: 503 }), "pending"],+ ["unreachable", new Error("fetch failed"), "pending"],+])(+ "reads Connect's unsubscribe answer for the watch's run: %s",+ async (_name, answer, expected) => {+ await watch();+ const subscription = saved.values().next().value!;+ if (answer instanceof Error) vi.mocked(adapter.unsubscribe).mockRejectedValueOnce(answer);+ else vi.mocked(adapter.unsubscribe).mockResolvedValueOnce({ ...subscription, ...answer });+ const binding = initial.binding!;+ expect(+ await unsubscribeConnectionEventStep({+ serializedContext: handlerContext(binding, ctx.require(BundleKey)),+ binding,+ subscriptionId: subscription.id,+ }),+ ).toBe(expected);+ expect(adapter.unsubscribe).toHaveBeenCalledWith(+ expect.objectContaining({ id: subscription.id }),+ );+ },+);++it("records a gap before dispatch and keeps the subscription available for later events", async () => {+ await watch();+ initial = { ...initial, serializedContext: serializeContext(ctx) };+ const normal = payload();+ const { event: _event, ...envelope } = normal.delivery as Extract<+ typeof normal.delivery,+ { event: unknown }+ >;+ const message: ConnectionEventPayload = {+ ...normal,+ delivery: { ...envelope, control: { type: "gap", cursor: "cursor-2", truncated: true } },+ };+ await dispatch(message);+ expect(gap).toHaveBeenCalledTimes(1);+ const next = { ...normal, delivery: { ...normal.delivery, deliveryId: "next" } };+ await dispatch(next);+ expect(callback).toHaveBeenCalledTimes(1);+});++it.each(["event", "gap", "terminated"] as const)(+ "traces each durable %s callback attempt under its saved receipt context",+ async (kind) => {+ const tracing = eventTracing();+ tracing.enable();+ const logging = vi.spyOn(console, "error").mockImplementation(() => {});+ try {+ await watch();+ initial = { ...initial, serializedContext: serializeContext(ctx) };+ const message = payload();+ const delivery = message.delivery;+ const tracedMessage: ConnectionEventPayload = {+ ...message,+ requestTraceContext: { traceId: "1".repeat(32), spanId: "2".repeat(16), traceFlags: 1 },+ delivery:+ kind === "event"+ ? delivery+ : {+ version: delivery.version,+ subscriptionId: delivery.subscriptionId,+ deliveryId: delivery.deliveryId,+ source: delivery.source,+ context: delivery.context,+ ...(kind === "gap"+ ? { control: { type: "gap" as const, cursor: null } }+ : {+ control: {+ type: "terminated" as const,+ error: { code: 1, message: "private" },+ },+ }),+ },+ };+ const handler = kind === "event" ? callback : kind === "gap" ? gap : terminated;+ const active: string[] = [];+ handler+ .mockImplementationOnce(async () => {+ active.push(trace.getActiveSpan()!.spanContext().spanId);+ throw new Error("secret-callback-payload");+ })+ .mockImplementationOnce(async () => {+ active.push(trace.getActiveSpan()!.spanContext().spanId);+ });+ await expect(dispatch(tracedMessage)).rejects.toThrow("secret-callback-payload");+ await dispatch(JSON.parse(JSON.stringify(tracedMessage)));+ const spans = tracing.exporter+ .getFinishedSpans()+ .filter((span) => span.name.startsWith("agent.connection.event.on"));+ expect(spans).toHaveLength(2);+ expect(active).toEqual(spans.map((span) => span.spanContext().spanId));+ expect(new Set(active).size).toBe(2);+ expect(spans.map((span) => span.parentSpanContext?.spanId)).toEqual([+ "2".repeat(16),+ "2".repeat(16),+ ]);+ expect(spans.map((span) => span.status.code)).toEqual([2, 1]);+ expect(spans[1]!.attributes).toMatchObject({+ "agent.run.id": "session-1",+ "connect.subscription.id": "sub_0",+ "connect.delivery.id": "delivery-1",+ });+ expect(+ JSON.stringify([spans.map((s) => [s.attributes, s.events, s.status]), logging.mock.calls]),+ ).not.toContain("secret-callback-payload");+ } finally {+ logging.mockRestore();+ await tracing.close();+ }+ },+);++it("honors disabled tracing and a dropped session policy without preventing event callbacks", async () => {+ const tracing = eventTracing();+ try {+ for (const enabled of [false, true]) {+ if (enabled) tracing.enable(() => false);+ await watch();+ initial = { ...initial, serializedContext: serializeContext(ctx) };+ await dispatch(payload());+ }+ expect(callback).toHaveBeenCalledTimes(2);+ expect(tracing.exporter.getFinishedSpans()).toEqual([]);+ } finally {+ await tracing.close();+ }+});++it("links callback sends to the callback span through durable channel delivery metadata", async () => {+ const tracing = eventTracing();+ tracing.enable();+ onTestFinished(() => tracing.close());+ await watch();+ initial = { ...initial, serializedContext: serializeContext(ctx) };+ const runtime = workflowRuntime.createWorkflowRuntime({+ compiledArtifactsSource: ctx.require(BundleKey).compiledArtifactsSource,+ });+ const send = vi.fn().mockResolvedValue({ status: "accepted" });+ vi.spyOn(workflowRuntime, "createWorkflowRuntime").mockReturnValue({+ ...runtime,+ dispatchSession: send,+ });+ callback.mockImplementation(async (args) => {+ const event = args as Parameters<+ NonNullable<typeof connection.experimental_events>["callbacks"]["onEvent"]+ >[0];+ await event+ .attachSession(event.origin.sessionId)+ .send("check this event", { auth: event.auth });+ });+ await dispatch(payload());+ const span = tracing.exporter+ .getFinishedSpans()+ .find((span) => span.name === "agent.connection.event.onEvent")!;+ expect(JSON.parse(JSON.stringify(send.mock.calls[0]![0]))).toMatchObject({+ sessionId: "session-1",+ command: {+ turnPolicy: "queue",+ requestId: "delivery-1",+ delivery: {+ channelKind: "mcp-events",+ channelName: "issues",+ requestId: "delivery-1",+ requestTraceContext: {+ traceId: span.spanContext().traceId,+ spanId: span.spanContext().spanId,+ traceFlags: 1,+ },+ },+ },+ });+});++it("does not let a sampled webhook override the session's saved sampling decision", async () => {+ const tracing = eventTracing();+ tracing.enable();+ onTestFinished(() => tracing.close());+ await watch();+ tracing.exporter.reset();+ ctx.set(SessionTraceSeedKey, {+ traceId: "3".repeat(32),+ spanId: "4".repeat(16),+ traceFlags: 0,+ decision: { action: "record", recordInputs: false, recordOutputs: false },+ });+ initial = { ...initial, serializedContext: serializeContext(ctx) };+ const message = {+ ...payload(),+ requestTraceContext: { traceId: "1".repeat(32), spanId: "2".repeat(16), traceFlags: 1 },+ };+ await dispatch(message);+ expect(callback).toHaveBeenCalledOnce();+ expect(tracing.exporter.getFinishedSpans()).toEqual([]);+});diff --git a/packages/eve/src/runtime/connections/events/lifecycle-step.ts b/packages/eve/src/runtime/connections/events/lifecycle-step.tsnew file mode 100644index 000000000..41fe837c3--- /dev/null+++ b/packages/eve/src/runtime/connections/events/lifecycle-step.ts@@ -0,0 +1,167 @@+import { createHash } from "node:crypto";+import { getWorkflowMetadata, getWritable } from "#compiled/@workflow/core/index.js";+import { deserializeContext } from "#context/serialize.js";+import { readHttpStatus } from "#runtime/connections/mcp-client.js";+import { resolveBinding } from "#runtime/connections/events/dispatch-step.js";+import { startConnectionEventDeliveryRun } from "#runtime/connections/events/owner.js";+import { connectionEventDestination } from "#runtime/connections/events/path.js";+import {+ CONNECTION_EVENT_SUBSCRIPTION_NAMESPACE,+ type ConnectionEventSubscribeOutcome,+ type ConnectionEventSubscribeResult,+ type EventBinding,+} from "#runtime/connections/events/state.js";+import type { ConnectionEventPayload } from "#runtime/connections/events/delivery.js";+import { withConnectionEventSpan } from "#tracing/eve/connection-events.js";++/**+ * Subscribes from inside the watch run, after its hook is registered, so a+ * delivery that beats the subscribe response finds the binding it runs under.+ * The key is the run's own: a retried step reuses it, and a later run for the+ * same watch, after this one ended, subscribes afresh.+ */+export async function openConnectionEventStep(input: {+ readonly serializedContext: Record<string, unknown>;+ readonly binding: EventBinding;+}): Promise<ConnectionEventSubscribeResult> {+ "use step";+ const idempotencyKey = createHash("sha256")+ .update(JSON.stringify([input.binding.id, getWorkflowMetadata().workflowRunId]))+ .digest("hex");+ const outcome = await subscribeConnectionEvent(+ input.serializedContext,+ input.binding,+ idempotencyKey,+ );+ await publishOutcome(outcome);+ return outcome;+}++/**+ * Connect's definitive refusals reach the model, and the run then ends+ * without a watch. Anything else, such as a timeout after Connect may have+ * created the subscription, throws so the step retries with the same+ * idempotency key.+ */+export async function subscribeConnectionEvent(+ serializedContext: Record<string, unknown>,+ binding: EventBinding,+ idempotencyKey: string,+): Promise<ConnectionEventSubscribeResult> {+ const ctx = await deserializeContext(serializedContext);+ const resolved = resolveBinding(ctx, binding);+ if (resolved === undefined)+ return { error: "This connection no longer accepts the subscription's binding." };+ const { connection } = resolved;+ try {+ const subscription = await withConnectionEventSpan(+ {+ ctx,+ connectionName: connection.connectionName,+ bindingId: binding.id,+ operation: "subscribe",+ },+ async () => {+ const adapter = await createAdapter(resolved);+ return adapter.subscribe({+ ...binding.request,+ idempotencyKey,+ options: { timeout: 30_000 },+ });+ },+ );+ // Snapshot the SDK's readonly JSON into the run's owned state.+ return { subscription: structuredClone(subscription) };+ } catch (error) {+ const status = readHttpStatus(error);+ if (status === undefined || !isRefusal(status)) throw error;+ return { error: error instanceof Error ? error.message : String(error), status };+ }+}++/**+ * One unsubscribe attempt for a stopped watch. "done" only once Connect has+ * finished cleanup or no longer has the subscription. Anything else, whether+ * Connect still cleaning up, an outage, refused credentials or a connection a+ * redeploy removed, is "pending": the watch keeps its hook and repeats the+ * attempt with its own durable backoff, so Workflow's step retries never+ * decide when cleanup gives up.+ */+export async function unsubscribeConnectionEventStep(input: {+ readonly serializedContext: Record<string, unknown>;+ readonly binding: EventBinding;+ readonly subscriptionId: string;+}): Promise<"pending" | "done"> {+ "use step";+ const ctx = await deserializeContext(input.serializedContext);+ const resolved = resolveBinding(ctx, input.binding);+ if (resolved === undefined) return "pending";+ try {+ const subscription = await withConnectionEventSpan(+ {+ ctx,+ connectionName: resolved.connection.connectionName,+ bindingId: input.binding.id,+ subscriptionId: input.subscriptionId,+ operation: "unsubscribe",+ },+ async () =>+ (await createAdapter(resolved)).unsubscribe({+ id: input.subscriptionId,+ options: { timeout: 30_000 },+ }),+ );+ return subscription.cleanupStatus === "pending" ? "pending" : "done";+ } catch (error) {+ const status = readHttpStatus(error);+ return status === 404 || status === 410 ? "done" : "pending";+ }+}++/** Starts a delivery the watch's run took because it arrived before the subscribe response. */+export async function startConnectionEventDeliveryStep(input: {+ readonly binding: EventBinding;+ readonly serializedContext: Record<string, unknown>;+ readonly payload: ConnectionEventPayload;+}): Promise<void> {+ "use step";+ await startConnectionEventDeliveryRun(input);+}++function createAdapter({+ connection,+ principal,+ events,+}: NonNullable<ReturnType<typeof resolveBinding>>) {+ return events.backend.createAdapter({+ principal,+ connection: { url: connection.url },+ destination: { path: connectionEventDestination(connection.connectionName) },+ });+}++/** A 4xx other than a timeout or rate limit: retrying the same request can't succeed. */+function isRefusal(status: number): boolean {+ return status >= 400 && status < 500 && status !== 408 && status !== 429;+}++/**+ * Publishes, for a duplicate run's caller, the run that owns the watch.+ */+export async function publishConnectionEventOutcomeStep(+ outcome: ConnectionEventSubscribeOutcome,+): Promise<void> {+ "use step";+ await publishOutcome(outcome);+}++async function publishOutcome(outcome: ConnectionEventSubscribeOutcome): Promise<void> {+ const writer = getWritable<ConnectionEventSubscribeOutcome>({+ namespace: CONNECTION_EVENT_SUBSCRIPTION_NAMESPACE,+ }).getWriter();+ try {+ await writer.write(outcome);+ } finally {+ writer.releaseLock();+ }+}diff --git a/packages/eve/src/runtime/connections/events/owner.test.ts b/packages/eve/src/runtime/connections/events/owner.test.tsnew file mode 100644index 000000000..da501fde5--- /dev/null+++ b/packages/eve/src/runtime/connections/events/owner.test.ts@@ -0,0 +1,148 @@+import { beforeEach, expect, it, vi } from "vitest";++import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";+import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";+import type { ConnectionEventPayload } from "./delivery.js";+import type { ConnectionEventSubscribeOutcome, EventBinding } from "./state.js";++const { hooks, runs, started, resumed } = vi.hoisted(() => ({+ hooks: new Map<string, { runId: string; metadata: unknown }>(),+ runs: new Map<string, { published: unknown[]; outcome: Promise<unknown> }>(),+ started: vi.fn(async (_reference: unknown, _args: unknown[]) => ({ runId: "watch-run" })),+ resumed: vi.fn(async (_token: string, _value: unknown) => ({})),+}));+vi.mock("#internal/workflow/runtime.js", () => ({+ async getHookByToken(token: string) {+ const hook = hooks.get(token);+ if (hook === undefined) throw new HookNotFoundError(token);+ return { runId: hook.runId, metadata: Promise.resolve(hook.metadata) };+ },+ async resumeHook(token: string, value: unknown) {+ if (!hooks.has(token)) throw new HookNotFoundError(token);+ return resumed(token, value);+ },+ getRun(runId: string) {+ const run = runs.get(runId)!;+ // The run's published subscribe outcome, as its stream delivers it.+ return {+ getReadable: () =>+ Object.assign(+ new ReadableStream({+ async pull(controller) {+ controller.enqueue(await run.outcome);+ controller.close();+ },+ }),+ { getTailIndex: async () => run.published.length - 1 },+ ),+ };+ },+}));+vi.mock("#execution/workflow-runtime.js", () => ({+ connectionEventWorkflowReference: { workflowId: "watch" },+ connectionEventDeliveryWorkflowReference: { workflowId: "delivery" },+ startWorkflowOnCurrentDeployment: started,+}));++const {+ findConnectionEventOwner,+ retireConnectionEventOwner,+ startConnectionEventDelivery,+ startConnectionEventOwner,+} = await import("./owner.js");+const { connectionEventHookToken } = await import("./path.js");++const binding = {+ id: "binding-1",+ sessionId: "session-1",+ auth: null,+ connectionName: "issues",+} as EventBinding;+const token = connectionEventHookToken(binding.id);+const bundle = {+ compiledArtifactsSource: { kind: "disk", appRoot: "/virtual/events" },+} as CompiledBundle;+const payload = {+ kind: "connection-event",+ connectionName: "issues",+ bindingId: binding.id,+ delivery: { deliveryId: "delivery-1", subscriptionId: "sub_1" },+} as ConnectionEventPayload;+const subscription = {+ id: "sub_1",+ name: "issue.created",+ arguments: {},+ status: "active" as const,+ expiresAt: null,+};+/** A running watch holding its hook; call the result to publish its subscribe outcome. */+function holdWatch() {+ let publish!: (value: unknown) => void;+ const run = {+ published: [] as unknown[],+ outcome: new Promise((resolve) => (publish = resolve)),+ };+ runs.set("watch-run", run);+ hooks.set(token, { runId: "watch-run", metadata: binding });+ return (value: ConnectionEventSubscribeOutcome) => {+ run.published.push(value);+ publish(value);+ };+}++beforeEach(() => {+ hooks.clear();+ runs.clear();+ started.mockClear();+ resumed.mockClear();+});++it("starts each delivery in its own run, under the binding its watch's hook carries", async () => {+ holdWatch()({ subscription });+ expect(await startConnectionEventDelivery(payload, bundle)).toBe(true);+ expect(started).toHaveBeenCalledExactlyOnceWith({ workflowId: "delivery" }, [+ { binding, payload, serializedContext: expect.any(Object) },+ ]);+ // The watch's own run takes nothing per delivery.+ expect(resumed).not.toHaveBeenCalled();+});++it("refuses a delivery for a subscription its watch did not create", async () => {+ holdWatch()({ subscription });+ const other = { ...payload, delivery: { ...payload.delivery, subscriptionId: "sub_other" } };+ expect(await startConnectionEventDelivery(other, bundle)).toBe(false);+ expect(started).not.toHaveBeenCalled();+});++it("refuses a delivery when its watch has ended", async () => {+ expect(await startConnectionEventDelivery(payload, bundle)).toBe(false);+ expect(started).not.toHaveBeenCalled();+});++it("hands a delivery that beats the subscribe response to the watch's own run", async () => {+ holdWatch();+ expect(await startConnectionEventDelivery(payload, bundle)).toBe(true);+ expect(resumed).toHaveBeenCalledExactlyOnceWith(token, { kind: "delivery", payload });+ expect(started).not.toHaveBeenCalled();+});++it("asks a running watch to retire, and reports one that has ended", async () => {+ expect(await retireConnectionEventOwner(binding.id)).toBe(false);+ holdWatch();+ expect(await retireConnectionEventOwner(binding.id)).toBe(true);+ expect(resumed).toHaveBeenCalledExactlyOnceWith(token, { kind: "retire" });+});++it("reports a subscribe still in flight when the caller stops waiting, then its later result", async () => {+ const publish = holdWatch();+ const caller = new AbortController();+ const subscribing = startConnectionEventOwner(binding, bundle, caller.signal);+ caller.abort();+ expect(await subscribing).toBeUndefined();+ expect(await findConnectionEventOwner(binding.id)).toEqual({+ owner: binding,+ subscription: undefined,+ });+ publish({ subscription });+ expect(await findConnectionEventOwner(binding.id)).toEqual({ owner: binding, subscription });+});diff --git a/packages/eve/src/runtime/connections/events/owner.ts b/packages/eve/src/runtime/connections/events/owner.tsnew file mode 100644index 000000000..81dfa7199--- /dev/null+++ b/packages/eve/src/runtime/connections/events/owner.ts@@ -0,0 +1,190 @@+import { ContextContainer } from "#context/container.js";+import { AuthKey, SessionIdKey, SessionTraceSeedKey } from "#context/keys.js";+import { serializeContext } from "#context/serialize.js";+import { BundleKey, type CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";+import type { ConnectionEventPayload } from "#runtime/connections/events/delivery.js";+import {+ CONNECTION_EVENT_SUBSCRIPTION_NAMESPACE,+ type ConnectionEventSubscribeOutcome,+ type ConnectionEventSubscribeResult,+ type EventBinding,+} from "#runtime/connections/events/state.js";+import type { ConnectionEventWatchMessage } from "#runtime/connections/events/workflow.js";+import {+ connectionEventDeliveryWorkflowReference,+ connectionEventWorkflowReference,+ startWorkflowOnCurrentDeployment,+} from "#execution/workflow-runtime.js";+import { getHookByToken, getRun, resumeHook } from "#internal/workflow/runtime.js";+import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";+import { connectionEventHookToken } from "#runtime/connections/events/path.js";+import type { ManagedEventSubscription } from "#shared/connection-events.js";++/** Bounds the wait for a run's first step, which itself subscribes with a 30 s timeout. */+const SUBSCRIBE_OUTCOME_TIMEOUT_MS = 90_000;++/** The context a watch's runs execute in: its creator's auth and origin session. */+function bindingContext(binding: EventBinding, bundle: CompiledBundle): Record<string, unknown> {+ const ctx = new ContextContainer({ localDevRequest: undefined });+ ctx.set(BundleKey, bundle);+ ctx.set(AuthKey, binding.auth);+ if (binding.traceSeed !== undefined) ctx.set(SessionTraceSeedKey, binding.traceSeed);+ // This is origin metadata, not a conversation owner or a state snapshot.+ ctx.set(SessionIdKey, binding.sessionId);+ return serializeContext(ctx);+}++/**+ * Starts the watch's run, which subscribes once its hook is registered. A+ * watch already running under the binding's id answers instead. Returns+ * undefined when the subscription is still being created after the caller+ * stops waiting: asking for the same watch again finds it.+ */+export async function startConnectionEventOwner(+ binding: EventBinding,+ bundle: CompiledBundle,+ signal?: AbortSignal,+): Promise<ManagedEventSubscription | undefined> {+ const run = await startWorkflowOnCurrentDeployment(connectionEventWorkflowReference, [+ { binding, serializedContext: bindingContext(binding, bundle) },+ ]);+ const outcome = await readSubscribeOutcome(run.runId, signal);+ return outcome && subscriptionFromOutcome(outcome);+}++/**+ * Routes one verified delivery to its watch. Returns false when the watch+ * has ended or never created this subscription, so the receiver tells+ * Connect to stop. A delivery that beats the subscribe response waits in the+ * watch's own hook, and the watch's run starts it once it knows its+ * subscription.+ */+export async function startConnectionEventDelivery(+ payload: ConnectionEventPayload,+ bundle: CompiledBundle,+): Promise<boolean> {+ const watch = await findConnectionEventOwner(payload.bindingId);+ if (watch === undefined) return false;+ if (watch.subscription === undefined)+ return resumeWatch(payload.bindingId, { kind: "delivery", payload });+ if (watch.subscription.id !== payload.delivery.subscriptionId) return false;+ const binding = watch.owner;+ await startConnectionEventDeliveryRun({+ binding,+ serializedContext: bindingContext(binding, bundle),+ payload,+ });+ return true;+}++/** Runs one delivery's callback in its own short run. */+export async function startConnectionEventDeliveryRun(input: {+ readonly binding: EventBinding;+ readonly serializedContext: Record<string, unknown>;+ readonly payload: ConnectionEventPayload;+}): Promise<void> {+ await startWorkflowOnCurrentDeployment(connectionEventDeliveryWorkflowReference, [input]);+}++/** Connect's refusal reaches the caller with its status, so a 401 is classified as a sign-in request. */+export function subscriptionFromOutcome(+ outcome: ConnectionEventSubscribeResult,+): ManagedEventSubscription {+ if ("error" in outcome) throw Object.assign(new Error(outcome.error), { status: outcome.status });+ return outcome.subscription;+}++/**+ * A running watch: who owns it and what it subscribed to. The subscription+ * is undefined while it is still being created. An ended watch's hook ended+ * with its run, so it is not found.+ */+export async function findConnectionEventOwner(+ bindingId: string,+): Promise<+ { owner: EventBinding; subscription: ManagedEventSubscription | undefined } | undefined+> {+ let hook;+ try {+ hook = await getHookByToken(connectionEventHookToken(bindingId));+ } catch (error) {+ if (HookNotFoundError.is(error)) return undefined;+ throw error;+ }+ const outcome = await readPublishedOutcomeNow(hook.runId);+ // The hook's run is the owner, so it never points at another run.+ if (outcome !== undefined && !("subscription" in outcome)) return undefined;+ return { owner: (await hook.metadata) as EventBinding, subscription: outcome?.subscription };+}++/** Asks the watch's run to unsubscribe and end; the run repeats unsubscribe until Connect finishes. */+export async function retireConnectionEventOwner(bindingId: string): Promise<boolean> {+ return resumeWatch(bindingId, { kind: "retire" });+}++async function resumeWatch(+ bindingId: string,+ message: ConnectionEventWatchMessage,+): Promise<boolean> {+ try {+ await resumeHook(connectionEventHookToken(bindingId), message);+ return true;+ } catch (error) {+ if (HookNotFoundError.is(error)) return false;+ throw error;+ }+}++/** What the run that owns this binding subscribed to, following a duplicate run to that owner. */+async function readSubscribeOutcome(+ runId: string,+ signal?: AbortSignal,+): Promise<ConnectionEventSubscribeResult | undefined> {+ const outcome = await readPublishedOutcome(runId, signal);+ if (outcome === undefined || !("ownerRunId" in outcome)) return outcome;+ const owned = await readPublishedOutcome(outcome.ownerRunId, signal);+ if (owned !== undefined && "ownerRunId" in owned)+ throw new Error("Event handler ownership did not resolve.");+ return owned;+}++/** The run's published outcome if it has one yet, without waiting for it. */+async function readPublishedOutcomeNow(+ runId: string,+): Promise<ConnectionEventSubscribeOutcome | undefined> {+ const readable = getRun(runId).getReadable({+ namespace: CONNECTION_EVENT_SUBSCRIPTION_NAMESPACE,+ });+ const tail = await readable.getTailIndex();+ await readable.cancel().catch(() => {});+ return tail < 0 ? undefined : readPublishedOutcome(runId);+}++/** The run's published outcome, or undefined if the caller stops waiting before it is published. */+async function readPublishedOutcome(+ runId: string,+ signal?: AbortSignal,+): Promise<ConnectionEventSubscribeOutcome | undefined> {+ const reader = getRun(runId)+ .getReadable<ConnectionEventSubscribeOutcome>({+ namespace: CONNECTION_EVENT_SUBSCRIPTION_NAMESPACE,+ })+ .getReader();+ const deadline = AbortSignal.any([+ AbortSignal.timeout(SUBSCRIBE_OUTCOME_TIMEOUT_MS),+ ...(signal === undefined ? [] : [signal]),+ ]);+ const abandoned = new Promise<{ value: undefined; abandoned: true }>((resolve) => {+ const abort = () => resolve({ value: undefined, abandoned: true });+ if (deadline.aborted) abort();+ else deadline.addEventListener("abort", abort, { once: true });+ });+ try {+ const read = await Promise.race([reader.read(), abandoned]);+ if ("abandoned" in read) return undefined;+ if (read.value === undefined) throw new Error("Event handler ended before subscribing.");+ return read.value;+ } finally {+ await reader.cancel().catch(() => {});+ }+}diff --git a/packages/eve/src/runtime/connections/events/path.ts b/packages/eve/src/runtime/connections/events/path.tsnew file mode 100644index 000000000..6a86aa587--- /dev/null+++ b/packages/eve/src/runtime/connections/events/path.ts@@ -0,0 +1,21 @@+import { EVE_ROUTE_PREFIX } from "#protocol/routes.js";+import { joinEveRoutePath } from "#shared/eve-route-path.js";+import {+ EVE_PUBLIC_ROUTE_PREFIX_ENV,+ normalizePublicRoutePrefix,+} from "#shared/public-route-prefix.js";++export function connectionEventRoute(connectionName: string): string {+ return `${EVE_ROUTE_PREFIX}/hooks/${encodeURIComponent(connectionName)}`;+}+export function connectionEventDestination(connectionName: string): string {+ return joinEveRoutePath(+ normalizePublicRoutePrefix(process.env[EVE_PUBLIC_ROUTE_PREFIX_ENV]) ?? "",+ connectionEventRoute(connectionName),+ );+}++/** The watch run's hook: the receiver finds it by the binding id Connect echoes in context. */+export function connectionEventHookToken(bindingId: string): string {+ return `eve:connection-event:${bindingId}`;+}diff --git a/packages/eve/src/runtime/connections/events/state.ts b/packages/eve/src/runtime/connections/events/state.tsnew file mode 100644index 000000000..3f5e90ed4--- /dev/null+++ b/packages/eve/src/runtime/connections/events/state.ts@@ -0,0 +1,49 @@+import type { SessionAuthContext } from "#channel/types.js";+import type { SessionTraceSeed } from "#context/keys.js";+import type {+ ManagedEventSubscribeInput,+ ManagedEventSubscription,+} from "#shared/connection-events.js";++/** Who owns a watch. The handler's hook carries it so management can authorize callers. */+export type EventOwner = {+ readonly connectionName: string;+ readonly instanceId: string | undefined;+ readonly connector: string;+ readonly principalKey: string;+ readonly executionPrincipal: string;+};++/** The handler run's input: everything a delivery needs, saved before subscribing. */+export interface EventBinding extends EventOwner {+ readonly id: string;+ readonly sessionId: string;+ readonly auth: SessionAuthContext | null;+ readonly traceSeed?: SessionTraceSeed;+ /** The watch's own run adds the idempotency key, so each run subscribes once. */+ readonly request: Omit<ManagedEventSubscribeInput, "idempotencyKey" | "options">;+}++/** The run publishes its subscription once, so callers outside it can read what it owns. */+export const CONNECTION_EVENT_SUBSCRIPTION_NAMESPACE = "eve.connection-event.subscription";++/** What a run's own subscribe produced. */+export type ConnectionEventSubscribeResult =+ | { readonly subscription: ManagedEventSubscription }+ /** Connect refused the subscription; `status` keeps its HTTP status, such as a 401 that asks for sign-in. */+ | { readonly error: string; readonly status?: number };++export type ConnectionEventSubscribeOutcome =+ | ConnectionEventSubscribeResult+ /** Another run already owns this binding: read the outcome from that run. */+ | { readonly ownerRunId: string };++export function sameEventOwner(left: EventOwner, right: EventOwner): boolean {+ return (+ left.connectionName === right.connectionName &&+ left.instanceId === right.instanceId &&+ left.connector === right.connector &&+ left.principalKey === right.principalKey &&+ left.executionPrincipal === right.executionPrincipal+ );+}diff --git a/packages/eve/src/runtime/connections/events/workflow.test.ts b/packages/eve/src/runtime/connections/events/workflow.test.tsnew file mode 100644index 000000000..f9cc5c8c9--- /dev/null+++ b/packages/eve/src/runtime/connections/events/workflow.test.ts@@ -0,0 +1,276 @@+import { beforeEach, expect, it, vi } from "vitest";++import type { EventBinding } from "./state.js";++/** A deterministic stand-in for Workflow's hooks and sleep: one owner per token. */+const world = vi.hoisted(() => {+ class FakeHook<T> {+ readonly queue: T[] = [];+ waiter: (() => void) | undefined;+ readonly token: string;+ readonly id: string;+ readonly metadata: unknown;+ readonly options: object;+ conflict: string | null = null;+ private readonly owners: Map<string, FakeHook<unknown>>;+ constructor(+ token: string,+ owners: Map<string, FakeHook<unknown>>,+ options: { id: string; metadata: unknown; options: object },+ ) {+ this.token = token;+ this.owners = owners;+ this.id = options.id;+ this.metadata = options.metadata;+ this.options = options.options;+ }+ push(value: T) {+ this.queue.push(value);+ const waiter = this.waiter;+ this.waiter = undefined;+ waiter?.();+ }+ async next(): Promise<T> {+ while (this.queue.length === 0) await new Promise<void>((resolve) => (this.waiter = resolve));+ return this.queue.shift()!;+ }+ // oxlint-disable-next-line unicorn/no-thenable -- Workflow hooks are awaited for their first payload.+ then<R>(resolve: (value: T) => R, reject: (error: unknown) => R) {+ return this.next().then(resolve, reject);+ }+ async getConflict() {+ return this.conflict === null ? null : { runId: this.conflict };+ }+ async dispose() {+ if (this.owners.get(this.token) === this) this.owners.delete(this.token);+ }+ }+ const owners = new Map<string, FakeHook<unknown>>();+ let created = 0;+ let expire: (() => void) | undefined;+ return {+ owners,+ createHook(options: { token: string; metadata?: unknown }) {+ const previous = owners.get(options.token);+ const hook = new FakeHook<unknown>(options.token, owners, {+ id: `hook-${++created}`,+ metadata: options.metadata,+ options,+ });+ // A held token conflicts; the hook reports which owner holds it.+ if (previous !== undefined) {+ hook.conflict = previous.id;+ return hook;+ }+ owners.set(options.token, hook);+ return hook;+ },+ resume(token: string, value: unknown) {+ const hook = owners.get(token);+ if (hook === undefined) throw new Error(`test world: no hook for ${token}`);+ hook.push(value);+ },+ sleeps: [] as Date[],+ backoffs: [] as number[],+ sleep(until: Date | number) {+ // A finite delay is the unsubscribe backoff; a date is the watch's expiry.+ if (typeof until === "number") {+ world.backoffs.push(until);+ return Promise.resolve();+ }+ world.sleeps.push(until);+ return new Promise<void>((resolve) => (expire = resolve));+ },+ expire: () => expire?.(),+ expiresAt: null as string | null,+ followed: [] as string[],+ /** Settles the watch's subscribe step; tests hold it to model a slow Connect. */+ subscribed: Promise.resolve() as Promise<void>,+ refuse: false,+ unsubscribed: vi.fn(async (_input: unknown): Promise<"pending" | "done"> => "done"),+ started: vi.fn(async (_input: unknown) => {}),+ dispatch: vi.fn(async (_input: unknown) => {}),+ };+});++vi.mock("#compiled/@workflow/core/index.js", () => ({+ createHook: world.createHook,+ sleep: world.sleep,+}));+vi.mock("#runtime/connections/events/dispatch-step.js", () => ({+ dispatchConnectionEventStep: world.dispatch,+}));+vi.mock("#runtime/connections/events/lifecycle-step.js", () => ({+ async openConnectionEventStep() {+ await world.subscribed;+ return world.refuse+ ? { error: "Unauthorized", status: 401 }+ : {+ subscription: {+ id: "sub_1",+ name: "issue.created",+ status: "active",+ expiresAt: world.expiresAt,+ },+ };+ },+ async publishConnectionEventOutcomeStep(outcome: { ownerRunId?: string }) {+ if (outcome.ownerRunId !== undefined) world.followed.push(outcome.ownerRunId);+ },+ unsubscribeConnectionEventStep: world.unsubscribed,+ startConnectionEventDeliveryStep: world.started,+}));++const { connectionEventWorkflow, connectionEventDeliveryWorkflow } = await import("./workflow.js");+const { connectionEventHookToken } = await import("./path.js");++const binding = { id: "binding-1", request: { ttlMs: 3_600_000 } } as EventBinding;+const token = connectionEventHookToken(binding.id);+const watching = () => vi.waitFor(() => expect(world.owners.has(token)).toBe(true));+const delivery = (subscriptionId: string) => ({+ kind: "delivery" as const,+ payload: {+ kind: "connection-event",+ bindingId: binding.id,+ delivery: { deliveryId: `delivery-${subscriptionId}`, subscriptionId },+ },+});++beforeEach(() => {+ world.owners.clear();+ world.sleeps.length = 0;+ world.backoffs.length = 0;+ world.followed.length = 0;+ world.expiresAt = null;+ world.refuse = false;+ world.subscribed = Promise.resolve();+ world.unsubscribed.mockReset().mockResolvedValue("done");+ world.started.mockReset();+ world.dispatch.mockReset();+});++it("holds the binding in a hook that ends with the run", async () => {+ const run = connectionEventWorkflow({ binding, serializedContext: {} });+ await watching();+ const hook = world.owners.get(token)!;+ expect(hook.metadata).toEqual(binding);+ // No retention: once the run ends, the watch is not found.+ expect(hook.options).not.toHaveProperty("experimental_minRetention");+ world.resume(token, { kind: "retire" });+ await run;+});++it("unsubscribes when stopped, and ends only once Connect finishes cleanup", async () => {+ world.unsubscribed+ .mockResolvedValueOnce("pending")+ .mockResolvedValueOnce("pending")+ .mockResolvedValueOnce("done");+ const run = connectionEventWorkflow({ binding, serializedContext: {} });+ await watching();+ world.resume(token, { kind: "retire" });+ await run;+ expect(world.unsubscribed).toHaveBeenCalledTimes(3);+ expect(world.unsubscribed).toHaveBeenCalledWith({+ serializedContext: {},+ binding,+ subscriptionId: "sub_1",+ });+ // Each repeat waits durably, longer each time.+ expect(world.backoffs).toEqual([5_000, 10_000]);+});++it("keeps the watch through repeated failed unsubscribes until Connect's cleanup completes", async () => {+ let attempts = 0;+ world.unsubscribed.mockImplementation(async () => {+ // Every failed attempt leaves the watch reachable for get and stop.+ expect(world.owners.has(token)).toBe(true);+ return ++attempts <= 5 ? "pending" : "done";+ });+ const run = connectionEventWorkflow({ binding, serializedContext: {} });+ await watching();+ world.resume(token, { kind: "retire" });+ await run;+ expect(world.unsubscribed).toHaveBeenCalledTimes(6);+ expect(world.backoffs).toEqual([5_000, 10_000, 20_000, 40_000, 80_000]);+});++it("takes a stop that arrives before the subscribe response, then unsubscribes what it created", async () => {+ let respond!: () => void;+ world.subscribed = new Promise((resolve) => (respond = resolve));+ const run = connectionEventWorkflow({ binding, serializedContext: {} });+ await watching();+ world.resume(token, { kind: "retire" });+ respond();+ await run;+ expect(world.unsubscribed).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ subscriptionId: "sub_1" }),+ );+});++it("starts a delivery that beat the subscribe response once, and drops another subscription's", async () => {+ let respond!: () => void;+ world.subscribed = new Promise((resolve) => (respond = resolve));+ const run = connectionEventWorkflow({ binding, serializedContext: {} });+ await watching();+ world.resume(token, delivery("sub_other"));+ world.resume(token, delivery("sub_1"));+ await Promise.resolve();+ expect(world.started).not.toHaveBeenCalled();+ respond();+ await vi.waitFor(() => expect(world.started).toHaveBeenCalledTimes(1));+ expect(world.started).toHaveBeenCalledWith({+ binding,+ serializedContext: {},+ payload: delivery("sub_1").payload,+ });+ world.resume(token, { kind: "retire" });+ await run;+ expect(world.started).toHaveBeenCalledTimes(1);+});++it("ends the watch at its subscription's expiry without unsubscribing", async () => {+ world.expiresAt = "2026-10-08T00:00:00.000Z";+ const run = connectionEventWorkflow({ binding, serializedContext: {} });+ await vi.waitFor(() => expect(world.sleeps).toHaveLength(1));+ expect(world.sleeps[0]).toEqual(new Date(world.expiresAt));+ world.expire();+ await run;+ expect(world.unsubscribed).not.toHaveBeenCalled();+});++it("runs each delivery in its own run, so a failed callback leaves the watch to a later stop", async () => {+ const run = connectionEventWorkflow({ binding, serializedContext: {} });+ await watching();+ const live = world.owners.get(token);+ const input = {+ binding,+ serializedContext: {},+ payload: { kind: "connection-event", delivery: { deliveryId: "delivery-1" } },+ } as Parameters<typeof connectionEventDeliveryWorkflow>[0];+ world.dispatch.mockRejectedValueOnce(new Error("callback failed"));+ await expect(connectionEventDeliveryWorkflow(input)).rejects.toThrow("callback failed");+ await connectionEventDeliveryWorkflow(input);+ expect(world.dispatch).toHaveBeenCalledWith(input);+ // The watch's run saw neither delivery and still holds its hook.+ expect(world.owners.get(token)).toBe(live);+ expect(live?.queue).toEqual([]);+ world.resume(token, { kind: "retire" });+ await run;+});++it("points a second run for the same watch at the run that owns it", async () => {+ const first = connectionEventWorkflow({ binding, serializedContext: {} });+ await watching();+ const owner = world.owners.get(token)!.id;+ await connectionEventWorkflow({ binding, serializedContext: {} });+ expect(world.followed).toEqual([owner]);+ expect(world.owners.get(token)?.id).toBe(owner);+ world.resume(token, { kind: "retire" });+ await first;+});++it("ends a run whose subscribe Connect refused, releasing its token", async () => {+ world.refuse = true;+ await connectionEventWorkflow({ binding, serializedContext: {} });+ expect(world.owners.has(token)).toBe(false);+});diff --git a/packages/eve/src/runtime/connections/events/workflow.ts b/packages/eve/src/runtime/connections/events/workflow.tsnew file mode 100644index 000000000..19158c720--- /dev/null+++ b/packages/eve/src/runtime/connections/events/workflow.ts@@ -0,0 +1,89 @@+import { createHook, sleep, type HookOptions } from "#compiled/@workflow/core/index.js";+import { claimHookOwnership, disposeHook, isHookConflictError } from "#execution/hook-ownership.js";+import { parseJsonObject } from "#shared/json.js";+import type { ConnectionEventPayload } from "#runtime/connections/events/delivery.js";+import { connectionEventHookToken } from "#runtime/connections/events/path.js";+import type { EventBinding } from "#runtime/connections/events/state.js";+import { dispatchConnectionEventStep } from "#runtime/connections/events/dispatch-step.js";+import {+ openConnectionEventStep,+ publishConnectionEventOutcomeStep,+ startConnectionEventDeliveryStep,+ unsubscribeConnectionEventStep,+} from "#runtime/connections/events/lifecycle-step.js";++export type ConnectionEventWatchMessage =+ | { readonly kind: "retire" }+ /** A delivery that reached the receiver before this run published its subscription. */+ | { readonly kind: "delivery"; readonly payload: ConnectionEventPayload };++/** Unsubscribe repeats until Connect's cleanup completes, through outages and refusals. */+const FIRST_UNSUBSCRIBE_RETRY_MS = 5_000;+const LAST_UNSUBSCRIBE_RETRY_MS = 3_600_000;++/**+ * Holds one watch: its hook carries the binding every delivery runs under,+ * and the run waits until the watch is stopped, terminated or expires.+ * Deliveries run in their own {@link connectionEventDeliveryWorkflow}, so+ * this run's log only grows by the deliveries that arrive before its+ * subscribe response does. The hook ends with the run: an ended watch is+ * not found.+ */+export async function connectionEventWorkflow(input: {+ readonly binding: EventBinding;+ readonly serializedContext: Record<string, unknown>;+}): Promise<void> {+ "use workflow";+ const { binding, serializedContext } = input;+ const hook = createHook<ConnectionEventWatchMessage>({+ token: connectionEventHookToken(binding.id),+ metadata: parseJsonObject(binding) as HookOptions["metadata"],+ });+ try {+ await claimHookOwnership(hook);+ } catch (error) {+ if (!isHookConflictError(error) || typeof error.conflictingRunId !== "string") throw error;+ // The same watch was asked for again while it runs: its caller reads the first run.+ await publishConnectionEventOutcomeStep({ ownerRunId: error.conflictingRunId });+ return;+ }+ const opened = await openConnectionEventStep({ serializedContext, binding });+ if ("error" in opened) {+ // Nothing was subscribed: asking for the same watch again starts over.+ await disposeHook(hook);+ return;+ }+ const { id: subscriptionId, expiresAt } = opened.subscription;+ // Connect ends the subscription at expiresAt and sends nothing more.+ const expiry = expiresAt === null ? undefined : sleep(new Date(expiresAt));+ while (true) {+ const message = await (expiry === undefined ? hook : Promise.race([hook, expiry]));+ if (message === undefined) return;+ if (message.kind === "retire") break;+ // Connect verifies the destination, not the subscription: only this run's own runs.+ if (message.payload.delivery.subscriptionId === subscriptionId)+ await startConnectionEventDeliveryStep({+ binding,+ serializedContext,+ payload: message.payload,+ });+ }+ let retryMs = FIRST_UNSUBSCRIBE_RETRY_MS;+ while (+ (await unsubscribeConnectionEventStep({ serializedContext, binding, subscriptionId })) ===+ "pending"+ ) {+ await sleep(retryMs);+ retryMs = Math.min(retryMs * 2, LAST_UNSUBSCRIBE_RETRY_MS);+ }+}++/** Runs one delivery's callback in its own short run. */+export async function connectionEventDeliveryWorkflow(input: {+ readonly binding: EventBinding;+ readonly serializedContext: Record<string, unknown>;+ readonly payload: ConnectionEventPayload;+}): Promise<void> {+ "use workflow";+ await dispatchConnectionEventStep(input);+}diff --git a/packages/eve/src/runtime/connections/mcp-client.ts b/packages/eve/src/runtime/connections/mcp-client.tsindex 5bc2240c1..4110820af 100644--- a/packages/eve/src/runtime/connections/mcp-client.ts+++ b/packages/eve/src/runtime/connections/mcp-client.ts@@ -1,3 +1,4 @@+import { ConnectionEventActions, isEventAction } from "#runtime/connections/events/actions.js";import { createMCPClient, type MCPClient } from "#compiled/@ai-sdk/mcp/index.js";import type { ToolSet } from "ai";@@ -60,9 +61,36 @@ export class McpConnectionClient implements ConnectionClient {#connection: ResolvedConnectionDefinition;/** Whether the current transport connected without a bearer because none was available yet. */#anonymous = false;+ readonly eventActions: ConnectionClient["eventActions"];constructor(connection: ResolvedConnectionDefinition) {this.#connection = connection;+ if (connection.experimental_events !== undefined) {+ const events = new ConnectionEventActions(+ connection,+ connection.experimental_events,+ () => resolveHeaders(connection),+ this.#forwardingFetch(),+ );+ this.eventActions = {+ ownsName: isEventAction,+ recoveryMetadata: () => events.recoveryMetadata(),+ metadata: async () => {+ try {+ return await events.metadata();+ } catch (error) {+ return await this.#rethrowClassified(error);+ }+ },+ execute: async (name, args, options) => {+ try {+ return await events.execute(name, args, options);+ } catch (error) {+ return await this.#rethrowClassified(error);+ }+ },+ };+ }}/**@@ -143,8 +171,8 @@ export class McpConnectionClient implements ConnectionClient {}/**- * Returns cached tool metadata for all tools this connection exposes,- * after applying any configured tool filter.+ * Returns cached tool metadata for all tools this connection exposes. The+ * catalog applies the connection's tool filter to the listing.** The first call fetches tools from the server via `listTools()` and* creates the AI SDK tool set in parallel. Subsequent calls return@@ -152,8 +180,7 @@ export class McpConnectionClient implements ConnectionClient {* promise.*/async getToolMetadata(): Promise<readonly ConnectionToolMetadata[]> {- const cache = await this.#ensureTools();- return cache.metadata;+ return (await this.#ensureTools()).metadata;}/**@@ -242,18 +269,12 @@ export class McpConnectionClient implements ConnectionClient {protocolVersion: client.initializeResult?.protocolVersion,});- const filter = this.#connection.tools;- const filteredTools =- filter !== undefined- ? listResult.tools.filter((t) => passesToolFilter(t.name, filter))- : listResult.tools;-// `toolsFromDefinitions` returns `McpToolSet<"automatic">`, whose// elements are `Tool<unknown, CallToolResult>`. The AI SDK's// `ToolSet` constraint only admits `Tool<any | never, any | never>`,// so a single-hop cast is required — the runtime shape is identical.const providedArgumentNames = Object.keys(this.#connection.toolCall?.providedArguments ?? {});- const projectedTools = filteredTools.map((tool) => ({+ const projectedTools = listResult.tools.map((tool) => ({...tool,inputSchema: omitProvidedArgumentsFromSchema(tool.inputSchema, providedArgumentNames),}));@@ -386,7 +407,7 @@ function isMcpHttpFallbackRetryableError(error: unknown): boolean {return status === 400 || status === 404 || status === 405;}-function readHttpStatus(error: unknown): number | undefined {+export function readHttpStatus(error: unknown): number | undefined {for (const candidate of walkErrorChain(error)) {if (!isObject(candidate)) {continue;diff --git a/packages/eve/src/runtime/connections/openapi-client.test.ts b/packages/eve/src/runtime/connections/openapi-client.test.tsindex d38eb9289..0660c521f 100644--- a/packages/eve/src/runtime/connections/openapi-client.test.ts+++ b/packages/eve/src/runtime/connections/openapi-client.test.ts@@ -284,15 +284,6 @@ describe("OpenApiConnectionClient", () => {expect(JSON.stringify(createItem?.inputSchema)).not.toContain("nullable");});- it("applies an operations allow filter", async () => {- const client = new OpenApiConnectionClient(- makeConnection({ tools: { allow: ["getProject"] } }),- );- const metadata = await client.getToolMetadata();-- expect(metadata.map((m) => m.name)).toEqual(["getProject"]);- });-it("substitutes path params, appends query, and attaches auth on execute", async () => {const fetchMock = vi.fn(async (_url: URL, _init: RequestInit) =>diff --git a/packages/eve/src/runtime/connections/openapi-client.ts b/packages/eve/src/runtime/connections/openapi-client.tsindex 9222080b1..eef02af26 100644--- a/packages/eve/src/runtime/connections/openapi-client.ts+++ b/packages/eve/src/runtime/connections/openapi-client.ts@@ -1,6 +1,6 @@import { createLogger } from "#internal/logging.js";import type { ResolvedConnectionDefinition } from "#runtime/types.js";-import { passesToolFilter, resolveHeaders } from "#runtime/connections/mcp-client.js";+import { resolveHeaders } from "#runtime/connections/mcp-client.js";import {omitProvidedArgumentsFromSchema,resolveProvidedArguments,@@ -145,17 +145,11 @@ export class OpenApiConnectionClient implements ConnectionClient {const baseUrl = this.#resolveBaseUrl(document);const operations = this.#extractOperations(document);- const filter = this.#connection.tools;- const selected =- filter !== undefined- ? operations.filter((op) => passesToolFilter(op.toolName, filter))- : operations;-const metadata: ConnectionToolMetadata[] = [];const operationMap = new Map<string, OpenApiOperation>();const providedArgumentNames = Object.keys(this.#connection.toolCall?.providedArguments ?? {});- for (const operation of selected) {+ for (const operation of operations) {let inputSchema: JsonObject;try {inputSchema = parseJsonObject(diff --git a/packages/eve/src/runtime/resolve-connection.ts b/packages/eve/src/runtime/resolve-connection.tsindex 40ccf992f..04df0c29e 100644--- a/packages/eve/src/runtime/resolve-connection.ts+++ b/packages/eve/src/runtime/resolve-connection.ts@@ -135,10 +135,26 @@ export async function resolveConnectionDefinition(}if (definition.experimental_events === true) {- result.experimental_events = normalizeMcpClientConnectionDefinition(+ const callbacks = normalizeMcpClientConnectionDefinition(resolvedRecord,`Connection "${definition.connectionName}":`,).experimental_events;+ const authorization =+ typeof result.authorization === "object" ? result.authorization : undefined;+ if (+ callbacks === undefined ||+ authorization?.vercelConnect?.experimental_events === undefined+ )+ throw new ResolveAgentError(+ `Connection "${definition.connectionName}": experimental_events requires a static Connect auth provider with the events bridge.`,+ { logicalPath: definition.logicalPath, sourceId: definition.sourceId },+ );+ result.experimental_events = {+ callbacks,+ authorization,+ connector: authorization.vercelConnect.connector,+ backend: authorization.vercelConnect.experimental_events,+ };}if (hasHeaders) {diff --git a/packages/eve/src/runtime/types.ts b/packages/eve/src/runtime/types.tsindex d9ffc80e8..984bc329a 100644--- a/packages/eve/src/runtime/types.ts+++ b/packages/eve/src/runtime/types.ts@@ -1,4 +1,5 @@import type { Experimental_ConnectionEvents } from "#public/definitions/connections/events.js";+import type { ConnectionEventsBackend } from "#shared/connection-events.js";import type { ChannelAdapter } from "#channel/adapter.js";import type { CompiledChannel } from "#channel/compiled-channel.js";import type { NormalizedChannelCorsOptions } from "#channel/cors.js";@@ -100,8 +101,17 @@ export type ResolvedScheduleDefinition = Readonly<* Both `authorization` and `headers` are optional — a connection to a* server that requires no authentication (e.g. localhost) may omit both.*/+/** A connection's event watching, checked once when the connection resolves. */+export interface ResolvedConnectionEvents {+ readonly callbacks: Experimental_ConnectionEvents;+ /** The static Connect authorization every watch subscribes and runs under. */+ readonly authorization: Readonly<AuthorizationDefinition>;+ readonly connector: string;+ readonly backend: ConnectionEventsBackend;+}+export interface ResolvedConnectionDefinition extends ResolvedModuleSourceRef {- readonly experimental_events?: Experimental_ConnectionEvents;+ readonly experimental_events?: ResolvedConnectionEvents;readonly protocolVersionDiscovery?: boolean;/** MCP only: send the turn's principals in `eve-forwarded-principal`. */readonly forwardPrincipal?: boolean;diff --git a/packages/eve/src/setup/integrations/self-modification/setup.test.ts b/packages/eve/src/setup/integrations/self-modification/setup.test.tsindex f1f79bd9b..41f01b54f 100644--- a/packages/eve/src/setup/integrations/self-modification/setup.test.ts+++ b/packages/eve/src/setup/integrations/self-modification/setup.test.ts@@ -151,7 +151,7 @@ describe("self-modification integration setup", () => {projectId: "project",});expect(deps.ensurePackageDependencies).toHaveBeenCalledWith({- dependencies: { "@vercel/connect": "2.2.0", microsandbox: "0.5.5" },+ dependencies: { "@vercel/connect": "2.5.2", microsandbox: "0.5.5" },projectRoot: "/project",});expect(deps.installScaffoldDependencies).toHaveBeenCalledWith(diff --git a/packages/eve/src/setup/scaffold/version-tokens.ts b/packages/eve/src/setup/scaffold/version-tokens.tsindex f2b9fd703..d3c1958ba 100644--- a/packages/eve/src/setup/scaffold/version-tokens.ts+++ b/packages/eve/src/setup/scaffold/version-tokens.ts@@ -28,7 +28,7 @@ function bareToken(name: string): string {const NODE_ENGINE_TOKEN = bareToken("NODE_ENGINE");-export const DEFAULT_CONNECT_PACKAGE_VERSION = "2.2.0";+export const DEFAULT_CONNECT_PACKAGE_VERSION = "2.5.2";export const DEFAULT_MICROSANDBOX_PACKAGE_VERSION = "0.5.5";const TOKEN_SOURCES: Readonly<Record<string, TokenSource>> = {diff --git a/packages/eve/src/shared/connection-events.ts b/packages/eve/src/shared/connection-events.tsindex 06797d8ae..12a9f21bd 100644--- a/packages/eve/src/shared/connection-events.ts+++ b/packages/eve/src/shared/connection-events.ts@@ -27,11 +27,6 @@ export interface ConnectionEventsAdapter {id: string;options?: { timeout?: number };}): Promise<ManagedEventSubscription>;- listSubscriptions(input?: {- cursor?: string;- limit?: number;- status?: ManagedEventSubscription["status"];- }): Promise<{ subscriptions: ManagedEventSubscription[]; nextCursor?: string }>;unsubscribe(input: {id: string;options?: { timeout?: number };diff --git a/packages/eve/src/tools/provided/sleep-workflow.ts b/packages/eve/src/tools/provided/sleep-workflow.tsindex 2e62344fe..9a5a7309c 100644--- a/packages/eve/src/tools/provided/sleep-workflow.ts+++ b/packages/eve/src/tools/provided/sleep-workflow.ts@@ -10,6 +10,8 @@ export async function executeSleepTool(): Promise<SleepToolOutput> {"use workflow";+ if (ctx.abortSignal.aborted) return { interrupted: true };+const interrupted = new Promise<"interrupted">((resolve) =>ctx.abortSignal.addEventListener("abort", () => resolve("interrupted"), { once: true }),);diff --git a/packages/eve/src/tools/provided/sleep.test.ts b/packages/eve/src/tools/provided/sleep.test.tsindex b7ad79730..6a5da822a 100644--- a/packages/eve/src/tools/provided/sleep.test.ts+++ b/packages/eve/src/tools/provided/sleep.test.ts@@ -41,4 +41,19 @@ describe("sleep", () => {await expect(output).resolves.toEqual({ waitedSeconds: 2.5001 });});++ it.each(["before", "during"])(+ "stops when steering arrives %s execution",+ async (timing) => {+ vi.mocked(workflowSleep).mockImplementation(() => new Promise<void>(() => {}));+ const controller = new AbortController();+ if (timing === "before") controller.abort();++ const output = sleep().execute({ seconds: 600 }, { abortSignal: controller.signal } as never);+ if (timing === "during") controller.abort();++ await expect(output).resolves.toEqual({ interrupted: true });+ },+ 1_000,+ );});diff --git a/packages/eve/src/tracing/eve/connection-events.ts b/packages/eve/src/tracing/eve/connection-events.tsnew file mode 100644index 000000000..315d78a3a--- /dev/null+++ b/packages/eve/src/tracing/eve/connection-events.ts@@ -0,0 +1,223 @@+import { formatTraceparent } from "#protocol/traceparent.js";+import {+ context,+ ROOT_CONTEXT,+ trace,+ type SpanContext,+} from "#compiled/@opentelemetry/api/index.js";+import { otelTelemetry } from "#compiled/@eve/tracing/index.js";+import {+ activeTraceOperation,+ truncateTelemetryText,+ withErrorContent,+} from "#compiled/@eve/tracing/otel.js";+import { contextStorage, type AlsContext } from "#context/container.js";+import { SessionIdKey } from "#context/keys.js";+import { getInstrumentationRuntime } from "#instrumentation/runtime-global.js";+import { readInstrumentationSessionContext } from "#instrumentation/session-context.js";+import { createLogger, logError } from "#internal/logging.js";+import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";+import { resolveTracePolicy } from "#shared/trace-policy.js";+import { ContextAgentTraceStateStore } from "#tracing/eve/agent-trace-context-store.js";+import { markAgentTraceContext } from "#tracing/eve/agent-trace-context.js";+import { withChannelAudience } from "#tracing/eve/channel-audience-context.js";+import { eveOutputMapping } from "#tracing/eve/profile.js";++const log = createLogger("connection.events");++/** Only carry a validated W3C identity across durable steps, never baggage or content policy. */+export function connectionEventTraceContext(value: unknown): SpanContext | undefined {+ if (typeof value !== "object" || value === null) return undefined;+ const { traceId, spanId, traceFlags } = value as Partial<SpanContext>;+ if (+ typeof traceId !== "string" ||+ typeof spanId !== "string" ||+ (traceFlags !== 0 && traceFlags !== 1)+ )+ return undefined;+ const reference = { traceId, spanId, traceFlags };+ return formatTraceparent(reference) === undefined ? undefined : reference;+}++export function connectionEventAttributes(input: {+ connectionName: string;+ sessionId?: string;+ subscriptionId?: string;+ deliveryId?: string;+ bindingId?: string;+}): Record<string, string> {+ const attributes: Record<string, string> = {};+ for (const [key, value] of Object.entries({+ "agent.connection.name": input.connectionName,+ "agent.run.id": input.sessionId,+ "connect.subscription.id": input.subscriptionId,+ "connect.delivery.id": input.deliveryId,+ "eve.connection.event.binding.id": input.bindingId,+ }))+ if (value !== undefined) attributes[key] = truncateTelemetryText(value, 256);+ return attributes;+}++/** Preserve diagnostic categories without logging SDK request objects or provider response bodies. */+export function connectionEventError(error: unknown): Error {+ const summary = new Error("Connection event operation failed");+ if (+ error instanceof Error &&+ [+ "Error",+ "TypeError",+ "RangeError",+ "SyntaxError",+ "AbortError",+ "TimeoutError",+ "MCPClientError",+ ].includes(error.name)+ )+ summary.name = error.name;+ if (typeof error !== "object" || error === null) return summary;+ const candidate = error as { code?: unknown; status?: unknown; statusCode?: unknown };+ const code = candidate.code;+ const status = candidate.statusCode ?? candidate.status;+ const safeCode =+ typeof code === "number" && Number.isFinite(code)+ ? code+ : typeof code === "string" &&+ [+ "invalid_delivery",+ "verification_unavailable",+ "configuration_error",+ "ETIMEDOUT",+ "ECONNRESET",+ "ECONNREFUSED",+ "ENOTFOUND",+ "EAI_AGAIN",+ ].includes(code)+ ? code+ : undefined;+ if (safeCode !== undefined) Object.assign(summary, { code: safeCode });+ if (typeof status === "number" && Number.isInteger(status) && status >= 100 && status <= 599)+ Object.assign(summary, { statusCode: status });+ return summary;+}++type EventOperation =+ | "catalog"+ | "subscribe"+ | "get"+ | "unsubscribe"+ | "onEvent"+ | "onGap"+ | "onTerminated";++/** No model turn is needed to restore a session's trace policy in a durable event step. */+export async function withConnectionEventSpan<T>(+ input: {+ ctx: AlsContext;+ connectionName: string;+ operation: EventOperation;+ subscriptionId?: string;+ deliveryId?: string;+ bindingId?: string;+ requestTraceContext?: SpanContext;+ },+ execute: (reference?: SpanContext) => Promise<T>,+): Promise<T> {+ return contextStorage.run(input.ctx, async () => {+ const runtime = getInstrumentationRuntime();+ const telemetry = otelTelemetry({+ tracerName: "eve.connection.events",+ mapping: eveOutputMapping(),+ });+ const settings = runtime?.otelSettings;+ const sessionId = input.ctx.require(SessionIdKey);+ const attributes = connectionEventAttributes({ ...input, sessionId });+ const run = async (reference?: SpanContext) => {+ try {+ return await execute(reference);+ } catch (error) {+ // SDK and callback errors can include tokens or event bodies. Keep logs structural, too.+ logError(log, "connection event operation failed", connectionEventError(error), {+ ...attributes,+ operation: input.operation,+ });+ throw error;+ }+ };+ if (settings === undefined) return telemetry.suppressed!(() => run());+ const saved = new ContextAgentTraceStateStore().get("session", sessionId);+ const session = readInstrumentationSessionContext(input.ctx);+ const decision =+ session.traceSeed?.decision ??+ saved?.decision ??+ resolveTracePolicy(settings.tracePolicy, {+ ...session.conversation,+ agentName: input.ctx.require(BundleKey).resolvedAgent.config?.name ?? "eve",+ });+ const active = activeTraceOperation();+ const reference =+ connectionEventTraceContext(input.requestTraceContext) ?? active?.reference ?? saved?.context;+ if (+ decision.action === "drop" ||+ active?.capture.emit === false ||+ (session.traceSeed !== undefined && (session.traceSeed.traceFlags & 1) === 0) ||+ (saved !== undefined && (saved.context.traceFlags & 1) === 0) ||+ (reference !== undefined && (reference.traceFlags & 1) === 0)+ )+ return telemetry.suppressed!(() => run());+ const parent =+ reference === undefined+ ? context.active()+ : trace.setSpan(ROOT_CONTEXT, trace.wrapSpanContext(reference));+ const host = markAgentTraceContext(+ withErrorContent(withChannelAudience(parent, session.audience), false),+ );+ const name = `agent.connection.event.${input.operation}`;+ const span = telemetry.startSpan(+ {+ type: "step",+ operationId: name,+ name,+ kind: input.operation.startsWith("on") ? "CONSUMER" : "INTERNAL",+ attributes: { ...attributes, "operation.name": name, "resource.name": name },+ },+ { context: host },+ );+ try {+ const result = await telemetry.run(+ {+ type: "step",+ reference: span.reference,+ capture: { emit: true, recordInputs: false, recordOutputs: false },+ },+ () => run(connectionEventTraceContext(span.reference)),+ host,+ );+ if (+ ["subscribe", "get", "unsubscribe"].includes(input.operation) &&+ typeof result === "object" &&+ result !== null+ ) {+ const subscription = result as { id?: unknown; status?: unknown };+ if (typeof subscription.id === "string")+ span.setAttribute("connect.subscription.id", truncateTelemetryText(subscription.id, 256));+ if (+ typeof subscription.status === "string" &&+ ["pending", "active", "needs_auth", "stopped", "expired", "failed"].includes(+ subscription.status,+ )+ )+ span.setAttribute("connect.subscription.status", subscription.status);+ }+ span.setAttribute("eve.connection.event.outcome", "completed");+ span.setStatus("OK");+ return result;+ } catch (error) {+ span.setAttribute("eve.connection.event.outcome", "failed");+ span.fail(undefined, "connection_event_error");+ throw error;+ } finally {+ span.end();+ await runtime!.forceFlush().catch(() => log.warn("flushing connection event traces failed"));+ }+ });+}diff --git a/packages/eve/src/tracing/eve/mcp.ts b/packages/eve/src/tracing/eve/mcp.tsindex 7125069b4..d0912faf5 100644--- a/packages/eve/src/tracing/eve/mcp.ts+++ b/packages/eve/src/tracing/eve/mcp.ts@@ -59,7 +59,8 @@ export function createMcpTraceFetch(input: {);const annotateRequest =message.method === "tools/call" ||- (message.method === "tools/list" && activeTraceOperation(activeContext)?.type === "mcp");+ ((message.method === "tools/list" || message.method === "events/list") &&+ activeTraceOperation(activeContext)?.type === "mcp");if (annotateRequest) {activeTraceOperation(activeContext)?.mcp?.update(mcpRequestMetadata({@@ -128,7 +129,7 @@ export const MCP_SERIALIZER: ContentSerializer = {export function createMcpTracing() {const telemetry = otelTelemetry({ tracerName: "eve.mcp", mapping: eveOutputMapping() });function start(input: {- method: "tools/list" | "tools/call";+ method: "tools/list" | "tools/call" | "events/list";connectionName: string;toolName?: string;protocolVersion?: string;@@ -180,13 +181,14 @@ export function createMcpTracing() {}return {async list<T>(input: {+ readonly method?: "tools/list" | "events/list";readonly connectionName: string;readonly execute: () => Promise<T>;readonly protocolVersion?: string;}): Promise<T> {const parent = otelContext.active();const span = start({- method: "tools/list",+ method: input.method ?? "tools/list",connectionName: input.connectionName,protocolVersion: input.protocolVersion,executionContext: parent,diff --git a/packages/eve/test/setup/workflow-global-setup.ts b/packages/eve/test/setup/workflow-global-setup.tsindex 9df54ff5e..e818c2d69 100644--- a/packages/eve/test/setup/workflow-global-setup.ts+++ b/packages/eve/test/setup/workflow-global-setup.ts@@ -55,6 +55,9 @@ export default async function setupWorkflowTests(): Promise<void> {async function discoverWorkflowEntries(): Promise<WorkflowBundleDiscoveredEntries> {const inputFiles = [...(await collectWorkflowInputFiles(resolvePackageSourceDirectoryPath("src/execution"))),+ ...(await collectWorkflowInputFiles(+ resolvePackageSourceDirectoryPath("src/runtime/connections/events"),+ )),...(await collectWorkflowInputFiles(resolvePackageSourceDirectoryPath("src/internal/testing"))),...(await collectWorkflowInputFiles(resolvePackageSourceDirectoryPath("src/runtime/subagents"),diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 01e3edf38..dcef6e2f3 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -232,8 +232,8 @@ catalogs:specifier: 19.2.3version: 19.2.3'@vercel/connect':- specifier: 2.3.3- version: 2.3.3+ specifier: 2.5.2+ version: 2.5.2'@vercel/otel':specifier: 2.1.3version: 2.1.3@@ -1885,7 +1885,7 @@ importers:version: 2.8.0'@vercel/connect':specifier: 'catalog:'- version: 2.3.3(@ai-sdk/[email protected]([email protected]))(@auth/[email protected])(@chat-adapter/[email protected]([email protected]([email protected]))([email protected])([email protected]([email protected]))([email protected])([email protected]))(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected])([email protected]))([email protected]([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected](@aws-sdk/[email protected])([email protected])([email protected]))([email protected]([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected]([email protected]))([email protected]))+ version: 2.5.2(@ai-sdk/[email protected]([email protected]))(@chat-adapter/[email protected]([email protected]([email protected]))([email protected])([email protected]([email protected]))([email protected])([email protected]))(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected])([email protected]))([email protected]([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected](@aws-sdk/[email protected])([email protected])([email protected]))([email protected]([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected]([email protected]))([email protected]))'@vercel/detect-agent':specifier: 1.2.3version: 1.2.3@@ -2023,7 +2023,7 @@ importers:dependencies:'@vercel/connect':specifier: 'catalog:'- version: 2.3.3(@ai-sdk/[email protected]([email protected]))(@auth/[email protected])(@chat-adapter/[email protected]([email protected]([email protected]))([email protected])([email protected])([email protected]))(@modelcontextprotocol/[email protected]([email protected])([email protected]))([email protected]([email protected]))(eve@packages+eve)+ version: 2.5.2(@ai-sdk/[email protected]([email protected]))(@chat-adapter/[email protected]([email protected]([email protected]))([email protected])([email protected])([email protected]))(@modelcontextprotocol/[email protected]([email protected])([email protected]))([email protected]([email protected]))(eve@packages+eve)eve:specifier: workspace:*version: link:../eve@@ -2064,7 +2064,7 @@ importers:dependencies:'@vercel/connect':specifier: 'catalog:'- version: 2.3.3(@ai-sdk/[email protected]([email protected]))(@auth/[email protected])(@chat-adapter/[email protected]([email protected]([email protected]))([email protected])([email protected]([email protected]))([email protected])([email protected]))(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected])([email protected]))([email protected]([email protected]))(eve@packages+eve)+ version: 2.5.2(@ai-sdk/[email protected]([email protected]))(@chat-adapter/[email protected]([email protected]([email protected]))([email protected])([email protected]([email protected]))([email protected])([email protected]))(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected])([email protected]))([email protected]([email protected]))(eve@packages+eve)eve:specifier: workspace:*version: link:../eve@@ -7849,8 +7849,8 @@ packages:'@vercel/[email protected]':resolution: {integrity: sha512-KeSN2HBp8puZrj7kVjSEneDi9yBqW4nAD9AnhGhdYjGNpHl7IkXZVb3HnNe0WWc5+20RlUtmAGWNPQ8qP5QBhQ==}- '@vercel/[email protected]':- resolution: {integrity: sha512-kQLt5Pm8wKd7/imzDY9/9u0tf8OuRkAuXI+s7j057FSUrXapAmumJSKwDqnR4ZZqdWoUcNLlFAgVIAdiwcGTcw==}+ '@vercel/[email protected]':+ resolution: {integrity: sha512-sISbygqlFXYb8qfPu/+2Cf/A8IjrlAuZePdag3EDQr2PRA455s7UZtl9Ro674CWsB/saBRmz3jEkw0YsQs8OoQ==}'@vercel/[email protected]':resolution: {integrity: sha512-kQF8LGie/Hbdq9/psJxLE7owRTcqMQMhgybU04gCeR7cbQAr5t8OrjefDNColJv1QSSucFt4pLwRiARVmlOnug==}@@ -7906,11 +7906,11 @@ packages:eve:optional: true- '@vercel/[email protected]':- resolution: {integrity: sha512-Hu9BhaKgY7tBE4pYBKzlqQB0LHl805ht6Qb2EBPPP4sw7Zi/dJMqvsHFVhCqo9n0fcHo4H5vwMYXQ+pMXOhbHA==}+ '@vercel/[email protected]':+ resolution: {integrity: sha512-i7YZCymt8M7ywOKNNcLAtkwV2v1e5rzPWz2mVCKlXA1zBl9jBqRBRL/IAyBVOXJsc4T1OwOVDSQYkswEJ3d8Uw==}peerDependencies:'@ai-sdk/mcp': ^1 || ^2- '@auth/core': '>=0.37.0'+ '@auth/core': '>=0.41.3''@chat-adapter/slack': ^4.0.0'@modelcontextprotocol/sdk': ^1.29.0ai: ^6 || ^7.0.0-beta.0@@ -7991,8 +7991,8 @@ packages:resolution: {integrity: sha512-aeq4/sgVh80zO6j2H+7FRfsG6NOXBrvzV1EEO8IdXPEJgwHIPakP+BFq3QmprsEQ18bIimds07kvaYhm2lehtg==}engines: {node: '>= 20'}- '@vercel/[email protected]':- resolution: {integrity: sha512-TcbdH3YtGS2KU98T99dN4sbf+E4vbJZsJTRN97wKQ7QWQ0BR7U02QX3KN4+5GHxBtKTj1c5CnvTTitc2ZRad0A==}+ '@vercel/[email protected]':+ resolution: {integrity: sha512-l//xMmDTj2WR6EMtfA2BEF2oR7ViKCD1SCxqFKCn1/8wOZBxgxhxkegSGi90ICTc1rB50ZbKuPIslc8aJxAqew==}engines: {node: '>= 20'}'@vercel/[email protected]':@@ -21896,7 +21896,7 @@ snapshots:xdg-app-paths: 5.5.1zod: 4.5.4- '@vercel/[email protected]':+ '@vercel/[email protected]':dependencies:xdg-app-paths: 5.5.1zod: 4.5.4@@ -21939,34 +21939,31 @@ snapshots:ai: 7.0.137([email protected])eve: link:packages/eve- '@vercel/[email protected](@ai-sdk/[email protected]([email protected]))(@auth/[email protected])(@chat-adapter/[email protected]([email protected]([email protected]))([email protected])([email protected])([email protected]))(@modelcontextprotocol/[email protected]([email protected])([email protected]))([email protected]([email protected]))(eve@packages+eve)':+ '@vercel/[email protected](@ai-sdk/[email protected]([email protected]))(@chat-adapter/[email protected]([email protected]([email protected]))([email protected])([email protected])([email protected]))(@modelcontextprotocol/[email protected]([email protected])([email protected]))([email protected]([email protected]))(eve@packages+eve)':dependencies:- '@vercel/oidc': 3.8.9+ '@vercel/oidc': 4.0.1optionalDependencies:'@ai-sdk/mcp': 2.0.67([email protected])- '@auth/core': 0.41.2'@chat-adapter/slack': 4.34.0([email protected]([email protected]))([email protected])([email protected])([email protected])'@modelcontextprotocol/sdk': 1.30.0(@cfworker/[email protected])([email protected])([email protected])ai: 7.0.128([email protected])eve: link:packages/eve- '@vercel/[email protected](@ai-sdk/[email protected]([email protected]))(@auth/[email protected])(@chat-adapter/[email protected]([email protected]([email protected]))([email protected])([email protected]([email protected]))([email protected])([email protected]))(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected])([email protected]))([email protected]([email protected]))(eve@packages+eve)':+ '@vercel/[email protected](@ai-sdk/[email protected]([email protected]))(@chat-adapter/[email protected]([email protected]([email protected]))([email protected])([email protected]([email protected]))([email protected])([email protected]))(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected])([email protected]))([email protected]([email protected]))(eve@packages+eve)':dependencies:- '@vercel/oidc': 3.8.9+ '@vercel/oidc': 4.0.1optionalDependencies:'@ai-sdk/mcp': 2.0.67([email protected])- '@auth/core': 0.41.2'@chat-adapter/slack': 4.41.0([email protected]([email protected]))([email protected])([email protected]([email protected]))([email protected])([email protected])'@modelcontextprotocol/sdk': 1.30.0(@cfworker/[email protected])([email protected])([email protected])ai: 7.0.128([email protected])eve: link:packages/eve- '@vercel/[email protected](@ai-sdk/[email protected]([email protected]))(@auth/[email protected])(@chat-adapter/[email protected]([email protected]([email protected]))([email protected])([email protected]([email protected]))([email protected])([email protected]))(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected])([email protected]))([email protected]([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected](@aws-sdk/[email protected])([email protected])([email protected]))([email protected]([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected]([email protected]))([email protected]))':+ '@vercel/[email protected](@ai-sdk/[email protected]([email protected]))(@chat-adapter/[email protected]([email protected]([email protected]))([email protected])([email protected]([email protected]))([email protected])([email protected]))(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected])([email protected]))([email protected]([email protected]))([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected](@aws-sdk/[email protected])([email protected])([email protected]))([email protected]([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected]([email protected]))([email protected]))':dependencies:- '@vercel/oidc': 3.8.9+ '@vercel/oidc': 4.0.1optionalDependencies:'@ai-sdk/mcp': 2.0.73([email protected])- '@auth/core': 0.41.2'@chat-adapter/slack': 4.42.0([email protected]([email protected]))([email protected])([email protected]([email protected]))([email protected])([email protected])'@modelcontextprotocol/sdk': 1.30.0(@cfworker/[email protected])([email protected])([email protected])ai: 7.0.137([email protected])@@ -22098,9 +22095,9 @@ snapshots:'@vercel/cli-exec': 1.0.1jose: 5.10.0- '@vercel/[email protected]':+ '@vercel/[email protected]':dependencies:- '@vercel/cli-config': 0.3.0+ '@vercel/cli-config': 0.3.1'@vercel/cli-exec': 1.0.1jose: 5.10.0diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 0dac80fbd..c0fecf684 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -43,7 +43,7 @@ catalog:"@types/node": "24.13.3""@types/react": "19.2.15""@types/react-dom": "19.2.3"- "@vercel/connect": "2.3.3"+ "@vercel/connect": "2.5.2""@vercel/otel": "2.1.3""@vercel/sandbox": "3.3.0""@workflow/world-postgres": "5.0.3"