The Open Framework for Building Agents
docs: content and concision fixes + docs:check guardrails (#4)
John Phamous13b0c1ebf976
diff --git a/.changeset/eval-verbose-tlog-help.md b/.changeset/eval-verbose-tlog-help.mdnew file mode 100644index 000000000..c3dbe70f0--- /dev/null+++ b/.changeset/eval-verbose-tlog-help.md@@ -0,0 +1,5 @@+---+"eve": patch+---++The `eve eval --verbose` help text now refers to `t.log` (the actual eval context logging API) instead of the outdated `ctx.log`.diff --git a/apps/docs/app/[lang]/(home)/components/feature-grid.tsx b/apps/docs/app/[lang]/(home)/components/feature-grid.tsxindex 86e5f2ae1..4a88e4dad 100644--- a/apps/docs/app/[lang]/(home)/components/feature-grid.tsx+++ b/apps/docs/app/[lang]/(home)/components/feature-grid.tsx@@ -14,7 +14,7 @@ const features = ["Workflows survive crashes and restarts. Every step is checkpointed. Agents park when waiting, resume on the next message.",icon: <Database className="h-4 w-4 text-green-600" />,visual: <DurabilityVisual />,- href: "/docs/runs-and-streaming",+ href: "/docs/concepts/sessions-runs-and-streaming",},{title: "Sandboxed Compute",@@ -29,7 +29,7 @@ const features = [description: "One agent codebase deploys to web chat, Slack, API, cron, CLI, and custom apps.",icon: <MessageSquare className="h-4 w-4 text-cyan-600" />,visual: <ChannelsVisual />,- href: "/docs/channels",+ href: "/docs/channels/overview",},{title: "Human-in-the-Loop",@@ -37,7 +37,7 @@ const features = ["Tools that need confirmation trigger approval gates. Sessions park until resolved, then resume seamlessly.",icon: <Shield className="h-4 w-4 text-amber-600" />,visual: <HITLVisual />,- href: "/docs/human-in-the-loop",+ href: "/docs/tools",},{title: "Subagents",@@ -53,7 +53,7 @@ const features = ["Define test suites with scoring rubrics. Run evals on every deployment and on a schedule.",icon: <FlaskConical className="h-4 w-4 text-pink-600" />,visual: <EvalsVisual />,- href: "/docs/evals",+ href: "/docs/evals/overview",},];diff --git a/apps/docs/lib/integrations/data.ts b/apps/docs/lib/integrations/data.tsindex 0cafc2194..efb099d2d 100644--- a/apps/docs/lib/integrations/data.ts+++ b/apps/docs/lib/integrations/data.ts@@ -297,7 +297,7 @@ export default eveChannel();\`\`\`Point your frontend at the session routes Eve serves (\`/eve/v1/session\`) and stream responses with the Eve web client.`,- configure: `The Eve channel is the lowest-friction way to talk to your agent, with no third-party provisioning required. Layer in auth and route protection as needed. See the [Eve channel docs](/docs/channels/eve) and the [Frontend guide](/docs/frontend).`,+ configure: `The Eve channel is the lowest-friction way to talk to your agent, with no third-party provisioning required. Layer in auth and route protection as needed. See the [Eve channel docs](/docs/channels/eve) and the [Frontend guide](/docs/guides/frontend/overview).`,},};diff --git a/apps/frameworks/nuxt/README.md b/apps/frameworks/nuxt/README.mdindex 7ba78007e..4037c3f2e 100644--- a/apps/frameworks/nuxt/README.md+++ b/apps/frameworks/nuxt/README.md@@ -23,4 +23,4 @@ pnpm --filter framework-nuxt dev`vercel.json` declares two services: the Nuxt app at `/` and Eve behind theprivate `/_eve_internal/eve` service prefix. See-[the Nuxt frontend docs](../../../docs/frontend/nuxt.mdx) for details.+[the Nuxt frontend docs](../../../docs/guides/frontend/nuxt.mdx) for details.diff --git a/apps/frameworks/sveltekit/README.md b/apps/frameworks/sveltekit/README.mdindex 7b8697817..09de8c08b 100644--- a/apps/frameworks/sveltekit/README.md+++ b/apps/frameworks/sveltekit/README.md@@ -26,5 +26,5 @@ pnpm --filter framework-sveltekit dev`vercel.json` declares two services: the SvelteKit app at `/` and Eve behindthe private `/_eve_internal/eve` service prefix, with rewrites exposing thepublic `/eve/v1/*` endpoints. See-[the SvelteKit frontend docs](../../../docs/frontend/sveltekit.mdx) for+[the SvelteKit frontend docs](../../../docs/guides/frontend/sveltekit.mdx) fordetails.diff --git a/docs/README.md b/docs/README.mdindex da1cc26b4..f29bd3b07 100644--- a/docs/README.md+++ b/docs/README.md@@ -30,14 +30,14 @@ Read in this order:9. [Connections](./connections.mdx)10. [Sandboxes](./sandbox.mdx)11. [Channels](./channels/overview.mdx)-12. [Session Context](./guides/session-context.md)+12. [Session Context](./reference/typescript-api.md)13. [Sessions And Streaming](./concepts/sessions-runs-and-streaming.md)-14. [TypeScript SDK](./guides/client/overview.mdx)+14. [TypeScript SDK](./clients/typescript-sdk/overview.mdx)15. [Subagents](./subagents.mdx)16. [Schedules](./schedules.mdx)17. [Evals](./evals/overview.mdx)-18. [Auth And Route Protection](./guides/auth-and-route-protection.md)-19. [Vercel Deployment](./guides/deployment.md)+18. [Auth And Route Protection](./develop/auth-and-route-protection.md)+19. [Vercel Deployment](./develop/deployment.md)20. [CLI, Build, And Debugging](./reference/cli.md)## The public mental model@@ -90,5 +90,5 @@ That is why Eve exposes two identifiers:## Good companions in this repo-- Weather-focused smoke/dev fixture: [`../../apps/fixtures/weather-agent`](../../apps/fixtures/weather-agent)+- Weather-focused smoke/dev fixture: [`../../apps/fixtures/weather-fixture`](../../apps/fixtures/weather-fixture)- Public API source of truth: [`../../packages/eve/src/public/index.ts`](../../packages/eve/src/public/index.ts)diff --git a/docs/agent-config.md b/docs/agent-config.mdindex c83534a5f..6a93e8037 100644--- a/docs/agent-config.md+++ b/docs/agent-config.md@@ -1,11 +1,11 @@---title: "agent.ts"-description: "The agent's runtime config: defineAgent, the model, and compaction."+description: "Set the agent's runtime config in agent.ts with defineAgent, including the model and compaction."---An agent's `agent.ts` calls `defineAgent` (from `eve`) to set its runtime config.-## A good default+## Set the modelA typical config selects a model:@@ -20,7 +20,7 @@ export default defineAgent({The root `agent.ts` can be omitted when no runtime config is needed. In that case, Eve defaultsto `anthropic/claude-sonnet-4.6`. When `agent.ts` is present, `model` is required.-`model` can be a gateway model id string (which routes through the [Vercel AI Gateway](https://vercel.com/docs/ai-gateway)) or a provider-authored `LanguageModel`, when you want to call the provider directly, bypassing the gateway and configuring the model in code:+`model` accepts a gateway model id string, which routes through the [Vercel AI Gateway](https://vercel.com/docs/ai-gateway). To call a provider directly and configure the model in code, pass a provider-authored `LanguageModel`:```ts title="agent/agent.ts"import { anthropic } from "@ai-sdk/anthropic";@@ -33,7 +33,7 @@ export default defineAgent({## Compaction-Compaction summarizes older turns as you approach the context window. It is on by default, so you only touch it to tune when it kicks in. Lower `thresholdPercent` to compact sooner:+Compaction summarizes older turns as you approach the context window. It's on by default, so you only tune when it kicks in. Lower `thresholdPercent` to compact sooner:```ts title="agent/agent.ts"export default defineAgent({@@ -46,25 +46,16 @@ export default defineAgent({See [Default harness](./concepts/default-harness#compaction) for how the loop applies it.-## Other fields+## Other defineAgent fields-`defineAgent` takes a few more fields. For every field and its type, see the [TypeScript API](./reference/typescript-api).+`defineAgent` takes a few more fields, all optional. For the exported types, see the [TypeScript API](./reference/typescript-api).-### `modelOptions`--Provider option overrides forwarded to the model call.--### `experimental`--Opt-in flags that can change or disappear in any release, so treat them as unstable. The main one is `codeMode`, which routes executable tools through a sandboxed code-execution wrapper.--### `outputSchema`--A structured return type for task-mode runs: a subagent, schedule, or remote job.--### `build`--Build packaging controls. `externalDependencies` keeps listed packages external while Eve compiles authored modules such as tools and channels, and traces those packages into the hosted output.+| Field | Type | Default | Description |+| -------------- | --------------------------------------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `modelOptions` | `AgentModelOptionsDefinition` | none | Provider option overrides forwarded to the model call. |+| `experimental` | `{ codeMode?: boolean }` | flags unset | Opt-in flags that can change or disappear in any release. Treat them as unstable. `codeMode` routes executable tools through a sandboxed code-execution wrapper, where the model writes JavaScript that calls the tools inside the [sandbox](./sandbox). |+| `outputSchema` | Standard Schema or a JSON Schema object | none | Structured return type for task-mode runs (a subagent, schedule, or remote job). Interactive conversation turns ignore it unless the client supplies a per-message schema. |+| `build` | `{ externalDependencies?: string[] }` | none | Hosted-build packaging controls. `externalDependencies` keeps listed packages external while Eve compiles authored modules such as tools and channels, and traces those packages into the hosted output. |## Where adjacent settings livediff --git a/docs/channels/custom.mdx b/docs/channels/custom.mdxindex 9671ff071..78412e092 100644--- a/docs/channels/custom.mdx+++ b/docs/channels/custom.mdx@@ -3,13 +3,13 @@ title: "Custom Channels"description: "Author custom HTTP and WebSocket channels with routes, events, metadata, continuation tokens, and file uploads."----When Eve doesn't ship a channel for your surface, you build one. Custom channels let you expose HTTP or WebSocket endpoints, parse incoming requests, start or resume sessions, observe runtime events, and own delivery back to your platform.+When Eve doesn't ship a channel for your surface, you build one. Custom channels expose HTTP or WebSocket endpoints, parse incoming requests, start or resume sessions, observe runtime events, and own delivery back to your platform.## File location and identityCustom channels live in `agent/channels/` at the root agent. Local subagents do not declare channels today.-The channel file stem becomes the channel id, so `agent/channels/internal-webhook.ts` is addressed as `internal-webhook`. Channel files are module-backed: export the channel definition as the default export.+The channel file stem becomes the channel id, so `agent/channels/internal-webhook.ts` is addressed as `internal-webhook`. Export the channel definition as the module's default export.## Define a channel@@ -32,7 +32,7 @@ export default defineChannel({const stream = await session.getEventStream();return new Response(stream, {- headers: { "content-type": "text/event-stream" },+ headers: { "content-type": "application/x-ndjson; charset=utf-8" },});}),],@@ -44,14 +44,16 @@ export default defineChannel({});```-`defineChannel({ routes, ... })` defines a channel. Routes are declared with the `POST()` and `GET()` helpers. Each route handler receives the raw `Request` and a helpers object:+Declare routes with the `POST()` and `GET()` helpers. Each route handler receives the raw `Request` and a helpers object:-- `send(message, { auth, continuationToken, state? })`: start or resume a session. Returns a `Session`.-- `getSession(sessionId)`: look up an existing session. The returned `Session` exposes `getEventStream({ startIndex? })` for streaming.-- `params`: route parameters extracted from the path pattern.-- `waitUntil(promise)`: extend the request lifetime for background work.+- `send(message, { auth, continuationToken, state? })` starts or resumes a session. Returns a `Session`.+- `getSession(sessionId)` looks up an existing session. The returned `Session` exposes `getEventStream({ startIndex? })` for streaming.+- `receive(channel, ...)` hands inbound work to a different channel for cross-channel hand-off.+- `params` holds route parameters extracted from the path pattern.+- `waitUntil(promise)` extends the request lifetime for background work.+- `requestIp` is the client IP, or `null` when the host cannot provide it.-Event handlers like `"message.completed"` are declared under the `events` key. They receive `(eventData, channel, ctx)`, where `channel` carries platform handles and session continuation operations, and `ctx` is the Eve `SessionContext`.+Event handlers like `"message.completed"` are declared under the `events` key. They receive `(eventData, channel, ctx)`, where `eventData` is the event payload, `channel` carries platform handles and session continuation operations, and `ctx` is the Eve `SessionContext`. Every channel kind shares this signature. The one exception is `session.failed`, which receives only `(eventData, channel)` with no `ctx`.## WebSocket routes@@ -92,7 +94,7 @@ export default defineChannel({});```-The bridge server does not listen on its own port. It receives only upgrade events that matched the Eve route, and only on hosts where Nitro exposes the raw Node upgrade request, socket, and head. Treat it as a compatibility adapter for libraries with server-binding APIs, not as the primary way to build websocket channels in Eve.+The bridge server does not listen on its own port. It receives only upgrade events that matched the Eve route, and only on hosts where Nitro exposes the raw Node upgrade request, socket, and head. Treat it as a compatibility adapter for libraries with server-binding APIs, not the primary way to build websocket channels in Eve.## Cross-channel hand-off@@ -135,7 +137,7 @@ Semantics:## Channel metadata-Channels can project a subset of their adapter state as metadata available to instrumentation resolvers, dynamic tool resolvers, and dynamic skill or instruction resolvers. Define a `metadata(state)` function on the channel config:+A channel can project a subset of its adapter state as metadata, available to instrumentation resolvers, dynamic tool resolvers, and dynamic skill or instruction resolvers. Define a `metadata(state)` function on the channel config:```tsimport { defineChannel, POST } from "eve/channels";@@ -167,8 +169,8 @@ export default defineChannel({}),],events: {- "turn.started"(_event, ctx) {- ctx.state.internalCounter += 1;+ "turn.started"(eventData, channel) {+ channel.state.internalCounter += 1;},},});@@ -190,13 +192,17 @@ slackContinuationToken("C0123ABC", "1800000000.001234"); // "C0123ABC:1800000000twilioContinuationToken("+15551234567", "+15557654321"); // "+15551234567:+15557654321"```-Custom channels write their own function that joins the identity fields. The framework does not derive anything for you: the channel owns its token format.+Custom channels write their own function that joins the identity fields. The framework derives nothing for you; the channel owns its token format.-When the identity that should address a session is not known until later, the channel can re-key the parked session by calling `ctx.session.setContinuationToken(...)` from a handler. Pass the channel-local raw token; the runtime preserves the current channel namespace.+When the identity that should address a session is not known until later, the channel can re-key the parked session by calling `session.setContinuationToken(...)`. Pass the channel-local raw token; the runtime preserves the current channel namespace.++The `context(state, session)` config option builds the per-step `channel` argument handed to every event handler. It receives the channel's live adapter `state` and a `SessionHandle`, and returns the channel-owned context (thread handles, API clients, late-bound callbacks). The framework injects [`ChannelSessionOps`](#define-a-channel) and passes the result as the second positional argument to each handler. Closing over `session` lets the factory register callbacks that re-key the session later. State mutations made through the returned context are written back to adapter state.```tsimport { defineChannel } from "eve/channels";+import { mintRef } from "./refs.js";+defineChannel<{ ref: string | null }>({state: { ref: null },context(state, session) {@@ -209,8 +215,8 @@ defineChannel<{ ref: string | null }>({};},events: {- "message.completed"(_event, ctx) {- if (!ctx.state.ref) ctx.registerAnchor(mintRef());+ "message.completed"(eventData, channel) {+ if (!channel.state.ref) channel.registerAnchor(mintRef());},},routes: [@@ -264,7 +270,7 @@ defineChannel({});```-The `URL` object survives the queue boundary as a string and is reconstituted inside the workflow step. The staging pipeline calls `fetchFile(url)`: return bytes to stage the file to the sandbox, or return `null` to let the URL pass through to the model provider.+The `URL` object survives the queue boundary as a string and is reconstituted inside the workflow step. The staging pipeline calls `fetchFile` with the URL serialized as a string (the URL's `href`), which is why the example matches on `url.startsWith(...)`. Return bytes to stage the file to the sandbox, or `null` to let the URL pass through to the model provider.The framework handles staging bytes to the sandbox, enforcing upload policy, hydrating files for the model call, and reconstituting `URL` objects after queue serialization.diff --git a/docs/channels/discord.mdx b/docs/channels/discord.mdxindex 0cc0195f1..587423bab 100644--- a/docs/channels/discord.mdx+++ b/docs/channels/discord.mdx@@ -1,10 +1,10 @@---title: "Discord"-description: "Reach your agent from Discord HTTP Interactions: slash commands, components, and modals."+description: "Reach your agent from Discord HTTP Interactions, including slash commands, components, and modals."type: integration----The Discord channel wires your agent into Discord's HTTP Interactions: slash and application commands, message components, and modal submissions. The hard part Discord forces on you is the three-second ACK deadline, so the channel verifies the Ed25519 signature headers, acknowledges the command right away, and runs the actual Eve work in the background. See [Channels](./overview) for the contract this builds on.+The Discord channel wires your agent into Discord's HTTP Interactions, including slash and application commands, message components, and modal submissions. Discord enforces a three-second ACK deadline, so the channel verifies the Ed25519 signature headers, acknowledges the command right away, and runs the Eve work in the background. See [Channels](./overview) for the contract this builds on.## Add the channel@@ -20,11 +20,11 @@ DISCORD_APPLICATION_ID=... # edits the deferred response and sends followupsDISCORD_BOT_TOKEN=... # proactive messages + fallback + typing indicators```-If you'd rather not use env vars, pass the same values through `credentials: { applicationId, botToken, publicKey }`. The route is `POST /eve/v1/discord` by default. Paste that public URL into your Discord application's Interactions Endpoint URL.+To skip env vars, pass the same values through `credentials: { applicationId, botToken, publicKey }`. The route is `POST /eve/v1/discord` by default. Paste that public URL into your Discord application's Interactions Endpoint URL.## Register a command-Registering commands is on you, not the channel. Use Discord's API or the Developer Portal. If you give the command a string option named `message`, it lines up with Eve's default prompt extraction:+Registering commands is on you, not the channel. Use Discord's API or the Developer Portal. A string option named `message` lines up with Eve's default prompt extraction:```bashcurl -X PUT "https://discord.com/api/v10/applications/$DISCORD_APPLICATION_ID/commands" \@@ -35,9 +35,11 @@ curl -X PUT "https://discord.com/api/v10/applications/$DISCORD_APPLICATION_ID/coUse guild commands during development for faster propagation.-## Affordances+## How the channel handles messages-`onCommand(ctx, interaction)` is where you decide whether to dispatch and under what `auth`. Return `{ auth }` to proceed or `null` to drop the interaction. Out of the box, auth comes from the invoking user.+### Dispatch++`onCommand(ctx, interaction)` decides whether to dispatch and under what `auth`. Return `{ auth }` to proceed or `null` to drop the interaction. By default, auth comes from the invoking user. Event handlers receive `(eventData, channel, ctx)`, with Discord platform handles on `channel.discord`:```tsimport { discordChannel } from "eve/channels/discord";@@ -52,21 +54,31 @@ export default discordChannel({},}),events: {- "message.completed"(event, ctx) {- if (event.finishReason === "tool-calls") return;- if (event.message) ctx.discord.post(event.message);+ "message.completed"(eventData, channel, ctx) {+ if (eventData.finishReason === "tool-calls") return;+ if (eventData.message) channel.discord.post(eventData.message);},},});```-**Delivery.** The default `message.completed` handler edits the deferred response for the first reply and sends followups after that. If the interaction token gets rejected, it falls back to a bot-authenticated channel message. Long text is split to Discord's 2000-char limit, and generated messages default to `allowed_mentions: { parse: [] }`.+### Delivery++The default `message.completed` handler edits the deferred response for the first reply and sends followups after that. If the interaction token is rejected, it falls back to a bot-authenticated channel message. Long text is split to Discord's 2000-char limit, and generated messages default to `allowed_mentions: { parse: [] }`.++Typing fires on `turn.started` and `actions.requested`, but only when a bot token is present. In custom hooks, call `channel.discord.startTyping()` yourself.++### Human-in-the-loop (HITL)++HITL renders as Discord components. Confirmations and options become buttons, `display: "select"` becomes a string select, and freeform input becomes a button that opens a modal. When the user responds, the parked session (paused awaiting input) resumes.++### Proactive sessions-**Typing** fires on `turn.started` and `actions.requested`, but only when a bot token is present. In custom hooks, call `ctx.discord.startTyping()` yourself.+Start a session without an inbound interaction through `receive(discord, { message, target, auth })` from a schedule `run` handler, or `args.receive(discord, ...)` from another channel. The proactive target shape is `{ channelId, conversationId?, initialMessage? }`. Either path needs `DISCORD_BOT_TOKEN`.-**HITL** shows up as Discord components. Confirmations and options become buttons, `display: "select"` becomes a string select, and freeform input becomes a button that opens a modal. When the user responds, the parked session resumes on its own.+### Attachments-**Proactive sessions** go through `receive(discord, { message, target, auth })` from a schedule `run` handler, or `args.receive(discord, ...)` from another channel. Either way you need `DISCORD_BOT_TOKEN`.+Inbound file attachments are not supported on this channel today.## What to read nextdiff --git a/docs/channels/eve.mdx b/docs/channels/eve.mdxindex 9c805d601..64d4f0400 100644--- a/docs/channels/eve.mdx+++ b/docs/channels/eve.mdx@@ -1,11 +1,11 @@---title: "Eve"-description: "The default HTTP API for an agent: session routes, auth, and customization."+description: "The default HTTP API for an agent, covering session routes, auth, and customization."---The Eve channel is the framework's default HTTP API. It's what the terminal UI, [`useEveAgent`](../guides/frontend/overview), `curl`, and any SDK client talk to when they start sessions, send messages, and stream events. `eveChannel()` mounts the canonical session routes under `/eve/v1/session*`, and they are enabled by default even when `agent/channels/eve.ts` does not exist.-Reach for it when something needs HTTP access to your agent: local tooling, a browser frontend, the terminal UI, or another API client. Most apps never write this file. Add `agent/channels/eve.ts` only to override the defaults, usually the route auth policy:+Reach for it when something needs HTTP access to your agent, including local tooling, a browser frontend, the terminal UI, or another API client. Most apps never write this file. Add `agent/channels/eve.ts` only to override the defaults, usually the route auth policy.```ts title="agent/channels/eve.ts"import { eveChannel } from "eve/channels/eve";@@ -18,18 +18,36 @@ export default eveChannel({## Routes-The channel exposes the routes that create sessions, send follow-ups, and stream events:+The channel exposes routes that create sessions, send follow-ups, and stream events:- `GET /eve/v1/health`- `POST /eve/v1/session` (start a session)- `POST /eve/v1/session/:sessionId` (send a follow-up)- `GET /eve/v1/session/:sessionId/stream` (stream events, NDJSON)-See [Sessions, runs & streaming](../concepts/sessions-runs-and-streaming) for the request and stream flow.+Start a session with a minimal body. The response returns `sessionId` and the `continuationToken` you reuse for follow-ups:++```bash+curl -X POST https://<deployment>/eve/v1/session \+ -H "Content-Type: application/json" \+ -d '{"message":"What is the weather in Paris?"}'+# {"continuationToken":"eve:7f3c...","ok":true,"sessionId":"ses_01h..."}+```++Stream that session's events as newline-delimited JSON (`application/x-ndjson; charset=utf-8`), one event object per line:++```bash+curl -N https://<deployment>/eve/v1/session/ses_01h.../stream+# {"type":"turn.started",...}+# {"type":"text.delta","delta":"It is "}+# {"type":"message.completed",...}+```++See [Sessions, runs & streaming](../concepts/sessions-runs-and-streaming) for the full request and stream flow, including the complete event set.## Authentication-The `auth` option decides who can call these routes. The built-in helpers are meant for development and trusted infrastructure:+The `auth` option decides who can call these routes. The built-in helpers cover development and trusted infrastructure:- `localDev()` accepts requests during local development.- `vercelOidc()` lets the local CLI reach a deployed agent, and lets other internal deployments from your team call it.@@ -58,7 +76,7 @@ export default eveChannel({};},events: {- "message.completed"(event, channel, ctx) {+ "message.completed"(eventData, channel, ctx) {console.log("Eve response completed", {continuationToken: channel.continuationToken,sessionId: ctx.session.id,diff --git a/docs/channels/github.mdx b/docs/channels/github.mdxindex af01a61a4..e7d36c433 100644--- a/docs/channels/github.mdx+++ b/docs/channels/github.mdx@@ -4,7 +4,7 @@ description: "Reach your agent from GitHub App webhooks, with @mention dispatch,type: integration----The GitHub channel lets the agent work directly on a repository. Someone `@mentions` it in an issue, PR, or review comment, and the agent answers right there in the thread, with the PR diff already in context and the repo checked out into the sandbox. Under the hood it takes GitHub App webhooks at `/eve/v1/github`, checks the signature, figures out auth from whoever triggered the event, and replies on the native surface. See [Channels](./overview) for the contract this builds on.+The GitHub channel lets the agent work directly on a repository. Someone `@mentions` it in an issue, PR, or review comment, and the agent answers right there in the thread, with the PR diff already in context and the repo checked out into the sandbox. It takes GitHub App webhooks at `/eve/v1/github`, checks the signature, derives auth from whoever triggered the event, and replies on the native surface. See [Channels](./overview) for the contract this builds on.## Add the channel@@ -21,26 +21,31 @@ export default githubChannel({});```-Every field falls back to an env var (`GITHUB_APP_ID`, `GITHUB_APP_PRIVATE_KEY`, `GITHUB_WEBHOOK_SECRET`; `botName` reads `GITHUB_APP_SLUG`), so you can drop the `credentials` block entirely once those are set. `appId`/`privateKey`/`webhookSecret` will also take a lazy resolver function if you'd rather fetch them on demand.+Every field falls back to an env var, so you can drop the `credentials` block entirely once these are set:-Point the GitHub App webhook URL at `https://<deployment>/eve/v1/github`. For mention-driven turns, subscribe to `issue_comment` and `pull_request_review_comment`; add `issues` / `pull_request` if you wire up their opt-in hooks. A comment that `@mention`s `botName` starts a turn.+```bash+GITHUB_APP_ID=... # GitHub App id+GITHUB_APP_PRIVATE_KEY=... # GitHub App private key (PEM)+GITHUB_WEBHOOK_SECRET=... # verifies the webhook signature+GITHUB_APP_SLUG=... # supplies botName when it is not set in config+```-## Affordances+`appId`/`privateKey`/`webhookSecret` also take a lazy resolver function if you'd rather fetch them on demand.-**Acknowledgement & replies.** When a turn starts, the channel drops an `eyes` reaction on the triggering comment (turn this off with `progress: { reactions: false }`). The reply comes back as a comment, on the timeline or in the review thread, and splits across multiple comments when it runs long. If the turn fails, you get a short error comment carrying an error id.+Point the GitHub App webhook URL at `https://<deployment>/eve/v1/github`. For mention-driven turns, subscribe to `issue_comment` and `pull_request_review_comment`; add `issues` / `pull_request` if you wire up their opt-in hooks. A comment that `@mention`s `botName` starts a turn.-**PR context.** Summon the agent on a PR and it always sees the diff. PR metadata and the changed-file patch land in `context`. Large generated files still show up in the list, but their patch body is dropped; add more paths to the skip list with `pullRequestContext.excludedFiles`.+## How the channel handles messages-**Sandbox checkout.** Before the first model call, every triggered turn checks out the relevant ref into the sandbox, so `read_file`/`glob`/`grep`/`bash` all run against the real tree. The trick with the installation token is that it never enters the sandbox: `git` fetches a token-free URL, and the platform injects auth on egress at the firewall. That requires a firewall-capable backend (Vercel); the local backend skips checkout. Within a session, checkout is incremental across turns.+### Dispatch-**Inbound hooks** return `{ auth }` to dispatch, or `null` to ignore. Reach for `defaultGitHubAuth(ctx)` to derive auth from the actor.+Inbound hooks return `{ auth }` to dispatch, or `null` to ignore. Use `defaultGitHubAuth(ctx)` to derive auth from the actor.```tsimport { defaultGitHubAuth, githubChannel } from "eve/channels/github";export default githubChannel({botName: "my-agent",- // Replaces the @mention gate. ctx.conversation.kind: "issue" | "pull_request" | "review_thread".+ // Replaces the @mention gate. ctx.conversation.kind is "issue", "pull_request", or "review_thread".onComment: (ctx, comment) => ({ auth: defaultGitHubAuth(ctx) }),// Opt in; no default dispatch on these events.onIssue: (ctx, issue) => (issue.action === "opened" ? { auth: defaultGitHubAuth(ctx) } : null),@@ -48,7 +53,33 @@ export default githubChannel({});```-**Arbitrary API calls.** For anything the channel doesn't wrap, call `ctx.github.request({ method, path, body })`; it carries installation-token auth.+### Delivery++When a turn starts, the channel adds an `eyes` reaction to the triggering comment (turn this off with `progress: { reactions: false }`). The reply comes back as a comment, on the timeline or in the review thread, and splits across multiple comments when it runs long. If the turn fails, you get a short error comment carrying an error id.++### Human-in-the-loop (HITL)++GitHub comments have no interactive button or card affordance. A human-in-the-loop (HITL) `input.requested` event is posted as a comment prompt, and the user's reply comment maps back to the pending input request. Declare an `events["input.requested"]` handler to customize the prompt.++### Proactive sessions++Start a session without an inbound mention through `receive(github, { message, target, auth })` from a schedule `run` handler, or `args.receive(github, ...)` from another channel. The target requires `owner`, `repo`, and exactly one of `issueNumber` or `pullRequestNumber`.++### Attachments++Inbound file attachments are not supported on this channel today. Repository contents reach the agent through the sandbox checkout below, not as message attachments.++### PR context++Summon the agent on a PR and it always sees the diff. PR metadata and the changed-file patch land in `context`. Large generated files still appear in the list, but their patch body is dropped; add more paths to the skip list with `pullRequestContext.excludedFiles`.++### Sandbox checkout++Before the first model call, every triggered turn checks out the relevant ref into the sandbox, so `read_file`/`glob`/`grep`/`bash` all run against the real tree. The installation token never enters the sandbox. `git` fetches a token-free URL, and the platform injects auth on egress at the firewall. That requires a firewall-capable backend (Vercel); the local backend skips checkout. Within a session, checkout is incremental across turns.++### Arbitrary API calls++For anything the channel doesn't wrap, call `ctx.github.request({ method, path, body })`. It carries installation-token auth.## What to read nextdiff --git a/docs/channels/linear.mdx b/docs/channels/linear.mdxindex 3c27c3c3c..48d9118fe 100644--- a/docs/channels/linear.mdx+++ b/docs/channels/linear.mdx@@ -4,7 +4,7 @@ description: "Reach your agent through Linear Agent Sessions, with native Agenttype: integration----The Linear channel uses Linear's Agent Session surface rather than ordinary comments. Users delegate work to the agent from Linear, Eve receives `AgentSessionEvent` webhooks at `/eve/v1/linear`, and the channel replies with native Agent Activities: `thought`, `action`, `elicitation`, `response`, and `error`.+The Linear channel uses Linear's Agent Session surface rather than ordinary comments. Users delegate work to the agent from Linear, Eve receives `AgentSessionEvent` webhooks at `/eve/v1/linear`, and the channel replies with native Agent Activities, including `thought`, `action`, `elicitation`, `response`, and `error`. See [Channels](./overview) for the contract this builds on.## Add the channel@@ -24,7 +24,7 @@ LINEAR_AGENT_ACCESS_TOKEN=lin_api_... # posts Agent Activities and creates proacLINEAR_WEBHOOK_SECRET=... # verifies Linear-Signature```-If you'd rather not use env vars, pass the same values through `credentials: { accessToken, webhookSecret }`. Both fields also accept lazy resolver functions. The access token falls back to `LINEAR_AGENT_ACCESS_TOKEN`, `LINEAR_ACCESS_TOKEN`, `LINEAR_API_KEY`, or `LINEAR_API_TOKEN`; the webhook secret falls back to `LINEAR_WEBHOOK_SECRET`.+The sample passes credentials explicitly. To rely on env vars instead, drop the `credentials` block: the access token falls back to `LINEAR_AGENT_ACCESS_TOKEN`, `LINEAR_ACCESS_TOKEN`, `LINEAR_API_KEY`, or `LINEAR_API_TOKEN`, and the webhook secret falls back to `LINEAR_WEBHOOK_SECRET`. Both fields also accept lazy resolver functions.## Configure Linear@@ -38,25 +38,31 @@ For Linear's agent surface, configure the OAuth authorize URL with `actor=app` aLinear sends webhook signatures in `Linear-Signature`; Eve verifies the HMAC over the raw body and rejects stale `webhookTimestamp` values. If a trusted gateway verifies Linear before the request reaches Eve, pass `credentials.webhookVerifier` instead of a webhook secret.-## Affordances+## How the channel handles messages-**Agent Session dispatch.** The default hook dispatches `created` and `prompted` Agent Session events. Eve adds a Linear context block with the agent session, issue, comment, and organization identifiers, then continues the same session with `agent-session:<id>`.+### Dispatch-**Native progress and replies.** Turn start posts an ephemeral `thought`, tool calls post ephemeral `action` activities, final assistant text posts a durable `response`, and failures post `error` activities. When the model emits text before a tool call, Eve buffers the first non-empty line and uses it as the next ephemeral Linear `thought`, mirroring Slack's typing-status behavior.+The default hook dispatches `created` and `prompted` Agent Session events. Eve adds a Linear context block with the agent session, issue, comment, and organization identifiers, then continues the same session with `agent-session:<id>`.-**Human input.** Eve input requests are rendered as Linear `elicitation` activities. When the user replies to the Agent Session, the channel resolves that prompt back to the pending Eve input request and resumes with `inputResponses`.+### Delivery-**API handle.** Event handlers receive `channel.linear`, which exposes `createActivity`, `listActivities`, and `updateSession` for custom Agent Activity delivery and Agent Session metadata.+Turn start posts an ephemeral `thought`, tool calls post ephemeral `action` activities, final assistant text posts a durable `response`, and failures post `error` activities. When the model emits text before a tool call, Eve buffers the first non-empty line and uses it as the next ephemeral Linear `thought`, mirroring Slack's typing-status behavior.-**Proactive sessions.** `receive(linear, { target })` accepts an existing `agentSessionId`, or can create a new Agent Session on an `issueId` or root `commentId` before sending the message.+### Human-in-the-loop (HITL)-```ts-await receive(linear, {- auth: null,- message: "Summarize the current status and risks.",- target: { issueId: "issue-id" },-});-```+Human-in-the-loop (HITL) input requests render as Linear `elicitation` activities. When the user replies to the Agent Session, the channel resolves that prompt back to the pending Eve input request and resumes with `inputResponses`.++### Proactive sessions++Start a session without an inbound webhook with `receive(linear, { target })`. See [Proactive sessions](#proactive-sessions) below for the target shape and examples.++### Attachments++Inbound file attachments are not supported on this channel today.++### API handle++Event handlers receive `channel.linear`, which exposes `createActivity`, `listActivities`, and `updateSession` for custom Agent Activity delivery and Agent Session metadata.## Custom hooks@@ -73,7 +79,7 @@ export default linearChannel({});```-Restrict dispatch to a subset of Linear teams or projects by inspecting `event.agentSession.issue` in `onAgentSession`. Add extra context by returning `context` alongside auth.+Restrict dispatch to a subset of Linear teams or projects by inspecting `event.agentSession.issue` in `onAgentSession`. Add extra context by returning `context` alongside `auth`.```tsimport { defaultLinearAuth, linearChannel } from "eve/channels/linear";@@ -96,16 +102,16 @@ import { linearChannel } from "eve/channels/linear";export default linearChannel({events: {- async "message.completed"(event, channel) {- if (event.finishReason === "tool-calls" || !event.message) return;+ async "message.completed"(eventData, channel) {+ if (eventData.finishReason === "tool-calls" || !eventData.message) return;await channel.linear.createActivity({- body: `Done.\n\n${event.message}`,+ body: `Done.\n\n${eventData.message}`,type: "response",});},- async "input.requested"(event, channel) {+ async "input.requested"(eventData, channel) {await channel.linear.createActivity({- body: event.requests.map((request) => request.prompt).join("\n\n"),+ body: eventData.requests.map((request) => request.prompt).join("\n\n"),type: "elicitation",});},@@ -123,7 +129,7 @@ await channel.linear.updateSession({## Proactive sessions-Use the channel's `receive` target to continue an existing Agent Session or create one from a Linear issue or root comment.+Use the channel's `receive` target to continue an existing Agent Session or create one from a Linear issue or root comment. The target accepts an existing `agentSessionId`, or an `issueId` or root `commentId` to create a new session before sending the message. The example below runs from a schedule; a route handler uses the same target shape through its own `receive` helper.```tsimport { defineSchedule } from "eve/schedules";@@ -147,20 +153,7 @@ export default defineSchedule({});```-Route handlers can use the same target shape through their `receive` helper:--```ts-await receive(linear, {- auth: null,- message: "Post a concise status update with blockers and next actions.",- target: {- issueId: "EVE-123",- initialActivity: "Preparing the status update.",- },-});-```--For issue/comment targets, the channel calls Linear's proactive Agent Session mutations before starting the Eve turn. For an existing `agentSessionId`, it skips session creation and only seeds the continuation token.+For issue or comment targets, the channel calls Linear's proactive Agent Session mutations before starting the Eve turn. For an existing `agentSessionId`, it skips session creation and only seeds the continuation token.## What to read nextdiff --git a/docs/channels/overview.mdx b/docs/channels/overview.mdxindex e2e5f786d..c609db58b 100644--- a/docs/channels/overview.mdx+++ b/docs/channels/overview.mdx@@ -3,7 +3,11 @@ title: "Overview"description: "How users reach your agent: the channel contract, the base Eve HTTP channel, and authoring custom channels."----A channel is the edge adapter between a platform and your agent, and its job is deliberately small. It does exactly three things: normalizes platform input into a user message, owns the `continuationToken` (the resume handle for a conversation on that surface), and decides delivery (how, where, and whether a response goes back).+A channel is the edge adapter between a platform and your agent. It does three things:++- Normalizes platform input into a user message.+- Owns the `continuationToken`, the resume handle for a conversation on that surface.+- Decides delivery, meaning how, where, and whether a response goes back.Eve ships a base HTTP channel plus first-class platform channels, and you can author your own. Browse the full set in the [Integrations](/integrations) gallery.@@ -24,17 +28,17 @@ Scaffold a channel file with `eve channels add` (interactive), or pass a kind: `## The Eve HTTP channel (default)-Eve's canonical HTTP session API: the routes the terminal UI, [`useEveAgent`](../guides/frontend/overview), and `curl` all talk to. It is enabled by default, even with no `agent/channels/eve.ts` file. Add that file only to override the defaults, most often the route auth policy. See [Eve channel](./eve) for the routes, auth, and customization.+The Eve channel is the framework's default HTTP session API, the routes the terminal UI, [`useEveAgent`](../guides/frontend/overview), and `curl` all talk to. It is enabled by default, even with no `agent/channels/eve.ts` file. Add that file only to override the defaults, most often the route auth policy. See [HTTP channel](./eve) for routes, auth, and customization.## Custom channels-When Eve doesn't ship a channel for your surface, build one with `defineChannel` from `eve/channels`: route handlers (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `WS`), an `events` map, and a `send` call inside a handler to start or resume a session. See [Custom channels](./custom) for the full walkthrough, including WebSocket routes, cross-channel hand-off, channel metadata, continuation tokens, and file uploads.+When Eve doesn't ship a channel for your surface, build one with `defineChannel` from `eve/channels`. A custom channel declares route handlers (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `WS`), an `events` map, and a `send` call inside a handler to start or resume a session. See [Custom channels](./custom) for the full walkthrough, including WebSocket routes, cross-channel hand-off, channel metadata, continuation tokens, and file uploads.## Relationship to the Chat SDKEve uses the Chat SDK's **card-builder components** (Cards, Buttons, Actions, etc.) for composing rich Slack messages. When you build a card with the [Slack channel](./slack), the underlying primitives come from the Chat SDK and get converted to Slack Block Kit at post time.-Eve does **not** use the Chat SDK's runtime. The `Chat`, `Adapter`, and `Thread` primitives are never imported or reachable through Eve's public API. Eve's channel layer (webhook handling, signature verification, event parsing, and thread management) is implemented inside Eve itself. In short: building Slack messages feels just like Chat SDK cards, but wiring a channel means authoring against Eve's `defineChannel(...)` API, not a Chat SDK adapter.+Eve does **not** use the Chat SDK's runtime. The `Chat`, `Adapter`, and `Thread` primitives are never imported or reachable through Eve's public API. Eve implements its own channel layer (webhook handling, signature verification, event parsing, and thread management). Building Slack messages works like Chat SDK cards, but wiring a channel means authoring against Eve's `defineChannel(...)` API, not a Chat SDK adapter.## Which channel?diff --git a/docs/channels/slack.mdx b/docs/channels/slack.mdxindex 6529f6572..7800053b2 100644--- a/docs/channels/slack.mdx+++ b/docs/channels/slack.mdx@@ -4,7 +4,7 @@ description: "Reach your agent from Slack app mentions and DMs, with thread anchtype: integration----The Slack channel puts your agent inside a workspace: it answers `@mentions` and DMs, replies in threads, shows typing indicators, and turns HITL prompts into buttons. Use it when the conversation should happen where your team already works. Credentials run through [Vercel Connect](../guides/auth-and-route-protection), which handles both the outbound bot token and inbound webhook verification, so there's no `SLACK_BOT_TOKEN` or `SLACK_SIGNING_SECRET` for you to manage. See [Channels](./overview) for the contract this builds on.+The Slack channel puts your agent inside a workspace. It answers `@mentions` and DMs, replies in threads, shows typing indicators, and turns human-in-the-loop (HITL) prompts into buttons. Use it when the conversation should happen where your team already works. Credentials run through [Vercel Connect](../guides/auth-and-route-protection), which handles both the outbound bot token and inbound webhook verification, so there's no `SLACK_BOT_TOKEN` or `SLACK_SIGNING_SECRET` for you to manage. See [Channels](./overview) for the contract this builds on.## Set up Connect@@ -17,9 +17,9 @@ vercel connect detach <uid> --yesvercel connect attach <uid> --triggers --trigger-path /eve/v1/slack --yes```-`--triggers` turns on Slack Event Subscriptions; without it, Slack never delivers `app_mention` or `message.im`. `--trigger-path /eve/v1/slack` must match the channel route, since Eve doesn't serve the default Connect path. You can also create the client from the [Connect dashboard](https://vercel.com/d?to=/%5Bteam%5D/~/connect&title=Go+to+Connect).+`FF_CONNECT_ENABLED=1` turns on the Connect commands, which are feature-flagged in the Vercel CLI today. The `create` step provisions a destination at the default Connect path. `detach` then `attach --trigger-path /eve/v1/slack` re-points the trigger at the Eve Slack route, since Eve does not serve the default Connect path. `--triggers` turns on Slack Event Subscriptions; without it, Slack never delivers `app_mention` or `message.im`. You can also create the client from the [Connect dashboard](https://vercel.com/d?to=/%5Bteam%5D/~/connect&title=Go+to+Connect).-## Add the channel file+## Add the channelScaffold the channel and its dependency with `eve channels add slack`, or set it up by hand:@@ -36,67 +36,94 @@ export default slackChannel({});```-`connectSlackCredentials` returns `{ botToken, webhookVerifier }`. That keeps token rotation, multi-workspace tenancy, and request verification inside Connect rather than your code. Deploy once the trigger destination and channel file are ready:+`connectSlackCredentials` returns `{ botToken, webhookVerifier }`, keeping token rotation, multi-workspace tenancy, and request verification inside Connect rather than your code. Deploy once the trigger destination and channel file are ready:```bashVERCEL_USE_EXPERIMENTAL_FRAMEWORKS=1 vercel deploy --prod```-## Affordances+`VERCEL_USE_EXPERIMENTAL_FRAMEWORKS=1` lets the Vercel CLI recognize Eve as a framework during the build. Eve's own setup commands set the same flag.-**Inbound hooks** decide whether to dispatch a turn and with what `auth`. Return `{ auth }` to dispatch, `null` to drop, or `{ auth, context }` to inject background into history.+## How the channel handles messages++### Dispatch++Inbound hooks decide whether to dispatch a turn and with what `auth`. Return `{ auth }` to dispatch, `null` to drop, or `{ auth, context }` to inject background into history.- `onAppMention(ctx, message)` handles `app_mention` events. The default derives workspace-scoped auth and posts a `Thinking…` indicator.- `onDirectMessage(ctx, message)` handles `message.im` events (needs `im:history` scope). Bot-authored messages and edits are filtered out first.- `onInteraction(action, ctx)` handles `block_actions` callbacks not consumed by HITL.-**Thread context.** You get the triggering mention by default, but not the earlier replies in the thread. Pull them in with `loadThreadContextMessages` and return them as `context`, which Eve appends to history as user messages the model sees on every later turn. Use `since: "last-agent-reply"` so repeated mentions in one thread only inject what is new:+You get the triggering mention by default, but not the earlier replies in the thread. Pull them in with `loadThreadContextMessages` and return them as `context`, which Eve appends to history as user messages the model sees on every later turn. Use `since: "last-agent-reply"` so repeated mentions in one thread inject only what is new:```ts-async onAppMention(ctx, message) {- const auth = defaultSlackAuth(message, ctx);- const prior = await loadThreadContextMessages(ctx.thread, message, { since: "last-agent-reply" });- if (prior.length === 0) return { auth };- const transcript = prior.map((m) => `${m.isMe ? "you" : (m.user ?? "user")}: ${m.markdown}`).join("\n");- return { auth, context: [`Recent thread messages since your last reply:\n\n${transcript}`] };-}-```+import { defaultSlackAuth, loadThreadContextMessages, slackChannel } from "eve/channels/slack";+import { connectSlackCredentials } from "@vercel/connect/eve";-**Thread anchoring.** When a session starts without a `threadTs` (say, from a schedule or `args.receive(slack, ...)`), it anchors on the first agent post, and later posts and mentions resume that same session. Pass `initialMessage` with a `Card` to land a structured anchor first instead. `threadTs` and `initialMessage` are mutually exclusive.+export default slackChannel({+ credentials: connectSlackCredentials("slack/my-agent"),+ async onAppMention(ctx, message) {+ const auth = defaultSlackAuth(message, ctx);+ const prior = await loadThreadContextMessages(ctx.thread, message, {+ since: "last-agent-reply",+ });+ if (prior.length === 0) return { auth };+ const transcript = prior+ .map((m) => `${m.isMe ? "you" : (m.user ?? "user")}: ${m.markdown}`)+ .join("\n");+ return { auth, context: [`Recent thread messages since your last reply:\n\n${transcript}`] };+ },+});+```-**Typing indicators** post out of the box: `Thinking…` on inbound, `Working…` on `turn.started`, tool status on `actions.requested`. Override any handler to customize.+### Delivery-**HITL** renders as Slack buttons/selects; submissions resume the parked session.+The default handlers reply in-thread and show progress. Typing indicators post automatically: `Thinking…` on inbound, `Working…` on `turn.started`, tool status on `actions.requested`. Override `onAppMention` or the `events` handlers to customize.-**Authorization prompts are private.** A sign-in challenge (OAuth URL, device code) is a credential. Anyone who completes it binds their identity to the session's connection. The default `authorization.required` handler delivers the challenge ephemerally to the triggering user, device code included, and posts a public link-free status only when it has no user to target. The handler receives a private-delivery context with `postEphemeral`, `postDirectMessage` (needs the `im:write` scope), and `state`. There is, intentionally, no public `post` and no raw API access.+When a session starts without a `threadTs` (say, from a schedule or `receive(slack, ...)`), it anchors on the first agent post, and later posts and mentions resume that same session. Pass `initialMessage` with a `Card` to land a structured anchor first instead. `threadTs` and `initialMessage` are mutually exclusive.-```ts-events: {- "authorization.required"(event, ctx) {- const userId = ctx.state.triggeringUserId;- if (!userId || !event.authorization?.url) return;- return ctx.postDirectMessage(userId, `Sign in to continue: ${event.authorization.url}`);- },-},-```+The example below overrides `onAppMention` to gate on an authored message and posts the completed reply to the thread. Event handlers receive `(eventData, channel, ctx)`, with Slack platform handles on `channel.thread` and `channel.slack`:```tsimport { defaultSlackAuth, slackChannel } from "eve/channels/slack";+import { connectSlackCredentials } from "@vercel/connect/eve";export default slackChannel({credentials: connectSlackCredentials("slack/my-agent"),onAppMention: (ctx, message) =>message.author ? { auth: defaultSlackAuth(message, ctx) } : null,events: {- "message.completed"(event, ctx) {- if (event.finishReason === "tool-calls") return;- if (event.message) ctx.thread.post(event.message);+ "message.completed"(eventData, channel, ctx) {+ if (eventData.finishReason === "tool-calls") return;+ if (eventData.message) channel.thread.post(eventData.message);},},});```-Event handlers receive `(eventData, ctx)` with platform handles on `ctx.thread` and `ctx.slack`.+### Human-in-the-loop (HITL)++HITL renders as Slack buttons and selects. When the user responds, the parked session (paused awaiting input) resumes.++Authorization prompts are private. A sign-in challenge (OAuth URL, device code) is a credential. Anyone who completes it binds their identity to the session's connection. The default `authorization.required` handler delivers the challenge ephemerally to the triggering user, device code included, and posts a public link-free status only when it has no user to target. The handler receives a private-delivery context with `postEphemeral`, `postDirectMessage` (needs the `im:write` scope), and `state`. There is, intentionally, no public `post` and no raw API access.++```ts+events: {+ "authorization.required"(eventData, channel) {+ const userId = channel.state.triggeringUserId;+ if (!userId || !eventData.authorization?.url) return;+ return channel.postDirectMessage(userId, `Sign in to continue: ${eventData.authorization.url}`);+ },+},+```++### Proactive sessions++Start a session without an inbound message through `receive(slack, { message, target, auth })` from a schedule `run` handler, or `args.receive(slack, ...)` from another channel. The proactive target shape is `{ channelId }`.++### Attachments++Inbound files behind authenticated Slack URLs are staged with `fetchFile`. See [File uploads](./custom#file-uploads) for the `fetchFile` contract.## What to read nextdiff --git a/docs/channels/teams.mdx b/docs/channels/teams.mdxindex b3e84faee..8169fe707 100644--- a/docs/channels/teams.mdx+++ b/docs/channels/teams.mdx@@ -1,10 +1,10 @@---title: "Microsoft Teams"-description: "Reach your agent from Microsoft Teams via the Bot Framework Activity protocol, with Adaptive Card HITL."+description: "Reach your agent from Microsoft Teams via the Bot Framework Activity protocol, with Adaptive Card human-in-the-loop prompts."type: integration----The Teams channel lets your agent live inside Microsoft Teams as a bot. It takes Bot Framework Activity POSTs, checks the Bot Connector bearer JWT on each one, and routes message activities to your agent. HITL prompts come back as Adaptive Cards, and replies go out over the Bot Framework Connector REST API. See [Channels](./overview) for the contract this builds on.+The Teams channel runs your agent inside Microsoft Teams as a bot. It takes Bot Framework Activity POSTs, checks the Bot Connector bearer JWT on each one, and routes message activities to your agent. Human-in-the-loop (HITL) prompts come back as Adaptive Cards, and replies go out over the Bot Framework Connector REST API. See [Channels](./overview) for the contract this builds on.## Add the channel@@ -22,9 +22,11 @@ MICROSOFT_TENANT_ID=... # optional, single-tenant botsBy default the channel mounts at `POST /eve/v1/teams`. Point your Azure Bot or Teams app messaging endpoint at that public URL. To mount somewhere else, pass `route: "/api/teams/activity"`.-## Affordances+## How the channel handles messages-**Message dispatch.** The default `onMessage` handles two cases: personal-chat messages, and channel or group-chat messages that mention the bot directly. Ambient resource-specific-consent messages are dropped unless you override it. Before dispatch, Eve strips the mention, adds a `<teams_context>` block, and scopes channel and group threads by root activity id (`replyToId ?? id`).+### Dispatch++The default `onMessage` handles two cases: personal-chat messages, and channel or group-chat messages that mention the bot directly. Ambient resource-specific-consent messages are dropped unless you override it. Before dispatch, Eve strips the mention, adds a `<teams_context>` block, and scopes channel and group threads by root activity id (`replyToId ?? id`).```tsimport { defaultTeamsAuth, teamsChannel } from "eve/channels/teams";@@ -37,11 +39,21 @@ export default teamsChannel({});```-**Delivery & HITL.** Replies post as Markdown (`textFormat: "markdown"`), with oversized text split across messages and a typing indicator sent on turn start and action requests. An `input.requested` event renders as an Adaptive Card. Buttons and options map to `Action.Submit`, selects to `Input.ChoiceSet`, and freeform to `Input.Text`. When the user submits, the activity converts to Eve `inputResponses` for you. For invokes that aren't HITL, handle them in `onInvoke(ctx, activity)`.+### Delivery++Replies post as Markdown (`textFormat: "markdown"`), with oversized text split across messages and a typing indicator sent on turn start and action requests.++### Human-in-the-loop (HITL)++A human-in-the-loop (HITL) `input.requested` event renders as an Adaptive Card. Buttons and options map to `Action.Submit`, selects to `Input.ChoiceSet`, and freeform to `Input.Text`. When the user submits, the activity converts to Eve `inputResponses` for you. For invokes that aren't HITL, handle them in `onInvoke(ctx, activity)`.++### Proactive sessions++Proactive sessions need an existing conversation reference, because the Bot Framework v1 surface cannot create new chats by Azure Active Directory (AAD) user id. Pass `serviceUrl`, `conversationId`, and the other reference fields to `receive(teams, { target })`.-**Proactive sessions** need an existing conversation reference, because Teams v1 cannot create new chats by AAD user id. Pass `serviceUrl`, `conversationId`, etc. to `receive(teams, { target })`.+### Attachments-**Files** are off by default. Opt in to enable personal-scope downloads and public media URLs:+Inbound files are off by default. Opt in to allow personal-scope downloads and public media URLs:```tsexport default teamsChannel({diff --git a/docs/channels/telegram.mdx b/docs/channels/telegram.mdxindex 6373a234d..7caf47c3e 100644--- a/docs/channels/telegram.mdx+++ b/docs/channels/telegram.mdx@@ -1,10 +1,10 @@---title: "Telegram"-description: "Reach your agent from Telegram bot webhooks, with inline-keyboard HITL and attachments."+description: "Reach your agent from Telegram bot webhooks, with inline-keyboard human-in-the-loop prompts and attachments."type: integration----The Telegram channel puts your agent behind a Telegram bot. It takes Bot API webhooks, checks the `X-Telegram-Bot-Api-Secret-Token` header before it trusts anything, and routes the messages it cares about (private chats plus group messages that address the bot) to a reply over `sendMessage`. See [Channels](./overview) for the contract this builds on.+The Telegram channel puts your agent behind a Telegram bot. It takes Bot API webhooks, checks the `X-Telegram-Bot-Api-Secret-Token` header before trusting anything, and routes the messages it cares about (private chats plus group messages that address the bot) to a reply over `sendMessage`. See [Channels](./overview) for the contract this builds on.## Add the channel@@ -31,15 +31,31 @@ curl -X POST "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/setWebhook" \"allowed_updates":["message","callback_query"]}'```-## Affordances+## How the channel handles messages-**Dispatch.** In a private chat, text, captions, photos, and documents all go through. Groups are stricter. Only three things wake the bot: a command (`/ask`, `/ask@my_bot`), an `@my_bot` mention (when `botUsername` is set), or a reply to one of the bot's own messages. Everything else gets ignored. Forum topics carry `message_thread_id` in the continuation token, so each topic stays on its own thread. Need custom auth or filtering? Override `onMessage`. Group privacy mode itself lives in BotFather, not here.+### Dispatch-**Delivery.** The default `message.completed` handler sends plain text via `sendMessage`. It passes no `parse_mode`, so any Markdown shows up literally. Replies longer than Telegram's 4096-char limit get split across messages. Custom handlers reach for `ctx.telegram`.+In a private chat, text, captions, photos, and documents all go through. Groups are stricter. Only three things wake the bot: a command (`/ask`, `/ask@my_bot`), an `@my_bot` mention (when `botUsername` is set), or a reply to one of the bot's own messages. Everything else is ignored.-**HITL** turns option requests into inline-keyboard buttons and freeform requests into `ForceReply`. Telegram caps `callback_data` at 64 bytes, so Eve keeps compact callback ids in channel state instead. It acknowledges its own callbacks with `answerCallbackQuery`; anything it doesn't recognize goes to `onCallbackQuery`.+Forum topics carry `message_thread_id` in the continuation token, so each topic stays on its own thread.-**Attachments** are inbound photos and documents. Eve fetches them on demand via `getFile`, only when an upload policy allows the type:+To customize auth or filtering, override `onMessage`. Group privacy mode itself lives in BotFather, not here.++### Delivery++The default `message.completed` handler sends plain text via `sendMessage`. It passes no `parse_mode`, so any Markdown shows up literally. Replies longer than Telegram's 4096-char limit are split across messages. Custom handlers use `channel.telegram`.++### Human-in-the-loop (HITL)++Human-in-the-loop (HITL) turns option requests into inline-keyboard buttons and freeform requests into `ForceReply`. Telegram caps `callback_data` at 64 bytes, so Eve keeps compact callback ids in channel state instead. It acknowledges its own callbacks with `answerCallbackQuery`; anything it doesn't recognize goes to `onCallbackQuery`.++### Proactive sessions++Start a session without an inbound message through `receive(telegram, { message, target, auth })` from a schedule `run` handler, or `args.receive(telegram, ...)` from another channel. `target.chatId` is required. Add `messageThreadId` to land in a specific forum topic.++### Attachments++Inbound photos and documents are supported. Eve fetches them on demand via `getFile`, only when an upload policy allows the type:```tsexport default telegramChannel({@@ -48,8 +64,6 @@ export default telegramChannel({});```-**Proactive sessions** start with `receive(telegram, { message, target, auth })` from a schedule `run` handler, or `args.receive(telegram, ...)` when you're kicking off from another channel. `target.chatId` is required. Add `messageThreadId` to land in a specific forum topic.-## What to read next- [Channels overview](./overview): the channel contract and every built-in channeldiff --git a/docs/channels/twilio.mdx b/docs/channels/twilio.mdxindex f27431ae2..8c84829e9 100644--- a/docs/channels/twilio.mdx+++ b/docs/channels/twilio.mdx@@ -4,7 +4,7 @@ description: "Reach your agent over SMS and speech-transcribed phone calls withtype: integration----The Twilio channel puts your agent on a phone number, so people can text it or call it. Inbound SMS arrives as a webhook. Inbound calls get answered with TwiML `<Gather input="speech">`, and the resulting transcript feeds the same Eve session that SMS uses, so a caller and a texter look identical downstream. Every request is checked against `X-Twilio-Signature` before anything else runs. The raw continuation token is `From:To`. See [Channels](./overview) for the contract this builds on.+The Twilio channel puts your agent on a phone number, so people can text it or call it. Inbound SMS arrives as a webhook. Inbound calls are answered with TwiML `<Gather input="speech">`, and the resulting transcript feeds the same Eve session that SMS uses, so a caller and a texter look identical downstream. Every request is checked against `X-Twilio-Signature` before anything else runs. The raw continuation token is `From:To`. See [Channels](./overview) for the contract this builds on.## Add the channel@@ -22,7 +22,7 @@ TWILIO_ACCOUNT_SID=AC... # required for default outbound SMSTWILIO_AUTH_TOKEN=... # required for inbound signature verification```-If you'd rather not use env vars, pass the same values via `credentials: { accountSid, authToken }`. The channel mounts three routes:+To skip env vars, pass the same values via `credentials: { accountSid, authToken }`. The channel mounts three routes:- `POST /eve/v1/twilio/messages`: Messaging webhook- `POST /eve/v1/twilio/voice`: inbound call webhook@@ -30,15 +30,17 @@ If you'd rather not use env vars, pass the same values via `credentials: { accouPoint your Twilio number's Messaging webhook at `/messages` and Voice webhook at `/voice`, using the exact public URL Twilio will call.-## Affordances+## How the channel handles messages-**`allowFrom` is required.** It gates who can reach the inbound hooks. Pass a single number, a list, an async resolver, or `"*"`. The wildcard is dangerous: only use it with an explicit check inside `onText`/`onVoice`.+### Dispatch++`allowFrom` is required. It gates who can reach the inbound hooks. Pass a single number, a list, an async resolver, or `"*"`. The wildcard is dangerous; only use it with an explicit check inside `onText`/`onVoice`.```tsexport default twilioChannel({ allowFrom: ["+15551234567", "+15557654321"] });```-**Hooks.** `onText` and `onVoiceTranscription` decide dispatch and `auth`: return `{ auth }` to proceed, or `null` to drop the message. `onVoice` fires the moment a call comes in. Return `null` to reject it, or return an object to override the spoken prompt, language, `<Say voice>`, and speech-recognition options.+`onText` and `onVoiceTranscription` decide dispatch and `auth`. Return `{ auth }` to proceed, or `null` to drop the message. `onVoice` fires the moment a call comes in. Return `null` to reject it, or return an object to override the spoken prompt, language, `<Say voice>`, and speech-recognition options.```tsexport default twilioChannel({@@ -54,7 +56,21 @@ export default twilioChannel({});```-**Delivery.** The default `message.completed` handler sends the reply as SMS through Twilio's Messages API. A reply to an inbound message can reuse the webhook's `To` as the sender, but a proactive send has nothing to reuse, so it needs `messaging.from` or `messaging.messagingServiceSid`. Behind a proxy, set `webhookUrl` so signature verification matches the exact configured URL, and `publicBaseUrl` so voice TwiML can build absolute callback URLs.+### Delivery++The default `message.completed` handler sends the reply as SMS through Twilio's Messages API. A reply to an inbound message can reuse the webhook's `To` as the sender, but a proactive send has nothing to reuse, so it needs `messaging.from` or `messaging.messagingServiceSid`. Behind a proxy, set `webhookUrl` so signature verification matches the exact configured URL, and `publicBaseUrl` so voice TwiML can build absolute callback URLs.++### Human-in-the-loop (HITL)++SMS and voice have no native button or card affordance, so HITL prompts do not render as interactive controls. The agent's `input.requested` event reaches your `events["input.requested"]` handler if you declare one. Handle it by sending the prompt as text and mapping the caller's reply back to the input request yourself.++### Proactive sessions++Start a session without an inbound message through `receive(twilio, { message, target, auth })` from a schedule `run` handler, or `args.receive(twilio, ...)` from another channel. `target.phoneNumber` is required, and the channel needs `messaging.from` or `messaging.messagingServiceSid` for the outbound sender.++### Attachments++Inbound media attachments are not supported on this channel today.## What to read nextdiff --git a/docs/concepts/context-control.md b/docs/concepts/context-control.mdindex b52d335bc..0b27dfa63 100644--- a/docs/concepts/context-control.md+++ b/docs/concepts/context-control.md@@ -1,17 +1,11 @@---title: "Context Control"-description: "Control what the model sees and when: instructions, skills, the workspace, and subagents."+description: "Control what an Eve agent's model sees and when, across instructions, skills, the workspace, and subagents."----Eve gives you a few levers for controlling what the model sees and when it sees it.+Eve gives you a few levers for controlling what the model sees and when. `instructions.md` (or `instructions.ts`) is always on, `skills/` are available but loaded on demand, and the workspace and sandbox are visible through tools rather than pasted into the prompt.-The most useful mental model is:--- `instructions.md` (or `instructions.ts`) is always on.-- `skills/` are available but loaded on demand.-- The workspace and sandbox are visible through tools, not pasted into the prompt.--## 1. Base identity with `instructions.md`+## Base identity with `instructions.md`Use `instructions.md` for the core contract of the agent.@@ -22,9 +16,9 @@ used a tool.Keep this file focused on stable behavior that should apply on every turn.-## 2. Compose instructions in TypeScript with `instructions.ts`+## Compose instructions in TypeScript with `instructions.ts`-When you want to build the instructions prompt from typed helpers, lib code, or environment-derived values, author it as a module instead of markdown.+To build the instructions prompt from typed helpers, lib code, or environment-derived values, author it as a module instead of markdown.```ts title="agent/instructions.ts"import { defineInstructions } from "eve/instructions";@@ -37,13 +31,9 @@ export default defineInstructions({Module-backed instructions run once at build time. Eve captures the resulting markdown into the compiled manifest, so the runtime serves the same prompt every session without re-running the module.-## 3. Load procedures on demand with `skills/`--Skills are not part of the always-on prompt by default.--Instead, Eve advertises the available skills and adds a framework-owned `load_skill` tool. When the request clearly matches a skill description, or the user names a skill explicitly, the model activates that skill, and Eve appends the skill's markdown to the active instructions for later turn work.+## Load procedures on demand with `skills/`-That is how you keep rich procedures available without bloating every turn.+Skills stay out of the always-on prompt by default, which keeps rich procedures available without bloating every turn. Eve advertises the available skills and adds a framework-owned `load_skill` tool. When the request clearly matches a skill description, or the user names a skill explicitly, the model activates that skill, and Eve appends the skill's markdown to the active instructions for later turn work.### Flat skill@@ -62,48 +52,41 @@ When the task is novel or ambiguous, gather evidence first, then answer with theremaining uncertainty.```-Packaged skills are useful when you also want sibling files such as `references/`, `assets/`, or `scripts/` under the same skill directory. Those packaged paths show up under the runtime workspace root, so the model can inspect them with the normal file or shell tools instead of pasting all of that content into the prompt.+Packaged skills are useful when you also want sibling files such as `references/`, `assets/`, or `scripts/` under the same skill directory. Those paths show up under the runtime workspace root, so the model can inspect them with the normal file or shell tools instead of pasting their content into the prompt.See [Skills](../skills) for the full authoring model and install notes.-## 4. Put runtime files in the workspace, not the prompt+## Put runtime files in the workspace, not the prompt-Eve does not inline the entire authored surface into the prompt. Instead, it gives the model a shallow workspace hint and runtime tools to inspect deeper when needed. That keeps prompts smaller and makes file and command work explicit: skill files are available under the active workspace root, and the model can inspect them with the shared `bash` tool.+Eve does not inline the entire authored surface into the prompt. Instead, it gives the model a shallow workspace hint and runtime tools to inspect deeper when needed. Skill files are available under the active workspace root, and the model inspects them with the shared `bash` tool, which keeps prompts smaller and makes file and command work explicit.See [Sandbox](../sandbox) for the workspace and sandbox model.-## 5. Delegate to a specialist with a subagent+## Delegate to a specialist with a subagent-If a task deserves its own prompt and tool surface, use a local subagent instead of overloading the root agent. Subagents are a context-control tool too: they get their own `instructions.md`, their own tools, and their own sandbox, and they run inside their own delegated context instead of extending the root agent inline.+If a task deserves its own prompt and tool surface, use a local subagent instead of overloading the root agent. Subagents are a context-control lever too. They get their own `instructions.md`, tools, and sandbox, and they run inside their own delegated context instead of extending the root agent inline.See [Subagents](../subagents).## Dynamic context with `defineDynamic`-The levers above are static: authored once, the same on every session. When the right context depends on who is calling (their team, tenant, plan, or feature flags), resolve it at runtime instead. `defineDynamic` in `agent/instructions/` returns the per-session system prompt, and `defineDynamic` in `agent/skills/` returns the set of skills a caller can load. Both read `ctx.session.auth` or channel metadata, so a caller on the billing team gets the billing instructions and playbook while nobody else sees them. See [Dynamic capabilities](../guides/dynamic-capabilities) for the resolver API and when each event fires.+The levers above are static, authored once and the same on every session. When the right context depends on who is calling (their team, tenant, plan, or feature flags), resolve it at runtime instead. `defineDynamic` in `agent/instructions/` returns the per-session system prompt, and `defineDynamic` in `agent/skills/` returns the set of skills a caller can load. Both read `ctx.session.auth` or channel metadata, so a caller on the billing team gets the billing instructions and playbook while no one else sees them. See [Dynamic capabilities](../guides/dynamic-capabilities) for the resolver API and when each event fires.-## Choosing the right lever+## Recommended context layout-Use:+Pick the lever by what the context is for:-- `instructions.md` for the agent's permanent identity.+- `instructions.md` for the agent's permanent identity. Keep it short and stable.- `instructions.ts` when you need to compose the prompt from typed helpers at build time.-- `skills/` for optional procedures that should load only when needed.-- a subagent when the task needs a different specialist surface.+- `skills/` for optional procedures that should load only when needed. Move long procedures here instead of into the always-on prompt.+- `tools/` to expose typed integrations.+- a subagent when the task needs a different specialist surface; use one only for real specialization boundaries.- the workspace or sandbox when the model should inspect files or run commands instead of relying on pasted instructions.-## A good pattern--For most agents:--1. Keep `instructions.md` short and stable.-2. Move long procedures into `skills/`.-3. Expose typed integrations through `tools/`.-4. Use subagents only for real specialization boundaries.-## What to read next-- [Tools](../tools)-- [Skills](../skills)-- [Subagents](../subagents)-- [Hooks](../guides/hooks)+- [Tools](../tools): expose typed integrations the model can call.+- [Skills](../skills): the full authoring model for on-demand procedures.+- [Subagents](../subagents): delegate to a specialist with its own prompt and tools.+- [Dynamic capabilities](../guides/dynamic-capabilities): resolve per-session instructions and skills with `defineDynamic`.+- [Hooks](../guides/hooks): run code on session events to update the channel state that dynamic resolvers read.diff --git a/docs/concepts/default-harness.md b/docs/concepts/default-harness.mdindex ead84f15a..731099c8b 100644--- a/docs/concepts/default-harness.md+++ b/docs/concepts/default-harness.md@@ -1,13 +1,13 @@---title: "The Harness"-description: "The out-of-the-box agent loop and the built-in tools every Eve agent ships with, plus how to override or disable them."+description: "The out-of-the-box Eve agent loop and the built-in tools every agent ships with, plus how to override or disable them."----The default harness is what every Eve agent ships with: the framework-owned agent loop, plus a set of built-in tools the model can call without you writing a line. You extend the base harness with capabilities specific to your agent. The loop itself, how a turn runs and checkpoints and resumes, lives in [Execution model & durability](./execution-model-and-durability).+The default harness is what every Eve agent ships with. It includes the framework-owned agent loop plus a set of built-in tools the model can call without you writing a line. You extend it with capabilities specific to your agent. The loop itself, how a turn runs and checkpoints and resumes, lives in [Execution model and durability](./execution-model-and-durability).## Compaction-A long session eventually fills the model's context window. The harness handles that for you: once the conversation crosses a fraction of the window (`thresholdPercent`, `0.9` by default), it summarizes the older turns into a compact form and keeps going, so the session continues instead of overflowing. The summary uses the active turn model unless you override it. Tune when and how it kicks in under [`compaction`](../agent-config#compaction) in `agent.ts`:+The harness keeps a long session from overflowing the model's context window. Once the conversation crosses a fraction of the window (`thresholdPercent`, `0.9` by default), it summarizes the older turns into a compact form and keeps going. The summary uses the active turn model unless you override it. Tune when and how it kicks in under [`compaction`](../agent-config#compaction) in `agent.ts`:```ts title="agent/agent.ts"export default defineAgent({@@ -18,11 +18,11 @@ export default defineAgent({});```-Compaction also preserves the framework's own tool state automatically. When the harness compacts history, it resets read-before-write tracking (so a write afterward re-reads the file whose read evidence was summarized away) and re-injects the active todo list, so the model keeps its task list across the summary. There is no per-tool hook to configure.+Compaction also preserves the framework's own tool state automatically. It resets read-before-write tracking (so a write afterward re-reads the file whose read evidence was summarized away) and re-injects the active todo list, so the model keeps its task list across the summary. There is no per-tool hook to configure.## Built-in tools-These ship with every agent, no imports. Discovery never runs them: the harness shows the model the tool descriptors first, then executes only what the model actually calls. The shell and file tools run inside the agent's single [sandbox](../sandbox); the rest run in the app runtime.+These ship with every agent, no imports. The harness shows the model the tool descriptors first, then executes only what the model actually calls; discovery never runs them. The shell and file tools (`bash`, `read_file`, `write_file`, `glob`, `grep`) live in the app runtime and proxy their work into the agent's single [sandbox](../sandbox); the rest run in the app runtime. The "Where it runs" column below names where each tool's effect lands.| Tool | Does | Where it runs || ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |@@ -48,7 +48,7 @@ Notes:## Override a default-Author a tool at the same slug and it takes over the built-in of that name. The file `agent/tools/write_file.ts` replaces the built-in `write_file` just by existing:+Author a tool at the same slug and it takes over the built-in of that name. The file `agent/tools/write_file.ts` replaces the built-in `write_file` by existing:```ts title="agent/tools/write_file.ts"import { defineTool } from "eve/tools";@@ -63,7 +63,7 @@ export default defineTool({});```-The framework defaults are importable from `eve/tools/defaults` (`bash`, `readFile`, `writeFile`, `glob`, `grep`, `webFetch`, `webSearch`, `todo`, `loadSkill`), so you can spread, wrap, or patch them. Skip the spread and your replacement owns its own context: a fresh `defineTool` for `todo` won't inherit the framework's durable state key.+The framework defaults are importable from `eve/tools/defaults` (`bash`, `readFile`, `writeFile`, `glob`, `grep`, `webFetch`, `webSearch`, `todo`, `loadSkill`), so you can spread, wrap, or patch them. Skip the spread and your replacement owns its own context. A fresh `defineTool` for `todo` won't inherit the framework's durable state key.## Disable a default@@ -75,11 +75,19 @@ import { disableTool } from "eve/tools";export default disableTool();```-Misspell the filename so it matches no known framework tool and it fails at resolve time, instead of silently doing nothing.+If the filename matches no known framework tool, resolution fails instead of silently doing nothing, so a typo surfaces at build time rather than removing the wrong tool.++## When to override, disable, or author a new tool++Three moves shape the harness. The right one depends on whether the model should keep the built-in capability.++- **Override** when you want the same capability with different behavior. Spread the default from `eve/tools/defaults` and wrap it (logging, an extra guard, a different backend), and the model still sees a tool by that name. Spreading keeps the default's description, schema, and any framework state, such as the `todo` tool's durable state key. Drop the spread and your replacement owns its own context, losing that wiring.+- **Disable** when the model should not have the capability at all. A `disableTool()` sentinel removes the built-in, and the model never sees it. Reach for this to lock down `bash` or `web_fetch` in an agent that should not run shell commands or fetch arbitrary URLs.+- **Author a new tool** when you want a capability the harness does not ship. Give it a fresh slug under `agent/tools/` and it joins the built-ins instead of replacing one. See [Tools](../tools) for the authoring model.## The opt-in `Workflow` tool-There's also an experimental `Workflow` tool, shipped but off by default. To turn it on, re-export the opt-in marker from `agent/tools/workflow.ts`:+An experimental `Workflow` tool ships but stays off by default. To turn it on, re-export the opt-in marker from `agent/tools/workflow.ts`:```tsexport { ExperimentalWorkflow as default } from "eve/tools";diff --git a/docs/concepts/execution-model-and-durability.md b/docs/concepts/execution-model-and-durability.mdindex 22be99b1d..a1ec2424b 100644--- a/docs/concepts/execution-model-and-durability.md+++ b/docs/concepts/execution-model-and-durability.md@@ -1,9 +1,9 @@----title: "Execution Model & Durability"-description: "How a session runs: durable conversations, turns that checkpoint at steps, and parked work that resumes later."+title: "Execution Model and Durability"+description: "How an Eve session runs. Durable conversations, turns that checkpoint at steps, and parked work that resumes later."----A session is a durable conversation. It can run for days, and it survives process restarts and redeploys without any work on your part. You write the capabilities (tools, instructions, channels) and Eve runs the loop.+An Eve session is a durable conversation. It can run for days and survives process restarts and redeploys without any work on your part. You write the capabilities (tools, instructions, channels) and Eve runs the loop.## Sessions, turns, and steps@@ -13,38 +13,38 @@ Work nests in three levels:- **turn**: one user message and all the work it triggers (model calls, tool calls, reasoning) until the agent produces its response.- **step**: a durable checkpoint inside a turn (one model call and the tool calls it makes).-Every turn runs as a durable workflow, built on the open-source [Workflow SDK](https://workflow-sdk.dev/) (Vercel Workflow when you deploy on Vercel). Eve checkpoints progress at each step and serializes durable state at that boundary. Your code runs inside a managed step, so tools, the sandbox, and subagents feel synchronous even though the session underneath them is durable.+Every turn runs as a durable workflow, built on the open-source [Workflow SDK](https://workflow-sdk.dev/) (Vercel Workflow when you deploy on Vercel). Eve checkpoints progress and serializes durable state at each step boundary. Your code runs inside a managed step, so tools, the sandbox, and subagents feel synchronous even though the session underneath them is durable.## Resuming after a crash-Crash the process, hit a timeout, or redeploy mid-turn, and the run picks up from the last completed step rather than replaying the whole turn. Re-running a step from the same input is idempotent. Your tool calls don't fire twice, so a resume never doubles up a side effect (a charge, an email, a write).+Crash the process, hit a timeout, or redeploy mid-turn, and the run picks up from the last completed step rather than replaying the whole turn. Completed steps never re-run; Eve replays the recorded result. A step interrupted mid-execution re-runs, so make non-idempotent side effects like charges or emails idempotent, or gate them with approval.-There's nothing to configure here. Eve owns the workflow lifecycle, and sessions are durable by default.+There's nothing to configure. Eve owns the workflow lifecycle, and sessions are durable by default.-You don't write workflow code directly. Workflow primitives (`start()`, `resumeHook()`, etc.) are an implementation detail of Eve's runtime layer; channels, tools, and hooks never touch them. When you do need session data from your own code, there are two supported surfaces: tools read the current session's metadata (id, turn, auth, parent lineage) via `ctx.session`, and [`defineState`](../guides/session-context) reads or writes session-scoped durable state. See [State](../guides/state) for the read/write model.+You don't write workflow code directly. Workflow primitives (`start()`, `resumeHook()`, etc.) are an implementation detail of Eve's runtime layer; channels, tools, and hooks never touch them. Two surfaces give your own code session data: tools read the current session's metadata (id, turn, auth, parent lineage) via `ctx.session`, and [`defineState`](../guides/state) reads or writes session-scoped durable state. See [State](../guides/state) for the read/write model.## Parked work-Some work has to wait: a human approving a [tool](../tools), an interactive OAuth sign-in for a [connection](../connections), or a long-running [subagent](../subagents). At those points the turn parks durably. The workflow suspends and holds no compute until the input it's waiting on shows up (a click, a callback, a child completing), even if that's much later. When it does, the conversation picks up exactly where it left off.+Some work has to wait, including a human approving a [tool](../tools), an interactive OAuth sign-in for a [connection](../connections), or a long-running [subagent](../subagents). At those points the turn parks durably. The workflow suspends and holds no compute until the input it's waiting on arrives (a click, a callback, a child completing), even if that's much later. When it does, the conversation picks up exactly where it left off.## Message delivery and queueing-Eve does not maintain a durable FIFO queue of user messages for a session today. The `continuationToken` is a resume handle for the session's current workflow hook, not a general message-queue address.+Eve does not maintain a durable FIFO queue of user messages for a session. The `continuationToken` is a resume handle for the session's current workflow hook, not a general message-queue address.-When a session is waiting, a delivery to the current continuation token wakes the session and starts the next turn. When a turn is already active, additional deliveries may be accepted by the hook, but the runtime only drains them at specific workflow boundaries. If more than one delivery is already ready when the driver checks, Eve may fold them into the next turn; that drain is best-effort and depends on workflow and transport timing.+When a session is waiting, a delivery to the current continuation token wakes the session and starts the next turn. When a turn is already active, the hook may accept additional deliveries, but the runtime only drains them at specific workflow boundaries. If more than one delivery is ready when the driver checks, Eve may fold them into the next turn; that drain is best-effort and depends on workflow and transport timing.-That means applications should not rely on concurrent sends to the same session behaving like a typical ordered chat queue. For deterministic behavior, send one user turn at a time: wait for `session.waiting` before sending the next message to the same session. If your channel can receive bursts while the agent is working, keep your own per-session queue in the channel or app layer, then deliver the next message after the session parks again. Separate sessions can still run independently.+So don't rely on concurrent sends to the same session behaving like a typical ordered chat queue. For deterministic behavior, send one user turn at a time and wait for `session.waiting` before sending the next message to the same session. If your channel can receive bursts while the agent is working, keep your own per-session queue in the channel or app layer, then deliver the next message after the session parks again. Separate sessions still run independently.## SubagentsA turn can hand work off to a [subagent](../subagents). Each subagent gets its own context and its own durable session; a declared subagent also gets its own sandbox, skills, and state. Nothing crosses the boundary implicitly.-## Ordering+## How Eve orders session history-Conversation history within a session is append-only. Turns land in order, and the tool calls inside a turn (plus their results) keep their order too. Read a session back and you see things in the order they happened.+Conversation history within a session is append-only. Turns land in order, and the tool calls inside a turn (plus their results) keep their order too. Read a session back and you see events in the order they happened.## What to read next-- [Sessions, runs & streaming](./sessions-runs-and-streaming): the handles you hold and the event stream you watch.+- [Sessions and streaming](./sessions-runs-and-streaming): the handles you hold and the event stream you watch.- [Security model](./security-model): the trust boundaries the runtime enforces.- [State](../guides/state): durable per-session memory that persists across step boundaries.diff --git a/docs/concepts/security-model.md b/docs/concepts/security-model.mdindex a514ac21d..c3c4affd5 100644--- a/docs/concepts/security-model.md+++ b/docs/concepts/security-model.md@@ -1,9 +1,9 @@---title: "Security Model"-description: "Trust boundaries, where secrets live, how credentials reach hosts, and what fails closed by default."+description: "Eve's trust boundaries, where secrets live, how credentials reach hosts, and what fails closed by default."----Your agent runs across two contexts, with a trust boundary drawn between them and every secret kept on the trusted side. This page is the mental model to use when you're deciding what an agent (and the model driving it) is allowed to reach.+Your Eve agent runs across two contexts, with a trust boundary between them and every secret kept on the trusted side. Use this mental model when deciding what an agent (and the model driving it) is allowed to reach.## Trust boundaries@@ -16,13 +16,13 @@ Your agent runs across two contexts, with a trust boundary drawn between them anThe app runtime is the trusted side. Your tool implementations, model calls, connections, state, and durable execution all run here, with `process.env` and full Node.js available. (On Vercel, this is a Vercel Function.)-The sandbox is the isolated side. The model runs shell commands there through the built-in `bash`, `read_file`, `write_file`, `glob`, and `grep` tools. It gets its own `/workspace` filesystem, but no `process.env`, no secrets, and no path back into the app runtime. (On Vercel, each sandbox is a [Vercel Sandbox](https://vercel.com/docs/sandbox) microVM with hardware-level isolation.) The only thing that actually executes in the sandbox is shell commands. Even the built-in `bash`/`read_file`/`write_file` tools live in the app runtime and _proxy_ into the sandbox. The model sees tool definitions and results, never your secrets.+The sandbox is the isolated side. The model runs shell commands there through the built-in `bash`, `read_file`, `write_file`, `glob`, and `grep` tools. It gets its own `/workspace` filesystem, but no `process.env`, no secrets, and no path back into the app runtime. (On Vercel, each sandbox is a [Vercel Sandbox](https://vercel.com/docs/sandbox) microVM with hardware-level isolation.) Only shell commands execute in the sandbox. Even the built-in `bash`/`read_file`/`write_file` tools live in the app runtime and _proxy_ into the sandbox. The model sees tool definitions and results, never your secrets.A concrete trace makes the boundary clear. When the model calls a custom `charge_card` tool, its `execute` runs in the app runtime, reads `process.env.STRIPE_KEY`, calls Stripe, and returns `{ ok: true }`. The model sees only `{ ok: true }`: the key never leaves the app runtime, and nothing about the call touches the sandbox. The built-in `write_file` is the mirror image, running in the app runtime and proxying the write into the sandbox `/workspace`. Either way the model drives the work through tool calls and their results, never by holding a credential or reaching the runtime directly.## Credential brokering-Sometimes the model needs _authenticated_ network access from inside the sandbox, like a `git clone` of a private repo or an authenticated `curl`, and there's no [tool](../tools) or [connection](../connections) to route it through. That's what credential brokering is for. On the Vercel Sandbox backend, auth headers get injected at the sandbox's network firewall for matching domains. The secret stays in the app runtime; the sandbox process only ever sees the response. See [Vercel Sandbox Credential Brokering](https://vercel.com/docs/sandbox/concepts/firewall#credentials-brokering) for the platform mechanism, and [Sandbox](../sandbox) for the Eve policy API.+Credential brokering gives the model _authenticated_ network access from inside the sandbox, like a `git clone` of a private repo or an authenticated `curl`, when there's no [tool](../tools) or [connection](../connections) to route it through. On the Vercel Sandbox backend, auth headers get injected at the sandbox's network firewall for matching domains. The secret stays in the app runtime; the sandbox process only ever sees the response. See [Vercel Sandbox Credential Brokering](https://vercel.com/docs/sandbox/concepts/firewall#credentials-brokering) for the platform mechanism, and [Sandbox](../sandbox) for the Eve policy API.## Connection credentials@@ -30,7 +30,7 @@ Sometimes the model needs _authenticated_ network access from inside the sandbox## Channel verification-A [channel](../channels/overview) is your agent's front door, which makes authenticating inbound traffic its job. The built-in platform channels follow two rules here, and so must any channel you write yourself:+A [channel](../channels/overview) is your agent's front door, so authenticating inbound traffic is its job. The built-in platform channels follow two rules, and so must any channel you write yourself:- **Verify signatures in constant time.** Platform channels (Slack, GitHub,Telegram, Twilio) verify the platform's HMAC signature over the raw request body@@ -46,11 +46,11 @@ A custom channel that accepts dashboard-style webhooks should follow the same sh## Authored markdown is data-[Skill](../skills) and [schedule](../schedules) files are markdown with YAML frontmatter, and Eve treats that frontmatter strictly as data. The code-capable engines (`---js` / `---javascript`, which would `eval()` the frontmatter body the moment the file is parsed) are disabled. A fence like that throws rather than running. Frontmatter has to parse to a plain YAML object.+[Skill](../skills) and [schedule](../schedules) files are markdown with YAML frontmatter, and Eve treats that frontmatter strictly as data. The code-capable engines (`---js` / `---javascript`, which would `eval()` the frontmatter body the moment the file is parsed) are disabled, so such a fence throws rather than running. Frontmatter has to parse to a plain YAML object.## Auth fails closed-Routes reject unauthenticated traffic by default: if no `AuthFn` in the walk accepts the request, it gets a `401`, and admitting anonymous callers takes an explicit `none()`. The scaffold's `placeholderAuth()` keeps a half-configured app closed in production until you replace it. See [Auth & route protection](../guides/auth-and-route-protection) for the full walk and verifiers.+Routes reject unauthenticated traffic by default. If no `AuthFn` in the walk accepts the request, it gets a `401`, and admitting anonymous callers takes an explicit `none()`. The scaffold's `placeholderAuth()` keeps a half-configured app closed in production until you replace it. See [Auth & route protection](../guides/auth-and-route-protection) for the full walk and verifiers.## Pre-production checklist@@ -75,5 +75,5 @@ Before exposing an agent to real traffic:- [Auth & route protection](../guides/auth-and-route-protection): the full auth walk and verifier helpers- [Sandbox](../sandbox): backends, network policy, and brokering config-- [Execution model & durability](./execution-model-and-durability): how durable sessions run+- [Execution model and durability](./execution-model-and-durability): how durable sessions run- [Connections](../connections): static-token and OAuth connectionsdiff --git a/docs/concepts/sessions-runs-and-streaming.md b/docs/concepts/sessions-runs-and-streaming.mdindex 8e6183996..6b363fa6c 100644--- a/docs/concepts/sessions-runs-and-streaming.md+++ b/docs/concepts/sessions-runs-and-streaming.md@@ -7,7 +7,7 @@ Every Eve app speaks the same stable HTTP API to a [durable session](./execution## The two handles-Two handles do two jobs here, and mixing them up is the most common mistake. One handle creates and resumes a session; a different one streams and inspects it.+Two handles do two jobs, and mixing them up is the most common mistake. One handle creates and resumes a session; a different one streams and inspects it.- **`continuationToken`**: the resume handle. Use it to send a follow-up message to the same conversation. Owned by the channel.- **`sessionId` / `runId`**: the stream-and-inspect handle. Use it to attach to the event stream and watch a run. Owned by the runtime.@@ -19,17 +19,17 @@ React, Vue, and Svelte apps reach for [`useEveAgent()`](../guides/frontend/overv## Start a session```bash-curl -X POST http://127.0.0.1:2000/eve/v1/session \+curl -X POST http://127.0.0.1:3000/eve/v1/session \-H 'content-type: application/json' \-d '{"message":"Summarize the latest forecast."}'```-Eve responds right away. The JSON body carries a `sessionId` and a `continuationToken`, and the `x-eve-session-id` header tells you which durable session to stream.+Eve responds right away. The JSON body carries a `sessionId` and a `continuationToken`, and the `x-eve-session-id` header names the durable session to stream.## Stream a session```bash-curl http://127.0.0.1:2000/eve/v1/session/<sessionId>/stream+curl http://127.0.0.1:3000/eve/v1/session/<sessionId>/stream```The stream is newline-delimited JSON (NDJSON), one event per line:@@ -75,7 +75,7 @@ A delegated subagent publishes progress on its own child-session stream. The parOnce the session is waiting (you'll see `session.waiting`), POST your follow-up to the session endpoint with the stored continuation token:```bash-curl -X POST http://127.0.0.1:2000/eve/v1/session/<sessionId> \+curl -X POST http://127.0.0.1:3000/eve/v1/session/<sessionId> \-H 'content-type: application/json' \-d '{"continuationToken":"<token>","message":"Now send the short version."}'```@@ -86,10 +86,10 @@ For deterministic ordering, send one follow-up at a time and wait for the next `## Reconnect and rewind-The stream is durable. Every event is recorded before a step completes, so it's all replayable. Pass `startIndex` to reconnect by event count and pick up where you dropped off, or rewind to the start:+The stream is durable. Every event is recorded before a step completes, so the whole stream is replayable. Pass `startIndex` to reconnect by event count and pick up where you dropped off, or rewind to the start:```bash-curl "http://127.0.0.1:2000/eve/v1/session/<sessionId>/stream?startIndex=<count>"+curl "http://127.0.0.1:3000/eve/v1/session/<sessionId>/stream?startIndex=<count>"```## Use the client from TypeScript@@ -103,7 +103,7 @@ Start with the [TypeScript SDK](../guides/client/overview) guide. It covers basi`GET /eve/v1/info` returns a JSON inspection snapshot for the running agent: model, instructions, authored and framework tools, skills, channels, schedules, subagents, sandbox, connections, hooks, workflow, and workspace metadata. Local development accepts loopback requests; deployed Vercel targets require the route's OIDC auth.```bash-curl http://127.0.0.1:2000/eve/v1/info+curl http://127.0.0.1:3000/eve/v1/info```The route uses the same default auth chain as the eve channel (`[localDev(), vercelOidc()]`). Locally it answers anonymously; a deployed Vercel target requires a valid OIDC bearer, with a same-project bypass for in-deployment callers. See [auth & route protection](../guides/auth-and-route-protection).@@ -117,7 +117,7 @@ Every stream event runs four steps, in this order:3. **Hooks**: authored [hooks](../guides/hooks) subscribed to the event fire.4. **Dynamic resolvers**: [dynamic](../guides/dynamic-capabilities) tool, skill, and instruction resolvers fire, and `ctx.channel.metadata` already holds the freshly projected metadata from step 2.-The order isn't incidental, it's structural. By the time a resolver or hook reads channel metadata, the channel has already updated its state and the projection is current.+The order is structural, not incidental. By the time a resolver or hook reads channel metadata, the channel has already updated its state and the projection is current.## What to read nextdiff --git a/docs/connections.mdx b/docs/connections.mdxindex d50eb3870..47397140c 100644--- a/docs/connections.mdx+++ b/docs/connections.mdx@@ -1,15 +1,15 @@---title: "Connections"-description: "Expose external MCP and OpenAPI servers to the model: with connection tokens the model never sees."+description: "Expose external MCP and OpenAPI servers to the model, with connection tokens the model never sees."----A connection wires an agent into an external server you don't author: an MCP server (Linear, GitHub, a warehouse) or any HTTP API with an OpenAPI document. Eve handles the parts you'd otherwise hand-roll: it discovers the remote tools, surfaces them to the model, and brokers auth.+A connection wires an agent into an external server you don't author, either an MCP server (Linear, GitHub, a warehouse) or any HTTP API with an OpenAPI document. Eve handles the parts you'd otherwise hand-roll, discovering the remote tools, surfacing them to the model, and brokering auth.Connections live under `agent/connections/`. The runtime name comes from the filename, so `agent/connections/linear.ts` registers as `"linear"`. The model never sees a connection's URL or credentials. It discovers tools through the built-in `connection__search` and calls them by their qualified name, `connection__<connection>__<tool>` (e.g. `connection__linear__list_issues`).## MCP connections-`defineMcpClientConnection` points at an MCP server. All you have to supply is a `url` and a `description`:+`defineMcpClientConnection` points at an MCP server. Supply a `url` and a `description`:```ts title="agent/connections/linear.ts"import { defineMcpClientConnection } from "eve/connections";@@ -23,11 +23,11 @@ export default defineMcpClientConnection({});```-The `url` must speak Streamable HTTP or SSE. Write the `description` for the model, not for yourself. It shows up in `connection__search`, and the model leans on it to decide which connection to query.+The `url` must speak Streamable HTTP or SSE. Write the `description` for the model, not for yourself. It shows up in `connection__search`, and the model uses it to decide which connection to query.### Static-token auth-`getToken` returns a `TokenResult` (`{ token, expiresAt? }`), and Eve sends it as `Authorization: Bearer <token>` on every request. Because it runs on each connection attempt, you can mint a fresh token from wherever you keep secrets: an env var, a secrets manager, an internal vault, or your own OAuth exchange. If the token has a known TTL, set `expiresAt` (milliseconds since epoch) and Eve refreshes ahead of time rather than waiting for a `401`.+`getToken` returns a `TokenResult` (`{ token, expiresAt? }`), and Eve sends it as `Authorization: Bearer <token>` on every request. Because it runs on each connection attempt, you can mint a fresh token from wherever you keep secrets, including an env var, a secrets manager, an internal vault, or your own OAuth exchange. If the token has a known TTL, set `expiresAt` (milliseconds since epoch) and Eve refreshes ahead of time rather than waiting for a `401`.When `getToken` is the only auth, `principalType` defaults to `"app"`: one shared credential keyed across all sessions. Switch to `principalType: "user"` when each end-user carries their own token.@@ -35,7 +35,7 @@ Eve resolves and caches connection tokens per step; they never land in conversat### No auth-Drop `auth` entirely for servers that need no token, like a localhost server during development or a public one:+Drop `auth` entirely for servers that need no token, such as a localhost server during development or a public one:```tsexport default defineMcpClientConnection({@@ -46,7 +46,7 @@ export default defineMcpClientConnection({### Headers-Reach for `headers` when the server wants a non-Bearer scheme (an API-key header) or some extra configuration. Headers stack on top of `auth`:+Use `headers` when the server wants a non-Bearer scheme (an API-key header) or extra configuration. Headers stack on top of `auth`:```tsexport default defineMcpClientConnection({@@ -58,7 +58,7 @@ export default defineMcpClientConnection({### Tool filters-To narrow which remote tools the model sees, set exactly one of `tools.allow` or `tools.block`. Filtered-out tools just don't appear in `connection__search`:+To narrow which remote tools the model sees, set exactly one of `tools.allow` or `tools.block`. Filtered-out tools do not appear in `connection__search`:```tsexport default defineMcpClientConnection({@@ -84,11 +84,11 @@ export default defineMcpClientConnection({});```-`never()` lets every call through, `once()` asks for approval the first time in a session, and `always()` asks every time. The pause and resume here is the same human-in-the-loop flow covered in [Tools](./tools).+`never()` lets every call through, `once()` asks for approval the first time in a session, and `always()` asks every time. The pause and resume is the same human-in-the-loop flow covered in [Tools](./tools).## OpenAPI connections-`defineOpenAPIConnection` turns any OpenAPI 3.x or Swagger 2.0 document into connection tools, one per operation. Pass an HTTPS URL Eve fetches at runtime, or an inline parsed object:+`defineOpenAPIConnection` turns any OpenAPI 3.x document into connection tools, one per operation. Pass an HTTPS URL Eve fetches at runtime, or an inline parsed object:```ts title="agent/connections/petstore.ts"import { defineOpenAPIConnection } from "eve/connections";@@ -104,10 +104,10 @@ Each operation becomes `connection__<connection>__<operationId>` (e.g. `connecti`auth`, `headers`, and `approval` work exactly as they do for MCP. There are two fields specific to OpenAPI:-| Field | Purpose |-| ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- |-| `baseUrl` | Base URL operation paths resolve against. Optional; defaults to the document's first usable `servers` entry or Swagger `schemes`/`host`/`basePath`. |-| `operations` | Filter keyed on `operationId` (`allow` or `block`). Mirrors `tools` on MCP connections, but names operations not tools. |+| Field | Purpose |+| ------------ | ----------------------------------------------------------------------------------------------------------------------- |+| `baseUrl` | Base URL operation paths resolve against. Optional; defaults to the document's first usable `servers` entry. |+| `operations` | Filter keyed on `operationId` (`allow` or `block`). Mirrors `tools` on MCP connections, but names operations not tools. |## Interactive OAuth via Vercel Connect@@ -128,7 +128,7 @@ export default defineMcpClientConnection({## Self-hosted interactive OAuth-Running your own OAuth? Use `defineInteractiveAuthorization` from `eve/connections`, which takes a three-method form. Eve mints a callback URL, parks the turn on a framework-owned webhook, and resumes once the token comes back. No Vercel Connect required. Interactive auth is always `principalType: "user"`, and the factory pins that for you.+To run your own OAuth, use `defineInteractiveAuthorization` from `eve/connections`, which takes a three-method form and needs no Vercel Connect. Eve mints a callback URL, parks (durably suspends) the turn on a framework-owned webhook, and resumes once the token comes back. Interactive auth is always `principalType: "user"`, and the factory pins that for you.```ts title="agent/connections/linear.ts"import {@@ -168,9 +168,18 @@ export default defineMcpClientConnection({});```-`getToken` runs before every tool call. `startAuthorization` and `completeAuthorization` are both-or-neither: provide one without the other and you get a definition error. The `challenge` rides along verbatim on the `authorization.required` event. Set `url` for redirect/device flows, `userCode` for a device code, `instructions` as the call to action when there's no URL, and `displayName` for the human-readable provider name channels show on the sign-in affordance (e.g. "Salesforce"). Drop `resume` when the provider keeps flow state server-side, so nothing has to cross the step boundary.+`getToken` runs before every tool call. `startAuthorization` and `completeAuthorization` are both-or-neither: provide one without the other and you get a definition error. The `challenge` rides along verbatim on the `authorization.required` event. Its fields:-`displayName` is presentation-only — the connection's path-derived name still keys the authorization scope, token cache, and callback URL. You can also set `displayName` on the `auth` definition itself (e.g. `auth: { ...connect("sfdc"), displayName: "Salesforce" }`); that definition-level value wins over one the strategy stamps on the challenge, and channels fall back to title-casing the connection name when neither is set.+| Field | Purpose |+| -------------- | ----------------------------------------------------------------------------------------- |+| `url` | The authorize URL for redirect or device flows. |+| `userCode` | The device code, for device flows. |+| `instructions` | The call to action when there's no URL. |+| `displayName` | Human-readable provider name channels show on the sign-in affordance (e.g. "Salesforce"). |++Drop `resume` when the provider keeps flow state server-side, so nothing has to cross the step boundary.++`displayName` is presentation-only. The connection's path-derived name still keys the authorization scope, token cache, and callback URL. You can also set `displayName` on the `auth` definition itself (e.g. `auth: { ...connect("sfdc"), displayName: "Salesforce" }`); that definition-level value wins over one the strategy stamps on the challenge, and channels fall back to title-casing the connection name when neither is set.### Signaling authorization state@@ -192,24 +201,31 @@ To narrow a caught error, use `isConnectionAuthorizationRequiredError(err)` and### Handling a revoked token mid-call-`getToken` only runs _before_ a tool call, so a grant revoked while a tool is mid-flight first surfaces as a downstream `401` inside your `execute`. A plain throw there is just a tool error — the model sees a failure and the cached bearer sticks around. Instead, map a provider `401` to `ctx.requireAuth()` (or rethrow `ConnectionAuthorizationRequiredError`). Eve then evicts the rejected token from its per-step cache and re-runs the consent flow with a fresh one, exactly as it does for a connection whose server rejects the bearer.+`getToken` only runs _before_ a tool call, so a grant revoked while a tool is mid-flight first surfaces as a downstream `401` inside your `execute`. A plain throw there is only a tool error, so the model sees a failure and the cached bearer sticks around. Instead, map a provider `401` to `ctx.requireAuth()` (or rethrow `ConnectionAuthorizationRequiredError`). Eve then evicts the rejected token from its per-step cache and re-runs the consent flow with a fresh one, exactly as it does for a connection whose server rejects the bearer.```ts title="agent/tools/list_issues.ts"-async execute(_input, ctx) {- const { token } = await ctx.getToken();- const res = await fetch("https://api.linear.app/graphql", {- headers: { authorization: `Bearer ${token}` },- });- // The grant was revoked since getToken ran: re-challenge instead of- // returning a dead-token error to the model.- if (res.status === 401) ctx.requireAuth();- return await res.json();-}+import { defineTool } from "eve/tools";+import { z } from "zod";++export default defineTool({+ description: "List open Linear issues.",+ inputSchema: z.object({}),+ async execute(_input, ctx) {+ const { token } = await ctx.getToken();+ const res = await fetch("https://api.linear.app/graphql", {+ headers: { authorization: `Bearer ${token}` },+ });+ // The grant was revoked since getToken ran: re-challenge instead of+ // returning a dead-token error to the model.+ if (res.status === 401) ctx.requireAuth();+ return await res.json();+ },+});```### Authorization and approval together-A tool can require both sign-in (`auth`) and a human approval. Today the model's approval gate runs before the tool's `execute`, so the order the user sees is **approve, then sign in**. Eve records the approval on session state the moment it's granted, and that record survives the sign-in park — so when the turn resumes after authorization, the tool is not put through approval a second time. You get one approval and one sign-in, never a double prompt.+A tool can require both sign-in (`auth`) and a human approval. The model's approval gate runs before the tool's `execute`, so the order the user sees is **approve, then sign in**. Eve records the approval on session state the moment it's granted, and that record survives the sign-in park, so when the turn resumes after authorization the tool is not put through approval again. You get one approval and one sign-in, never a double prompt.## What to read nextdiff --git a/docs/evals/assertions.mdx b/docs/evals/assertions.mdxindex 1f4a3629a..952089887 100644--- a/docs/evals/assertions.mdx+++ b/docs/evals/assertions.mdx@@ -3,37 +3,38 @@ title: "Assertions"description: "Run-level methods, t.check value assertions, the matcher mini-language, and gate vs soft severity."----Assertions are how an eval grades what its `test(t)` function produced. Each one **records** a result onto `t` and returns a chainable handle — the runner reads the recorded results to compute the verdict, so a single run reports every failing assertion rather than dying on the first. There are two deterministic surfaces: run-level methods on `t`, and `t.check` for grading a specific value. For model-graded assertions, see [Judge](./judge).+Assertions are how an eval grades what its `test(t)` function produced. Each one **records** a result onto `t` and returns a chainable handle. The runner reads the recorded results to compute the verdict, so a single run reports every failing assertion rather than dying on the first. There are two deterministic surfaces: run-level methods on `t`, and `t.check` for grading a specific value. For model-graded assertions, see [Judge](./judge).## Run-level assertions-Run-level assertions read the whole run, so they take no value. They are methods on `t` and gate by default.--| Assertion | Asserts |-| --------------------------------------------------- | --------------------------------------------------------------------------------- |-| `t.completed()` | The run did not fail and did not park on unanswered HITL input |-| `t.didNotFail()` | No terminal failure and no `turn.failed`/`step.failed` events (parked runs pass) |-| `t.waiting()` | The run parked on HITL input (for approval-shaped evals) |-| `t.messageIncludes(token)` | Joined assistant text contains `token` (string or RegExp) |-| `t.outputEquals(value)` / `t.outputMatches(schema)` | Deep equality / Standard Schema (e.g. Zod) validation of the parsed output |-| `t.calledTool(name, opts?)` | A matching tool call happened (`input`, `output`, `isError`, `times` constraints) |-| `t.notCalledTool(name)` | No call to `name` |-| `t.toolOrder([...names])` | Tool names appear in order (other calls may interleave) |-| `t.usedNoTools()` | No tool calls at all |-| `t.maxToolCalls(n)` | At most `n` tool calls |-| `t.noFailedActions()` | No tool, subagent, or skill action reported a failure |-| `t.calledSubagent(name, opts?)` | A subagent delegation happened (`remoteUrl`, `output` constraints) |-| `t.event(predicate, label)` | Escape hatch: any predicate over the typed event stream |--`t.completed()` subsumes `t.didNotFail()` — reach for `completed` unless you specifically want to allow a parked run.+Run-level assertions read the whole run, so they take no value. They are methods on `t` and gate by default. Several key off whether a run **parked**: paused on an unanswered human-in-the-loop (HITL) input request, waiting for an approval or answer before it can continue.++| Assertion | Asserts |+| --------------------------------------------------- | --------------------------------------------------------------------------------------- |+| `t.completed()` | The run did not fail and did not park on unanswered HITL input |+| `t.didNotFail()` | No terminal failure and no `turn.failed`/`step.failed` events (parked runs pass) |+| `t.waiting()` | The run parked on HITL input (for approval-shaped evals) |+| `t.messageIncludes(token)` | Joined assistant text contains `token` (string or RegExp) |+| `t.outputEquals(value)` / `t.outputMatches(schema)` | Deep equality or Standard Schema (e.g. Zod) validation of the agent's structured output |+| `t.calledTool(name, opts?)` | A matching tool call happened (`input`, `output`, `isError`, `times` constraints) |+| `t.notCalledTool(name)` | No call to `name` |+| `t.toolOrder([...names])` | Tool names appear in order (other calls may interleave) |+| `t.usedNoTools()` | No tool calls at all |+| `t.maxToolCalls(n)` | At most `n` tool calls |+| `t.noFailedActions()` | No tool, subagent, or skill action reported a failure |+| `t.calledSubagent(name, opts?)` | A subagent delegation happened (`remoteUrl`, `output` constraints) |+| `t.event(predicate, label)` | Escape hatch: any predicate over the typed event stream |++`t.completed()` subsumes `t.didNotFail()`, so reach for `completed` unless you specifically want to allow a parked run. The structured output that `t.outputEquals` and `t.outputMatches` read is the agent's structured output (see the [output schema guide](../guides/client/output-schema)).```tsawait t.send("What is the weather in Brooklyn?");t.completed();t.calledTool("get_weather");-t.usedNoTools(); // mutually exclusive with the line above — pick the one you mean```+`t.calledTool` and `t.usedNoTools` are mutually exclusive; assert one or the other, never both in the same run.+## Value assertions with `t.check``t.check(value, assertion)` grades an explicit value against a builder from `eve/evals/expect`. The value can be `t.reply`, a turn's `.message`, parsed JSON, or any local you computed:@@ -54,11 +55,11 @@ t.check(t.reply, similarity("Sunny, 72F")); // fuzzy 0–1 Levenshtein (soft)| `matches(schema)` | validates against a Standard Schema | gate || `similarity(expected)` | normalized Levenshtein similarity, 1 = identical | soft |-Pick the cheapest builder that captures what "correct" means. When exact match is too strict but a judge model is overkill, `similarity` is the middle ground; for nuanced grading, reach for the [judge](./judge).+Pick the cheapest builder that captures what "correct" means. When exact match is too strict but a judge model is overkill, `similarity` is the middle ground. For nuanced grading, reach for the [judge](./judge).## The matcher mini-language-`t.calledTool` and `t.calledSubagent` take a matcher object — `{ input, output, isError, times }` for tools, `{ remoteUrl, output }` for subagents. Each field accepts a literal (objects partial-deep-match), a RegExp, or a function. A matcher function receives the value and returns either a boolean (acts as a predicate) or an expected value to compare against (handy for runner-assigned values like environment-provided URLs):+`t.calledTool` and `t.calledSubagent` take a matcher object: `{ input, output, isError, times }` for tools, `{ remoteUrl, output }` for subagents. Each field accepts a literal (objects partial-deep-match), a RegExp, or a function. A matcher function receives the value and returns either a boolean (acts as a predicate) or an expected value to compare against (handy for runner-assigned values like environment-provided URLs):```tst.calledTool("bash", { input: { command: /^pwd/ }, isError: false, times: 1 });@@ -73,9 +74,9 @@ t.calledSubagent("weather", {## Run state and derived facts-A turn that leaves the session open for a next message is the normal end state of a successful turn. Parking on unanswered HITL input is tracked separately — that is what `t.completed()` and `t.waiting()` key off.+Beyond the raw `t.events` stream, the runner derives typed facts the assertions read: tool calls (name, input, output, error state), subagent calls, and HITL input requests. A turn that leaves the session open for a next message is the normal end state of a successful turn; parking on unanswered HITL input is tracked separately, and that is what `t.completed()` and `t.waiting()` key off.-Beyond the raw `t.events` stream, the runner derives typed facts the assertions read: tool calls (name, input, output, error state), subagent calls, and HITL input requests. The built-in assertions cover almost everything; when you need to read the stream directly, `t.event(predicate, label)` is the escape hatch:+The built-in assertions cover almost everything. When you need to read the stream directly, `t.event(predicate, label)` is the escape hatch:```tst.event(@@ -87,11 +88,11 @@ t.event(## Severity-Every assertion returns a chainable handle. Severity rides on the assertion — there is no separate thresholds map to keep in sync.+Every assertion returns a chainable handle. Severity rides on the assertion, so there is no separate thresholds map to keep in sync.-- `.gate(threshold?)` — hard. A miss marks the eval `failed` and `eve eval` exits non-zero.-- `.soft(threshold?)` — tracked data. A below-threshold miss marks the eval `scored`, fatal only under `--strict`. With no threshold, it is tracked-only and never fails.-- `.atLeast(threshold)` — soft with a bar (equivalent to `.soft(threshold)`).+- `.gate(threshold?)` is hard. A miss marks the eval `failed` and `eve eval` exits non-zero.+- `.soft(threshold?)` is tracked data. A below-threshold miss marks the eval `scored`, fatal only under `--strict`. With no threshold, it is tracked-only and never fails.+- `.atLeast(threshold)` is soft with a bar (equivalent to `.soft(threshold)`).The defaults are chosen so you rarely set severity. Run-level methods and `includes`/`equals`/`matches` are gates; `similarity` and every `t.judge.*` assertion are soft. Annotate only when you deviate:diff --git a/docs/evals/cases.mdx b/docs/evals/cases.mdxindex 2844b2bc2..e58df528a 100644--- a/docs/evals/cases.mdx+++ b/docs/evals/cases.mdx@@ -3,11 +3,11 @@ title: "Cases"description: "Author single-turn and multi-turn evals with test(t), and fan one file out over a dataset."----Each eval file is one graded case. The runner executes its `test(t)` function against the target, captures every event, and computes a verdict from the [assertions](./assertions) you recorded. Every eval — single-turn, multi-turn, HITL, or dataset-driven — is the same shape: one `async test(t)` function that drives the agent and asserts inline.+Each eval file is one graded case by default, and a single file can fan out over a dataset by default-exporting an array (covered below). The runner executes each `test(t)` function against the target, captures every event, and computes a verdict from the [assertions](./assertions) you recorded. Every eval shares one shape, whether single-turn, multi-turn, human-in-the-loop (HITL), or dataset-driven: one `async test(t)` function that drives the agent and asserts inline.## Single-turn evals-The common case sends one turn and asserts on the reply. `t.send(input)` resolves once the turn settles; `t.reply` is the last assistant message:+The common case sends one turn and asserts on the reply. `t.send(input)` resolves once the turn settles, and `t.reply` is the last assistant message:```ts title="evals/weather/brooklyn-forecast.eval.ts"import { defineEval } from "eve/evals";@@ -22,7 +22,7 @@ export default defineEval({});```-Some evals only care about behavior, not text — assert on the run and skip the content check entirely:+Some evals only care about behavior, not text. Assert on the run and skip the content check entirely:```ts title="evals/weather/no-tools-for-greetings.eval.ts"import { defineEval } from "eve/evals";@@ -43,7 +43,7 @@ Identity is the file path, so directories are the grouping mechanism. `evals/wea```textevals/├── weather/-│ ├── shared.ts # helpers — not an eval+│ ├── shared.ts # helpers, not an eval│ ├── brooklyn-forecast.eval.ts│ └── no-tools-for-greetings.eval.ts└── smoke.eval.ts@@ -51,7 +51,7 @@ evals/## Multi-turn evals-Drive several turns in sequence — branching, HITL approvals, structured output, attachments, multiple sessions. Because assertions live in the function, an intermediate value is just a local variable: judge a draft before the next turn overwrites it, then keep going.+Drive several turns in sequence for branching, HITL approvals, structured output, attachments, or multiple sessions. Because assertions live in the function, an intermediate value is a local variable. Judge a draft before the next turn overwrites it, then keep going.```ts title="evals/draft-then-send.eval.ts"import { defineEval } from "eve/evals";@@ -69,7 +69,7 @@ export default defineEval({});```-Bespoke preconditions that no built-in assertion expresses are plain `throw`s — a thrown error marks the eval `failed` with the message in the result:+For a precondition no built-in assertion expresses, `throw`. A thrown error marks the eval `failed` with the message in the result:```ts title="evals/session-continuity.eval.ts"import { defineEval } from "eve/evals";@@ -96,22 +96,22 @@ export default defineEval({`t` drives the primary session; `t.newSession()` returns an independent `EveEvalSession` against the same target, whose events feed the same run-level assertions.-- `t.send(input)` sends a turn and waits for it to settle. It accepts the same input as `ClientSession.send()` — a string or a structured message — and resolves to a turn carrying `.message` and `.expectOk()`.+- `t.send(input)` sends a turn and waits for it to settle. It accepts the same input as `ClientSession.send()` (a string or a structured message) and resolves to a turn carrying `.message` and `.expectOk()`.- `t.sendFile(text, path, mediaType?)` attaches a local file as a data URL.- `t.expectInputRequests(filter?)` asserts the previous turn parked on HITL input and returns the pending requests.- `t.respond(...responses)` answers specific pending input requests and sends them as the next turn.- `t.respondAll(optionId)` answers every pending input request with the same option and sends the responses as the next turn.- `t.reply` is the last assistant message (or `null`); `t.sessionId` is the current session id; `t.events` is the full typed event stream captured so far.-Each `send` (and `respond`/`respondAll`) resolves to a turn whose `expectOk()` throws only when the turn ended failed — a session left open for a next message is the normal end state of a successful turn.+Each `send` (and `respond`/`respondAll`) resolves to a turn whose `expectOk()` throws only when the turn ended failed. A session left open for a next message is the normal end state of a successful turn.Events from every session are captured in the result and artifacts. `t.log(message)` records debug lines into the eval artifact; `--verbose` also streams them to stdout as evals run. `t.signal` is an `AbortSignal` that fires on timeout.-For driving sessions created outside the eval — by a channel webhook or a schedule — see [Targets](./targets).+For driving sessions created outside the eval, by a channel webhook or a schedule, see [Targets](./targets).## Datasets: exporting an array-To fan one file out over a dataset, default-export an array of `defineEval(...)` values. Eval modules are ESM, so top-level `await` can load anything. Ids derive from the file name plus a zero-padded index (`sql/0000`, `sql/0001`, …, in array order). The loaders (`loadJson`, `loadYaml` from `eve/evals/loaders`) parse fixture files relative to the app root:+To fan one file out over a dataset, default-export an array of `defineEval(...)` values. Eval modules are ESM, so top-level `await` can load anything. Ids derive from the file name plus a zero-padded index in array order (`sql/0000`, `sql/0001`, and so on). The loaders (`loadJson`, `loadYaml` from `eve/evals/loaders`) parse fixture files relative to the app root:```ts title="evals/sql.eval.ts"import { defineEval } from "eve/evals";diff --git a/docs/evals/judge.mdx b/docs/evals/judge.mdxindex 52addb7b4..e6e633206 100644--- a/docs/evals/judge.mdx+++ b/docs/evals/judge.mdx@@ -3,7 +3,7 @@ title: "Judge"description: "Grade evals with an LLM judge via t.judge.autoevals, set thresholds on the assertion, and configure the judge model."----When no deterministic [assertion](./assertions) captures what "good" means — factual correctness, summary quality, free-form criteria — grade the run with an LLM judge. The `t.judge.*` assertions are the only model-backed ones, and they use a judge model that is resolved separately from the agent under test: Eve only uses it for scoring, never to swap out the agent.+When no deterministic [assertion](./assertions) captures what "good" means (factual correctness, summary quality, free-form criteria), grade the run with an LLM judge. The `t.judge.*` assertions are the only model-backed ones, and they use a judge model that is resolved separately from the agent under test. Eve only uses it for scoring, never to swap out the agent.```tsimport { defineEval } from "eve/evals";@@ -19,7 +19,7 @@ export default defineEval({## The graders-The judges live under `t.judge.autoevals` — the namespace names the [Braintrust autoevals](https://github.com/braintrustdata/autoevals) grader family, so the factuality and closedQA semantics are autoevals', not Eve-invented. Each grades `t.reply` by default and is soft by default (tracked, no gate):+The judges live under `t.judge.autoevals`. The namespace names the [Braintrust autoevals](https://github.com/braintrustdata/autoevals) grader family, so the factuality and closedQA semantics are autoevals', not Eve-invented. Each grader scores `t.reply` by default and is soft by default (tracked, no gate):| Grader | Grades || ---------------------------------------- | -------------------------------------------------------------------------------------- |@@ -30,8 +30,8 @@ The judges live under `t.judge.autoevals` — the namespace names the [BraintrusThe reference or criteria is the positional argument. An options object follows:-- `on` — the value to grade, defaulting to `t.reply`. Pass an intermediate draft or parsed value to grade it instead.-- `model` / `modelOptions` — a per-call judge override (see below).+- `on` is the value to grade, defaulting to `t.reply`. Pass an intermediate draft or parsed value to grade it instead.+- `model` and `modelOptions` are a per-call judge override (see below).```tsconst draft = await t.send("Draft the welcome email.");@@ -40,11 +40,11 @@ t.judge.autoevals.closedQA("professional tone", { on: draft.message }).atLeast(0## Soft scoring and thresholds-Judge assertions are soft, so the threshold rides on the assertion handle — there is no separate thresholds map:+Judge assertions are soft, so the threshold rides on the assertion handle. There is no separate thresholds map:-- **No threshold** — tracked-only. The score lands in reports and artifacts and never fails the eval. Use it to watch a metric without gating on it.-- `.atLeast(threshold)` — a soft bar. A below-threshold score marks the eval `scored`, fatal only under `eve eval --strict`.-- `.gate(threshold)` — promote a judge to a hard gate that fails the eval outright.+- **No threshold** is tracked-only. The score lands in reports and artifacts and never fails the eval. Use it to watch a metric without gating on it.+- `.atLeast(threshold)` is a soft bar. A below-threshold score marks the eval `scored`, fatal only under `eve eval --strict`.+- `.gate(threshold)` promotes a judge to a hard gate that fails the eval outright.```tst.judge.autoevals.closedQA("cites a source"); // tracked, never fails@@ -58,9 +58,9 @@ A judge runs once per assertion and burns tokens, so reach for one only when notThe judge model is resolved once when the runner builds `t`. It is **never** the model under test. Three levels resolve innermost-wins:-1. **Per-call** — `t.judge.autoevals.closedQA("…", { model, modelOptions })`.-2. **Per-eval** — `defineEval({ judge: { model, modelOptions }, test })`.-3. **Project default** — `defineEvalConfig({ judge: { model, modelOptions } })` in `evals.config.ts`.+1. **Per-call**: `t.judge.autoevals.closedQA("…", { model, modelOptions })`.+2. **Per-eval**: `defineEval({ judge: { model, modelOptions }, test })`.+3. **Project default**: `defineEvalConfig({ judge: { model, modelOptions } })` in `evals.config.ts`.```ts title="evals/evals.config.ts"import { defineEvalConfig } from "eve/evals";@@ -78,14 +78,14 @@ export default defineEval({async test(t) {await t.send("Explain quantum tunneling to a 10-year-old.");t.judge.autoevals.factuality(reference).atLeast(0.7);- t.judge.autoevals.closedQA("is concise", { model: "anthropic/claude-haiku-4-5" }); // cheaper, per-call+ t.judge.autoevals.closedQA("is concise", { model: "anthropic/claude-haiku-4.5" }); // cheaper, per-call},});```-`judge` in `evals.config.ts` is optional — a tree of fully deterministic evals can omit it. But calling `t.judge.*` with no judge model resolved is a fail-fast error at eval definition time.+`judge` in `evals.config.ts` is optional, and a tree of fully deterministic evals can omit it. Calling `t.judge.*` with no judge model resolved records a failed gate: the runner scores the assertion after the `test` function runs, the missing model throws, and the eval fails with that message.-A **string model id** (e.g. `"anthropic/claude-opus-4.8"`) routes through the Vercel AI Gateway and needs `AI_GATEWAY_API_KEY` or `VERCEL_OIDC_TOKEN` in the environment; an **AI SDK `LanguageModel` instance** is used directly. With a model configured but no credentials, a judge-backed eval **skips visibly** like other real-model legs, so mock-model fixture runs stay green. For provider-specific judge settings, use `modelOptions.providerOptions`.+A **string model id** (e.g. `"anthropic/claude-opus-4.8"`) routes through the Vercel AI Gateway and needs `AI_GATEWAY_API_KEY` or `VERCEL_OIDC_TOKEN` in the environment. An **AI SDK `LanguageModel` instance** is used directly. With a model configured but no credentials, a judge-backed eval **skips visibly** rather than failing, so the run reports the skip instead of a spurious error. For provider-specific judge settings, use `modelOptions.providerOptions`.## What to read nextdiff --git a/docs/evals/overview.mdx b/docs/evals/overview.mdxindex de833b20d..88a86d005 100644--- a/docs/evals/overview.mdx+++ b/docs/evals/overview.mdx@@ -3,13 +3,13 @@ title: "Overview"description: "Define repeatable scored checks for an Eve agent with defineEval and run them with eve eval."----An eval is a scored check that runs your agent against real sessions and grades the result. Use it to catch regressions when you change a prompt or a tool: drive the agent through one or more turns, then assert on what it did — the run completed, the right tool ran, the reply contains the right text — and optionally ship the results to Braintrust.+An eval is a scored check that runs your agent against real sessions and grades the result, catching regressions when you change a prompt or a tool. Drive the agent through one or more turns, assert on what it did (the run completed, the right tool ran, the reply contains the right text), and optionally ship the results to Braintrust.-Evals exercise the same HTTP surface your users hit. The runner boots (or targets) a real agent server, drives sessions through the [TypeScript client](../guides/client/overview) protocol, and grades what comes back — so a passing eval means the agent actually booted, accepted a request, and produced the result you asserted.+Evals exercise the same HTTP surface your users hit. The runner boots (or targets) a real agent server, drives sessions through the [TypeScript client](../guides/client/overview) protocol, and grades what comes back, so a passing eval means the agent booted, accepted a request, and produced the result you asserted.## `defineEval`-Eve discovers evals under the app-root `evals/` directory, in `.eval.ts` files. Each file is exactly one eval — one graded case. The file path is the eval's identity, so you don't author an `id` or `name`; directories group related evals (`evals/weather/brooklyn-forecast.eval.ts` → id `weather/brooklyn-forecast`).+Eve discovers evals under the app-root `evals/` directory, in `.eval.ts` files. Each file is one eval by default. A file can also default-export an array to fan out over a dataset (see [Cases](./cases)). The file path is the eval's identity, so you don't author an `id` or `name`. Directories group related evals (`evals/weather/brooklyn-forecast.eval.ts` becomes id `weather/brooklyn-forecast`).```textmy-agent/@@ -40,7 +40,7 @@ export default defineEval({});```-`test` is the only required field. The rest are optional: `description`, `judge`, `tags`, `metadata`, `timeoutMs`, `reporters`. The init template adds `evals/**/*.ts` to `tsconfig.json`, so your eval code type-checks alongside the app.+`test` is the only required field. The rest are optional: `description`, `judge`, `tags`, `metadata`, `timeoutMs`, and `reporters`. The init template adds `evals/**/*.ts` to `tsconfig.json`, so your eval code type-checks alongside the app.## `evals.config.ts`@@ -56,11 +56,11 @@ export default defineEvalConfig({});```-Everything is optional. `judge` sets the default model for [LLM-as-judge](./judge) assertions (`t.judge.*`) — only evals that use them need it, so a tree of fully deterministic evals can omit it entirely. `reporters`, `maxConcurrency`, and `timeoutMs` round out the defaults. Config `reporters` observe every eval in the run — set one `Braintrust()` here instead of adding it to each eval. CLI flags (`--max-concurrency`, `--timeout`) and per-eval values take precedence over the config defaults.+Everything is optional. `judge` sets the default model for [LLM-as-judge](./judge) assertions (`t.judge.*`); a tree of fully deterministic evals can omit it. `reporters`, `maxConcurrency`, and `timeoutMs` round out the defaults. Config `reporters` observe every eval in the run, so set one `Braintrust()` here instead of adding it to each eval. CLI flags (`--max-concurrency`, `--timeout`) and per-eval values take precedence over the config defaults.## The `t` context-`t` is both the driver and the assertion surface. There are no separate `input`, `run`, `checks`, or `scores` fields — you write ordinary control flow, sending turns and asserting inline.+`t` is both the driver and the assertion surface. There are no separate `input`, `run`, `checks`, or `scores` fields. You write ordinary control flow, sending turns and asserting inline.- **Drive** the agent: `t.send(...)`, `t.respond(...)`, `t.respondAll(...)`, `t.sendFile(...)`, `t.expectInputRequests(...)`, `t.newSession()`. Read what came back with `t.reply` (the last assistant message), `t.sessionId`, and `t.events`. See [Cases](./cases).- **Assert** with three surfaces, covered next.@@ -69,16 +69,16 @@ Everything is optional. `judge` sets the default model for [LLM-as-judge](./judgEach surface matches a genuinely different kind of judgment:-- **Run-level methods** read the whole run — `t.completed()`, `t.calledTool("get_weather")`, `t.usedNoTools()`, `t.toolOrder([...])`. They take no value because they observe the run itself. See [Assertions](./assertions).-- **`t.check(value, assertion)`** grades an explicit value with a deterministic builder from `eve/evals/expect` — `t.check(t.reply, includes("sunny"))`. Grade `t.reply`, an intermediate draft, parsed JSON — anything. See [Assertions](./assertions).-- **`t.judge.autoevals.*`** is the LLM-as-judge surface — `t.judge.autoevals.closedQA("cites a source")`. It grades `t.reply` by default and uses the configured judge model, never the agent under test. See [Judge](./judge).+- **Run-level methods** read the whole run, like `t.completed()`, `t.calledTool("get_weather")`, `t.usedNoTools()`, and `t.toolOrder([...])`. They take no value because they observe the run itself. See [Assertions](./assertions).+- **`t.check(value, assertion)`** grades an explicit value with a deterministic builder from `eve/evals/expect`, such as `t.check(t.reply, includes("sunny"))`. Grade `t.reply`, an intermediate draft, parsed JSON, or anything else. See [Assertions](./assertions).+- **`t.judge.autoevals.*`** is the LLM-as-judge surface, like `t.judge.autoevals.closedQA("cites a source")`. It grades `t.reply` by default and uses the configured judge model, never the agent under test. See [Judge](./judge).## Gate vs soft-Every assertion returns a chainable handle, so severity rides on the assertion itself — there is no separate thresholds map:+Every assertion returns a chainable handle, so severity rides on the assertion itself. There is no separate thresholds map.- **Gates** are hard. A failed gate marks the eval `failed` and `eve eval` exits non-zero. Run-level methods, `includes`, `equals`, and `matches` are gates by default.-- **Soft** assertions are tracked data. They land in reports and artifacts, and a below-threshold soft assertion marks the eval `scored` — visible but not fatal, unless you pass `--strict`. `similarity` and every `t.judge.*` assertion are soft by default. A soft assertion with no threshold is tracked-only and never fails.+- **Soft** assertions are tracked data. They land in reports and artifacts, and a below-threshold soft assertion marks the eval `scored` (visible but not fatal, unless you pass `--strict`). `similarity` and every `t.judge.*` assertion are soft by default. A soft assertion with no threshold is tracked-only and never fails.Override per assertion: `.gate(threshold?)` promotes to a hard gate, `.soft(threshold?)` demotes to tracked, and `.atLeast(threshold)` is a soft assertion with a bar.@@ -89,7 +89,7 @@ t.judge.autoevals.closedQA("cites a source"); // soft, tracked (no threshold)t.judge.autoevals.factuality(reference).atLeast(0.7); // soft, gated under --strict at 0.7```-## Run it+## Run evals with eve eval```basheve eval # run all discovered evals against a local dev server@@ -101,7 +101,9 @@ Exit code `0` means every eval passed its gates. See [Running evals](./running)## A good baseline-Most apps do fine with a few small smoke evals. Assert behavior with `t.completed()` plus one or two content checks, keep dataset fixtures in `evals/data/`, and only reach for a judge or Braintrust once you actually need fuzzy grading or shared result review. In CI, run `eve eval --strict` so soft threshold misses fail the build too.+Most apps do fine with a few small smoke evals. Assert behavior with `t.completed()` plus one or two content checks, keep dataset fixtures in `evals/data/`, and reach for a judge or Braintrust only when you need fuzzy grading or shared result review. In CI, run `eve eval --strict` so soft threshold misses fail the build too.++## What to read nextThe rest of this section covers each piece:@@ -111,8 +113,4 @@ The rest of this section covers each piece:- [Targets](./targets): local vs remote targets for the same eval files- [Reporters](./reporters): Braintrust experiments and JUnit XML- [Running evals](./running): the `eve eval` CLI, exit codes, and artifacts--## What to read next--- [Cases](./cases): author your first evals- [Tools](../tools): the surface most evals assert ondiff --git a/docs/evals/reporters.mdx b/docs/evals/reporters.mdxindex 0ff07a05b..00de99c0c 100644--- a/docs/evals/reporters.mdx+++ b/docs/evals/reporters.mdx@@ -1,11 +1,11 @@---title: "Reporters"-description: "Ship eval results to Braintrust experiments or JUnit XML — Eve runs and scores everything itself."+description: "Ship eval results to Braintrust experiments or JUnit XML. Eve runs and scores everything itself."----Eve runs and grades everything itself; reporters just ship the results out. The CLI prints a console summary by default — one line per eval, failed assertions with their messages — and reporters from `eve/evals/reporters` add destinations on top.+Eve runs and grades everything itself; reporters ship the results out. The CLI prints a console summary by default (one line per eval, with failed assertions and their messages), and reporters from `eve/evals/reporters` add destinations on top.-Reporters attach in two places. Declare them in `evals.config.ts` to observe **every** eval in the run — the usual choice for a shared destination like one Braintrust experiment, so you don't repeat the reporter in each file. Or list them on an individual eval's `reporters` to scope a destination to that eval (or to a group of evals that share one instance).+Reporters attach in two places. Declare them in `evals.config.ts` to observe **every** eval in the run, the usual choice for a shared destination like one Braintrust experiment, so you don't repeat the reporter in each file. Or list them on an individual eval's `reporters` to scope a destination to that eval (or to a group of evals that share one instance).## Braintrust@@ -38,13 +38,13 @@ export default defineEval({The reporter config takes an optional `projectName` and `experimentName`, plus a base experiment (by name or id) to diff against. Gate assertions log as binary scores under a `gate:` prefix so experiments diff gate regressions the same way they diff soft-score regressions. Eval `metadata` rides along to reporters.-A reporter instance observes the evals that reference it: share one instance across several evals — the config, a `shared.ts` export, or every entry of a dataset array — and their results land in a single experiment. Listing the same config reporter on an eval too does not double-report it.+A reporter instance observes the evals that reference it. Share one instance across several evals (the config, a `shared.ts` export, or every entry of a dataset array) and their results land in a single experiment. Listing the same config reporter on an eval too does not double-report it.-Braintrust needs its SDK installed in the app and credentials in the environment. Pass `--skip-report` to run the eval without shipping results (this also suppresses config reporters) — useful locally when iterating.+Braintrust needs its SDK installed in the app and credentials in the environment: install the `braintrust` package (`npm install braintrust`) and set `BRAINTRUST_API_KEY`. Pass `--skip-report` to run the eval without shipping results, which also suppresses config reporters and is useful locally when iterating.## JUnit-`JUnit({ filePath })` writes JUnit XML for CI annotations. The `--junit <path>` CLI flag does the same thing without touching the eval file, which is usually the better fit — CI owns the output path, not the eval:+`JUnit({ filePath })` writes JUnit XML for CI annotations. The `--junit <path>` CLI flag does the same thing without touching the eval file, usually the better fit because CI owns the output path, not the eval:```basheve eval --strict --junit .eve/junit.xml@@ -54,7 +54,17 @@ Each eval becomes one `<testcase>` named by its path-derived id; failed gates an## Custom reporters-A reporter implements the `EvalReporter` interface from `eve/evals/reporters` and receives the same structured results the built-ins do. Reach for one only when a destination isn't covered — the per-run artifacts under `.eve/evals/` already capture everything for ad-hoc inspection.+A reporter implements the `EvalReporter` interface from `eve/evals/reporters` and receives the same structured results the built-ins do. The runner calls three lifecycle methods, each of which may return a promise for async work like a remote upload:++```ts+interface EvalReporter {+ onRunStart(evaluations: readonly EveEval[], target: EveEvalTarget): void | Promise<void>;+ onEvalComplete(result: EveEvalResult): void | Promise<void>;+ onRunComplete(summary: EveEvalRunSummary): void | Promise<void>;+}+```++`onRunStart` fires once before any eval runs, `onEvalComplete` fires after each observed eval with its checks, scores, and verdict, and `onRunComplete` fires once with the aggregated summary. Reach for a custom reporter only when a destination isn't covered. The per-run artifacts under `.eve/evals/` already capture everything for ad-hoc inspection.## What to read nextdiff --git a/docs/evals/running.mdx b/docs/evals/running.mdxindex c898c3a1c..1b1a28d1d 100644--- a/docs/evals/running.mdx+++ b/docs/evals/running.mdx@@ -15,7 +15,7 @@ eve eval --timeout 60000 # per-eval timeout in millisecondseve eval --max-concurrency 4 # cap concurrent eval executions (default 8)eve eval --junit .eve/junit.xml # write JUnit XMLeve eval --list # print discovered evals without running-eve eval --verbose # stream per-eval ctx.log lines to stdout+eve eval --verbose # stream per-eval t.log lines to stdouteve eval --json # machine-readable outputeve eval --skip-report # skip config and eval-defined reporters (e.g. Braintrust)```@@ -27,7 +27,7 @@ Positional ids match exactly or by directory prefix: `eve eval weather` runs `ev| Code | Means || ---- | ------------------------------------------------------------------------------- || `0` | Every eval passed its gates (and soft thresholds, under `--strict`) |-| `1` | Any eval failed — a failed gate, an execution error, or a strict threshold miss |+| `1` | Any eval failed (a failed gate, an execution error, or a strict threshold miss) || `2` | Configuration error |## Artifactsdiff --git a/docs/evals/targets.mdx b/docs/evals/targets.mdxindex 5a409e24b..a28a9577d 100644--- a/docs/evals/targets.mdx+++ b/docs/evals/targets.mdx@@ -3,7 +3,7 @@ title: "Targets"description: "Point evals at a local dev server or a deployment with the same eval files."----An eval target is always an HTTP URL. `eve eval` starts a local dev server, while `eve eval --url <url>` runs against an existing server or deployment — the same eval files work for both, which is what makes evals usable as end-to-end tests in CI.+An eval target is always an HTTP URL. `eve eval` starts a local dev server, while `eve eval --url <url>` runs against an existing server or deployment. The same eval files work for both, which is what makes evals usable as end-to-end tests in CI.The runner polls `/eve/v1/health`, verifies `/eve/v1/info`, and exposes the live target as `t.target` inside the `test` function.@@ -22,11 +22,22 @@ export default defineEval({});```-- `t.target.fetch(path, init)` performs an authenticated fetch against the target — useful for channel and webhook ingress.+- `t.target.fetch(path, init)` performs an authenticated fetch against the target, useful for channel and webhook ingress. See [Authentication](#authentication) for how the runner authenticates.- `t.target.dispatchSchedule(id)` triggers a [schedule](../schedules) through the dev-only schedule route and returns the session ids it created. It works only against a target with dev routes enabled (the local `eve eval` dev server, or a deployment running in development mode), and throws otherwise.-- `t.target.attachSession(sessionId, { startIndex? })` consumes one turn from a session created outside the eval — by a channel or a schedule — so its events feed the run-level assertions.+- `t.target.attachSession(sessionId, { startIndex? })` consumes one turn from a session created outside the eval, by a channel or a schedule, so its events feed the run-level assertions. `startIndex` skips events before that position, so a session already partway through its stream resumes from where you left off rather than replaying from the start.-Sessions attached this way are full `EveEvalSession`s: you can keep driving them with `send` and read their event streams. The run-level assertions on `t` (`t.completed()`, `t.calledTool(...)`) read the whole run, attached sessions included.+Sessions attached this way are full `EveEvalSession`s: you can keep driving them with `send` and read their event streams. The run-level assertions on `t` (`t.completed()`, `t.calledTool(...)`) read the whole run, including attached sessions.++## Authentication++Local targets send no auth: `eve eval` owns the dev server it boots. A remote `--url` target connects with the same credentials as every other development client, resolved in this order:++- A Vercel OIDC trusted-IDP token, sent as a per-request header. It bypasses Deployment Protection without a per-project secret, so a CI job with a pulled OIDC token reaches a protected preview deployment without extra setup.+- An `x-vercel-protection-bypass` header, added when `VERCEL_AUTOMATION_BYPASS_SECRET` is set.+- A bearer token resolved from the same OIDC cascade.+- `EVE_EVAL_AUTH_TOKEN`, which overrides the bearer with a static token for targets whose auth is not OIDC-based.++`t.target.fetch(path, init)` carries these same credentials, so channel and webhook ingress you exercise through it authenticates the same way the session protocol does.## What to read nextdiff --git a/docs/getting-started.mdx b/docs/getting-started.mdxindex 28b936e17..954622150 100644--- a/docs/getting-started.mdx+++ b/docs/getting-started.mdx@@ -3,30 +3,44 @@ title: "Getting Started"description: "Install Eve, scaffold your first agent, give it a tool, and run it locally."----Eve is a filesystem-first framework for durable agents: you write capabilities under `agent/`, and Eve runs the model loop, persists every session, and serves the agent over HTTP and platform channels. This guide gets a small app running locally and walks the current request loop end to end: build, run, message, stream, and follow up.+Eve is a filesystem-first framework for durable agents. You write capabilities under `agent/`, and Eve runs the model loop, persists every session, and serves the agent over HTTP and platform channels. You'll scaffold an app, add a tool, run it locally, then create, stream, and continue a session over HTTP.++## Prerequisites++- Node 24 or newer+- npm (bundled with Node)+- A model credential (see below)++The scaffold's default model is `anthropic/claude-sonnet-4.6`, which routes through the Vercel AI Gateway. Set one of these before you run the agent:++- A gateway model id needs `AI_GATEWAY_API_KEY`, or a `VERCEL_OIDC_TOKEN` pulled with `vercel link`.+- A direct provider id needs that provider's key, derived from the model prefix. For example, `anthropic/claude-...` needs `ANTHROPIC_API_KEY`.++If you skip this, the dev TUI flags the missing credential and its `/model` command walks you through pasting a key or linking a project.## Quick start-Run `eve init` with `npx` before Eve is installed locally:+`npx` runs `eve init` without installing Eve first:```bashnpx eve@latest init my-agent```-The command creates an npm-managed child directory, uses Eve's default model, installs dependencies, initializes Git, and starts the development server — the interactive [terminal UI](./guides/dev-tui) opens; type a message and watch the model loop run. Pass `--channel-web-nextjs` to add the Web Chat application; every app ships the built-in HTTP channel (`agent/channels/eve.ts`) regardless. Stop the server before editing the generated agent. The command does not create a Vercel project or deploy.+The command:-## Prerequisites+- Creates an npm-managed child directory and uses Eve's default model+- Installs dependencies and initializes Git+- Starts the development server and opens the interactive [terminal UI](./guides/dev-tui)-- Node `24.x`-- npm (bundled with Node)+Type a message and watch the model loop run. Pass `--channel-web-nextjs` to add the Web Chat application. Every app ships the built-in HTTP channel (`agent/channels/eve.ts`) regardless.-You also need a model credential. Set the provider or gateway key your model string requires (gateway ids like `anthropic/claude-opus-4.8` route through the Vercel AI Gateway), or link a Vercel project that supplies one.+`eve init` holds the terminal, so stop it with Ctrl+C to get your shell back before editing the generated agent. The command does not create a Vercel project or deploy.-## Manual installation+To add Eve to an existing project, run `eve init .` from a directory that already has a `package.json` and no `agent/` files yet. Eve adds the missing `eve`, `ai`, and `zod` dependencies without touching anything else the project owns. The Eve dependency and the Node engine come from the same release. Eve pins `engines.node` to the lowest major that release supports (for example `24.x`). It keeps an existing range only when every version that range allows stays within that major; otherwise it replaces the range and prints a warning.-The quick start uses `eve init` for a guided scaffold. Run `npx eve@latest init <name>` from a parent directory, or create an empty directory first and run `eve init`, `eve init .`, or `eve init ./` inside it to run the same full scaffold there, including `package.json`. To add Eve to a non-empty existing app, use `npx eve@latest init .`: that add-agent flow requires a `package.json` and no existing `agent/` files yet, and Eve adds the missing `eve`, `ai`, and `zod` dependencies for you. Eve also ensures a compatible Node engine (for example `24.x`) is present; if an existing range is too narrow for the release, Eve updates it and warns you. Either way the final handoff runs the `eve dev` binary through the package manager, not the project’s own `dev` script.+## Manual installation-To wire Eve in by hand, declare a compatible Node runtime in `package.json`:+To wire Eve into an existing app by hand instead of using `eve init`, first declare a compatible Node runtime in `package.json`:```json{@@ -36,10 +50,10 @@ To wire Eve in by hand, declare a compatible Node runtime in `package.json`:}```-Then install Eve and author the two files the runtime needs:+Then install the dependencies and author the two files the runtime needs. The `eve init` scaffold adds `ai` and `zod` for you; by hand you install all three:```bash-npm install eve@latest+npm install eve@latest ai zod```### Project files@@ -66,14 +80,13 @@ Even at this size the agent can already do real work. The default harness gives### Add your first tool-Whatever you name the file becomes the tool name the model sees. Create `agent/tools/get_weather.ts`:+The filename becomes the tool name the model sees, and it must be snake_case ASCII. Create `agent/tools/get_weather.ts`:```tsimport { defineTool } from "eve/tools";import { z } from "zod";-// The runtime tool name comes from the filename, so the model sees this as-// `get_weather`. Tool filenames must be snake_case ASCII.+// The model sees this tool as `get_weather`, from the filename.export default defineTool({description: "Get the current weather for a city.",inputSchema: z.object({ city: z.string().min(1) }),@@ -87,29 +100,35 @@ Tools run in your app runtime with full `process.env`, not inside the [sandbox](## Run the app-From the app root:+A scaffolded app has a `dev` script, so from the app root run:```bashnpm run dev```-Useful commands:+The manual path authors no `dev` script. Run the binary through `npx` instead:++```bash+npx eve dev+```++Other commands the eve binary provides (prefix each with `npx`, or add a matching package.json script):- `eve info`: show the active routes and compiled artifacts- `eve build`: compile the agent into `.eve/` and build the host output- `eve start`: serve the built output- `eve dev`: start the local runtime and open the interactive [terminal UI](./guides/dev-tui)-In the dev TUI, type a message and watch it happen in order: the `get_weather` call, its result, then the reply.+In the dev TUI, type a message and watch it happen in order. First the `get_weather` call, then its result, then the reply.-The same CLI can point at a deployment. `eve dev https://your-app.vercel.app` drives a deployed app, which is handy for preview and production smoke tests. See [Deployment](./guides/deployment).+The same CLI can point at a deployment. `npx eve dev https://your-app.vercel.app` drives a deployed app, which is handy for preview and production smoke tests. See [Deployment](./guides/deployment).## Send a messageEvery Eve app exposes the same stable HTTP API. Start a durable session:```bash-curl -X POST http://127.0.0.1:2000/eve/v1/session \+curl -X POST http://127.0.0.1:3000/eve/v1/session \-H 'content-type: application/json' \-d '{"message":"What is the weather in Brooklyn?"}'```@@ -124,35 +143,47 @@ The response comes back with two things you'll reuse:Attach to the session stream:```bash-curl http://127.0.0.1:2000/eve/v1/session/<sessionId>/stream+curl http://127.0.0.1:3000/eve/v1/session/<sessionId>/stream```-The stream is NDJSON, one lifecycle event per line. See [Sessions, runs & streaming](./concepts/sessions-runs-and-streaming) for the full list of events and what each one carries.+The stream is NDJSON, served as `application/x-ndjson; charset=utf-8`. For this run you'll see a handful of lifecycle events:++- `session.started`+- `actions.requested` (the `get_weather` call)+- `action.result`+- `message.completed` (the reply)+- `session.completed`++`reasoning.appended` and `message.appended` are optional live-streaming events. Clients that can't surface incremental output can ignore them and rely on `reasoning.completed` and `message.completed`.++The full set covers more lifecycle, human-in-the-loop, and authorization events, including `input.requested`, `turn.failed`, `authorization.required`, and `authorization.completed`. See [Sessions, runs and streaming](./concepts/sessions-runs-and-streaming) for every event and its data shape.## Send a follow-up messageWhen the session is waiting for the next user message, post a follow-up with the token:```bash-curl -X POST http://127.0.0.1:2000/eve/v1/session/<sessionId> \+curl -X POST http://127.0.0.1:3000/eve/v1/session/<sessionId> \-H 'content-type: application/json' \-d '{"continuationToken":"<token>","message":"Now do Queens."}'```-See [Sessions, runs & streaming](./concepts/sessions-runs-and-streaming) for the full contract.+See [Sessions, runs and streaming](./concepts/sessions-runs-and-streaming) for the full contract.## Setting up with a coding agentIf a coding agent (Claude Code, Cursor, and the like) is doing the setup, hand it this prompt:-<CopyPrompt text="Set up an Eve agent for the user. Ask one question at a time. Use your prompt tools when available and do not guess. First ask what the agent should do. Then ask whether to create a new project or add it to an existing directory. For a new project, propose a name and ask the user to confirm it, then ask whether it should include Web Chat. Run `npx eve@latest init <target>`, adding `--channel-web-nextjs` if the user wants Web Chat. After scaffolding, read the relevant guide in `<project>/node_modules/eve/docs/`, replace the placeholder in `<project>/agent/instructions.md` with the purpose the user gave you, and do not start `eve dev` because it is interactive. Give the user the exact dev command printed by init.">- Set up an Eve agent by asking what it should do, whether to create a new project, scaffold the- current empty directory, or add Eve to an existing app, and whether a new project should include Web Chat, one question at a time.- Run `npx eve@latest init <target>`, read the bundled docs, fill in agent/instructions.md, and give- the user the dev command instead of starting the interactive server.+<CopyPrompt text="Set up an Eve agent for the user. Eve is a filesystem-first TypeScript framework for durable agents, published as the npm package eve. Read its docs: once eve is installed they are bundled in the package at node_modules/eve/docs; before eve is installed, read the published Introduction and Getting Started pages. If the project has no Eve app, scaffold one with `npx eve@latest init <name>`; add `--channel-web-nextjs` only when the user wants Web Chat. The init command installs dependencies, initializes Git, and starts the dev server, so run it in a controllable process and stop it with Ctrl+C before editing. To add Eve to an existing app, run `eve init .`, or install the dependencies by hand with `npm install eve@latest ai zod` (init adds ai and zod; the by-hand path needs all three). Make sure agent/agent.ts and agent/instructions.md exist, then add a first typed tool at agent/tools/get_weather.ts using defineTool from eve/tools with a Zod inputSchema and an inline execute. Start the dev server again, then exercise the HTTP API: create a session with POST /eve/v1/session, attach to GET /eve/v1/session/:id/stream, and send a follow-up with the returned continuationToken. Verify with the project's typecheck, adapt model and provider choices to the project, and do not commit unless the user asks.">+ Set up an Eve agent: read the Eve docs (bundled at node_modules/eve/docs once eve is+ installed), scaffold with `npx eve@latest init <name>` (or `npm install eve@latest ai zod` in an existing app), add+ a typed tool at agent/tools/get_weather.ts, run it with `npm run dev`, then create a session, stream+ it, and send a follow-up.</CopyPrompt>-Once `eve` is installed, the complete docs ship at `node_modules/eve/docs/`, so the agent can read them locally instead of fetching anything.+Once `eve` is a dependency, the package bundles the full docs, so the agent can read them locally at `node_modules/eve/docs/` without fetching anything.++To add a platform channel after setup, run `eve channels add slack` from an interactive terminal. The init flags are covered in [Quick start](#quick-start).## What to read next@@ -160,5 +191,5 @@ Once `eve` is installed, the complete docs ship at `node_modules/eve/docs/`, so- [Channels](./channels/overview): reach the agent from Slack, Discord, or a web UI- [Frontend](./guides/frontend/overview): browser chat with `useEveAgent`- [TypeScript SDK](./guides/client/overview): call the agent from scripts or server-side code-- [Sessions, runs & streaming](./concepts/sessions-runs-and-streaming): the durable session model+- [Sessions, runs and streaming](./concepts/sessions-runs-and-streaming): the durable session model- [Build an agent](./tutorial/first-agent): the full end-to-end walkthroughdiff --git a/docs/guides/auth-and-route-protection.md b/docs/guides/auth-and-route-protection.mdindex 94ae1c389..804a5282c 100644--- a/docs/guides/auth-and-route-protection.md+++ b/docs/guides/auth-and-route-protection.md@@ -3,16 +3,16 @@ title: "Auth & Route Protection"description: "Secure your agent's HTTP routes with an ordered auth walk, verifier helpers, and connection OAuth via Vercel Connect."----Eve has two separate auth concerns, and this page covers both:+Eve has two independent auth systems:-- **Route auth** (inbound): who is allowed to reach your agent's HTTP routes. It runs at the channel layer.-- **Tool and connection auth** (outbound): how your agent signs in to an external service it calls, like an OAuth MCP server.+- **Route auth** (inbound) decides who can reach your agent's HTTP routes. It runs at the channel layer, gating the request before any model work runs.+- **Tool and connection auth** (outbound) is how your agent signs in to an external service it calls, like an OAuth MCP server. It happens later, when a tool or connection actually reaches out.-They are independent. Route auth gates the request before any model work runs; tool and connection auth happens later, when a tool or connection actually reaches out. Start with route auth.+Start with route auth.## Route auth-Route auth runs at the channel layer. The policy lives on the HTTP channel factory (`agent/channels/eve.ts`) and guards three routes:+The route-auth policy lives on the HTTP channel factory (`agent/channels/eve.ts`) and guards three routes:- `POST /eve/v1/session`- `POST /eve/v1/session/:sessionId`@@ -64,7 +64,7 @@ export default eveChannel({Put your own providers ahead of the catch-all helpers. Any entry that doesn't recognize the caller returns `null`, and the walk moves on.-Want a precise status instead of a skip? Throw:+To reject with a precise status instead of skipping, throw:```tsimport { ForbiddenError, UnauthenticatedError } from "eve/channels/auth";@@ -76,7 +76,7 @@ throw new UnauthenticatedError({throw new ForbiddenError({ message: "Not allowed on this workspace." }); // 403```-Any other thrown error follows the normal channel failure path. Building a custom channel on `defineChannel`? Call `routeAuth(request, auth)` from `eve/channels/auth` to reuse the same walk semantics.+Any other thrown error follows the normal channel failure path. When building a custom channel on `defineChannel`, call `routeAuth(request, auth)` from `eve/channels/auth` to reuse the same walk semantics.## Verifier helpers@@ -106,7 +106,7 @@ Auth fails closed: routes reject unauthenticated traffic by default, and the OID#### `subjects` patterns and `vercelSubject(...)`-Each `subjects` entry is matched against the token's `sub` claim, which Vercel shapes as `owner:<team>:project:<name>:environment:<env>`. Hand-writing that string is a footgun: a typo silently rejects every caller, and an over-broad `*` wildcard silently lets unrelated ones in. Build the pattern with `vercelSubject(...)` instead. It rejects malformed input at construction time and forces an explicit `environment` (defaulting to `"production"`):+Each `subjects` entry is matched against the token's `sub` claim, which Vercel shapes as `owner:<team>:project:<name>:environment:<env>`. Hand-writing that string is a footgun: a typo silently rejects every caller, and an over-broad `*` wildcard silently lets unrelated ones in. Build the pattern with `vercelSubject(...)` instead. It rejects malformed input at construction time, and defaults `environment` to `"production"` when you omit it, so an unspecified environment cannot silently accept preview or development tokens:```tsimport { vercelOidc, vercelSubject } from "eve/channels/auth";@@ -205,14 +205,14 @@ Inside runtime code, `ctx.session.auth` carries the result of the channel's rout- `auth.current`: the caller on the active inbound turn.- `auth.initiator`: the caller that started the durable session.-- A follow-up message updates `auth.current` but leaves `auth.initiator` alone. So when a different caller follows up on the same session, `auth.current` tracks the new caller for that turn while `auth.initiator` stays pinned to whoever started it.+- A follow-up message updates `auth.current` but leaves `auth.initiator` alone. When a different caller follows up on the same session, `auth.current` tracks the new caller for that turn while `auth.initiator` stays pinned to whoever started it.- Both are `null` only on internal runtime paths (subagents, for instance) that never went through an authored route. HTTP traffic always populates `auth.current`, since the walk either accepts with a `SessionAuthContext` or returns `401`.-Use the principal on `auth.current` (or `auth.initiator`) to scope tools, resolve [dynamic capabilities](./dynamic-capabilities) per principal, or enforce tenant boundaries. There's no second per-session ownership ACL stacked on top of route auth: access is decided at the HTTP boundary, and the durable session just carries the caller snapshot forward into your runtime code.+Use the principal on `auth.current` (or `auth.initiator`) to scope tools, resolve [dynamic capabilities](./dynamic-capabilities) per principal, or enforce tenant boundaries. There's no second per-session ownership ACL stacked on top of route auth. Access is decided at the HTTP boundary, and the durable session carries the caller snapshot forward into your runtime code.## Tool and connection auth-Route auth decides who reaches your agent. Tool and connection auth is the flip side: how your agent reaches an external service that wants an interactive sign-in, like an OAuth MCP server. Both a connection and an individual tool can declare an `auth` strategy; Eve drives the sign-in, caches the token per step, and re-runs the call once the caller authorizes.+Tool and connection auth is how your agent reaches an external service that wants an interactive sign-in, like an OAuth MCP server. Both a connection and an individual tool can declare an `auth` strategy; Eve drives the sign-in, caches the token per step, and re-runs the call once the caller authorizes.### On a connection@@ -263,7 +263,7 @@ Declaring `auth` adds two accessors to the tool's `ctx`:Throw `ConnectionAuthorizationRequiredError` anywhere in `execute` (directly, via `requireAuth()`, or implicitly from `getToken()`) and you trigger the consent flow, keyed by the tool's name. Calling either accessor on a tool that does not declare `auth` throws.-By default the sign-in affordance title-cases the tool's path-derived name — a tool file named `sfdc_lookup.ts` renders "Sign in with Sfdc_lookup". Set `displayName` on the `auth` definition to control what users see instead: `auth: { ...connect("sfdc"), displayName: "Salesforce" }`. It is presentation-only; the tool's name still keys the authorization scope, token cache, and callback URL, and a definition-level `displayName` wins over one the strategy stamps on the challenge.+By default the sign-in affordance title-cases the tool's path-derived name, so a tool file named `sfdc_lookup.ts` renders "Sign in with Sfdc_lookup". Set `displayName` on the `auth` definition to control what users see instead, for example `auth: { ...connect("sfdc"), displayName: "Salesforce" }`. It is presentation-only. The tool's name still keys the authorization scope, token cache, and callback URL, and a definition-level `displayName` wins over one the strategy stamps on the challenge.## What to read nextdiff --git a/docs/guides/client/continuations.mdx b/docs/guides/client/continuations.mdxindex 9d0dd5352..a41509755 100644--- a/docs/guides/client/continuations.mdx+++ b/docs/guides/client/continuations.mdx@@ -3,12 +3,12 @@ title: "Continuations"description: "Persist and resume Eve client sessions with continuation tokens, session IDs, and stream cursors."----Eve hands back two different handles, and mixing them up is the most common mistake. The TypeScript client tracks both for you:+Every Eve client turn returns two handles, and mixing them up is a common mistake. The TypeScript client tracks both for you:- `continuationToken`: the resume handle. Use it to send the next user turn.- `sessionId`: the stream-and-inspect handle. Use it to attach to event history.-`ClientSession` also tracks `streamIndex`, the count of events already consumed. Together those fields make a `SessionState`.+`ClientSession` also tracks `streamIndex`, the count of events already consumed. Together these three fields make a `SessionState`.## Read and persist state@@ -75,7 +75,7 @@ if (result.status === "completed") {}```-This matches the runtime contract: only waiting sessions can accept the next user input.+This matches the runtime contract, where only waiting sessions can accept the next user input.## Multiple sessions@@ -99,7 +99,7 @@ The shared `Client` only owns host, auth, headers, and reconnect settings. Conve## Reconnect an existing stream-If a session already has a `sessionId`, `stream()` attaches to that stream from the saved cursor:+When a session already has a `sessionId`, `session.stream()` reattaches to its stream from the saved cursor. Resuming a saved `SessionState` after a restart is the common reason to do this:```tsconst session = client.session(savedState);@@ -109,15 +109,7 @@ for await (const event of session.stream()) {}```-Override the cursor when you want to replay from an earlier point:--```ts-for await (const event of session.stream({ startIndex: 0 })) {- console.log(event.type);-}-```--`stream()` is for attaching to an existing run. To send new user input, use `send()`.+`stream()` attaches to an existing run; to send new user input, use `send()`. For overriding the cursor with `startIndex` and the full reconnection model, see [Streaming](./streaming#open-a-stream-manually).## What to read nextdiff --git a/docs/guides/client/messages.mdx b/docs/guides/client/messages.mdxindex f946c5672..a6990e9dd 100644--- a/docs/guides/client/messages.mdx+++ b/docs/guides/client/messages.mdx@@ -12,7 +12,7 @@ Pass a string to `send()` for plain text:```tsimport { Client } from "eve/client";-const client = new Client({ host: "http://127.0.0.1:2000" });+const client = new Client({ host: "http://127.0.0.1:3000" });const session = client.session();const response = await session.send("What is the weather in Brooklyn?");@@ -34,7 +34,7 @@ console.log(result.status, result.message);| `sessionId` | Session ID for streaming and inspection. || `data` | Structured output when the turn requested an [output schema](./output-schema). |-Failed runtime turns don't throw just because the stream includes `session.failed`. They return `status: "failed"`. Transport and route errors throw `ClientError`.+When the stream includes `session.failed`, the turn returns `status: "failed"` rather than throwing. Transport and route errors throw `ClientError`.## Send a full turn payloaddiff --git a/docs/guides/client/output-schema.mdx b/docs/guides/client/output-schema.mdxindex 34c55a951..0a6f8d660 100644--- a/docs/guides/client/output-schema.mdx+++ b/docs/guides/client/output-schema.mdx@@ -3,7 +3,7 @@ title: "Output Schema"description: "Request structured results from Eve client turns and read typed data from MessageResult."----Pass `outputSchema` on a client turn when the caller needs structured data instead of only assistant text. The runtime makes the model satisfy the schema before the turn settles and emits the final payload as `result.completed`.+Pass `outputSchema` on a client turn when the caller needs structured data instead of only assistant text. The runtime makes the model satisfy the schema before the turn settles, then emits the final payload as `result.completed`.## JSON Schema@@ -26,7 +26,7 @@ const outputSchema = {required: ["title", "count"],} as const;-const client = new Client({ host: "http://127.0.0.1:2000" });+const client = new Client({ host: "http://127.0.0.1:3000" });const session = client.session();const response = await session.send<Summary>({diff --git a/docs/guides/client/overview.mdx b/docs/guides/client/overview.mdxindex 63db84248..c92a274a7 100644--- a/docs/guides/client/overview.mdx+++ b/docs/guides/client/overview.mdx@@ -1,9 +1,9 @@----title: "Overview"+title: "TypeScript SDK Overview"description: "Call an Eve agent from TypeScript with Client, sessions, auth, and health checks."----The `eve/client` entrypoint is the typed client for Eve's default HTTP API. Use it from scripts, server-to-server integrations, tests, evals, backend jobs, or custom UIs that want the session protocol without hand-writing the POST and NDJSON stream loop.+The `eve/client` entrypoint is the typed client for Eve's default HTTP API. Use it from scripts, server-to-server integrations, tests, evals, backend jobs, or custom UIs that want the session protocol without hand-writing the POST and NDJSON (newline-delimited JSON) stream loop.For browser chat UIs, start with [`useEveAgent`](../frontend/overview). For wire-level details, read [Sessions, runs & streaming](../../concepts/sessions-runs-and-streaming). The client sits between those two: lower level than the frontend hooks, higher level than raw HTTP.@@ -15,11 +15,11 @@ A `Client` binds one host, auth policy, header policy, and stream reconnection bimport { Client } from "eve/client";const client = new Client({- host: "http://127.0.0.1:2000",+ host: "http://127.0.0.1:3000",});```-`host` is the origin where the Eve routes are mounted. In a same-origin browser integration this is often `""`, but scripts and backend services usually name the full URL.+`host` is the origin where the Eve routes are mounted. In a same-origin browser integration this is often `""`; scripts and backend services usually name the full URL.## Check healthdiff --git a/docs/guides/client/streaming.mdx b/docs/guides/client/streaming.mdxindex e64525b38..97a2062a8 100644--- a/docs/guides/client/streaming.mdx+++ b/docs/guides/client/streaming.mdx@@ -3,7 +3,7 @@ title: "Streaming"description: "Consume Eve client stream events live, reconnect by event index, and aggregate turn results."----Every send starts with a POST and then reads the session's NDJSON event stream. `MessageResponse` gives you two ways to consume that stream: aggregate it with `result()` or iterate it live.+Every `ClientSession.send()` call posts the turn, then reads the session's NDJSON (newline-delimited JSON) event stream. `MessageResponse` gives you two ways to consume that stream, aggregating it with `result()` or iterating it live.## Aggregate a turn@@ -42,7 +42,7 @@ for await (const event of response) {}```-`message.appended` and `reasoning.appended` are incremental events. The completed forms, `message.completed` and `reasoning.completed`, are the compatibility path for clients that don't render deltas.+`message.appended` and `reasoning.appended` are incremental delta events. Their completed forms, `message.completed` and `reasoning.completed`, are the compatibility path for clients that don't render deltas.## Handle event types@@ -117,21 +117,22 @@ for await (const event of session.stream({ startIndex: 0 })) {## Abort a request-Pass an `AbortSignal` to cancel the POST or stream:+Pass an `AbortSignal` to cancel the POST or stream. Arm the timeout before awaiting `send()` so it covers the POST as well as the stream:```tsconst controller = new AbortController();+const timeout = setTimeout(() => controller.abort(), 10_000);const response = await session.send({message: "Run a long analysis.",signal: controller.signal,});-setTimeout(() => controller.abort(), 10_000);-for await (const event of response) {console.log(event.type);}++clearTimeout(timeout);```Once a response is aborted, create a new send for the next turn. Don't reuse the same `MessageResponse`.diff --git a/docs/guides/deployment.md b/docs/guides/deployment.mdindex f5ae42814..7e76a579a 100644--- a/docs/guides/deployment.md+++ b/docs/guides/deployment.md@@ -1,9 +1,9 @@---title: "Deployment"-description: "A production checklist for shipping an Eve agent on Vercel: build output, env/secrets, sandbox backend, prewarm, auth, deploy, and verify."+description: "A production checklist for shipping an Eve agent on Vercel, covering build output, env and secrets, sandbox backend, prewarm, auth, deploy, and verify."----You've got an agent running under `eve dev` and now you want it live. Eve runs the same way locally and on Vercel, so the move to production is mostly mechanical. Work through this checklist in order.+Eve runs the same way locally and on Vercel, so taking an agent from `eve dev` to production is mostly mechanical. Work through this checklist in order.## 1. Build@@ -13,16 +13,16 @@ You've got an agent running under `eve dev` and now you want it live. Eve runs teve build```-On hosted Vercel builds you get the Vercel output bundle under `.vercel/output`. You also get Eve's compiled framework artifacts under `.eve/`: the discovery manifest, compiled manifest, diagnostics, and module map. Crack those open to see exactly which authored surface a deployment will load. For the artifact guide and what to do when `eve build` fails, see [instrumentation.ts](./instrumentation).+When `VERCEL` is set (every hosted Vercel build sets it), `eve build` writes the Vercel output bundle under `.vercel/output`. A plain local `eve build` skips that bundle. Either way you get Eve's compiled framework artifacts under `.eve/`, including the discovery manifest, compiled manifest, diagnostics, and module map. Open those to see which authored surface a deployment will load. For the artifact guide and what to do when `eve build` fails, see [Observability](./instrumentation).-## 2. Environment variables & secrets+## 2. Environment variables and secretsSet these in your Vercel project's environment variables, never in source or compiled artifacts:-- **A model credential.** Easiest is the Vercel AI Gateway: link a Vercel project and gateway model ids like `anthropic/claude-opus-4.8` authenticate through Vercel OIDC, with no provider keys to manage. To call a provider directly instead, set its key (for example `OPENAI_API_KEY`).-- **Route-auth secrets**, for example `ROUTE_AUTH_BASIC_PASSWORD` and any JWT/OIDC signing keys referenced by your channel's `auth` (see [Auth & route protection](./auth-and-route-protection)).+- **A model credential.** The lowest-setup option is the Vercel AI Gateway. Link a Vercel project, and gateway model ids like `anthropic/claude-opus-4.8` authenticate through Vercel OIDC, with no provider keys to manage. To call a provider directly instead, set its key (for example `OPENAI_API_KEY`).+- **Route-auth secrets**, for example `ROUTE_AUTH_BASIC_PASSWORD` and any JWT/OIDC signing keys referenced by your channel's `auth` (see [Auth and route protection](./auth-and-route-protection)).-Route-auth secrets never get serialized into the compiled discovery or module-map artifacts. The runtime re-materializes them from the authored channel definition instead. One caveat: if your deployment sits behind Vercel preview protection and you want to drive it with `eve dev`, set `VERCEL_AUTOMATION_BYPASS_SECRET` locally before launching.+Route-auth secrets are never serialized into the compiled discovery or module-map artifacts. The runtime re-materializes them from the authored channel definition instead. If your deployment sits behind Vercel preview protection and you want to drive it with `eve dev`, set `VERCEL_AUTOMATION_BYPASS_SECRET` locally before launching.## 3. Sandbox backend@@ -41,7 +41,7 @@ Leave `backend` off and Eve falls back to `defaultBackend()`, which picks the Ve## 4. Build-time sandbox prewarm-During hosted builds, Eve prewarms reusable Vercel sandbox templates so the first session doesn't eat the cold-start cost. A few things worth knowing:+During hosted builds, Eve prewarms reusable Vercel sandbox templates so the first session doesn't pay the cold-start cost:- Prewarm runs only when both `VERCEL` and `VERCEL_DEPLOYMENT_ID` are present.- A sandbox with no `bootstrap()` and no workspace seed files gets skipped.@@ -53,7 +53,7 @@ During hosted builds, Eve prewarms reusable Vercel sandbox templates so the firs## 5. Auth-Swap any scaffolded `placeholderAuth()` for your real policy before the first production browser request hits the app. Both the framework default and the placeholder reject production browser traffic, so an unconfigured app fails closed rather than serving open routes. See [Auth & route protection](./auth-and-route-protection) for the full walk and the fail-closed guarantee.+Swap any scaffolded `placeholderAuth()` for your real policy before the first production browser request hits the app. Both the framework default and the placeholder reject production browser traffic, so an unconfigured app fails closed rather than serving open routes. See [Auth and route protection](./auth-and-route-protection) for the ordered auth walk and the fail-closed guarantee.## 6. Deploy on Vercel@@ -65,10 +65,6 @@ vercel deployThe deployed app serves the same stable health, session, and stream routes you've been hitting locally.-## How Eve sits behind a host framework--You can deploy an Eve app on its own, or mount it inside a host web framework that owns the rest of the site (marketing pages, a dashboard, other API routes). The host keeps its own routing and serves Eve's routes through the framework integration. For mounting Eve in Next.js (`withEve`) and the other supported frameworks, see [Frontend](./frontend/nextjs). Either way, the agent surface and HTTP contract are identical.-## 7. Verify the deploymentSmoke-test the live routes. Health first:@@ -85,13 +81,13 @@ curl -X POST https://<your-app>/eve/v1/session \-d '{"message":"Hello from production"}'```-Attach to the returned stream:+The POST returns a JSON body whose `sessionId` identifies the new session. Attach to that session's stream with it:```bashcurl https://<your-app>/eve/v1/session/<sessionId>/stream```-Or poke at the deployment interactively with the dev TUI, which is handy for preview and production smoke tests:+Or drive the deployment interactively with the dev TUI, which is handy for preview and production smoke tests:```basheve dev https://<your-app>@@ -103,20 +99,26 @@ eve dev https://<your-app>Once the agent is deployed, the platform auto-detects `eve` as the framework and surfaces an **Agent Runs** tab under your project's **Observability** view in the Vercel dashboard. From there you can browse sessions and drill into each conversation's trace.-> The Agent Runs tab is currently gated: your Vercel team needs the feature enabled before it appears. If you don't see it, reach out to your Vercel contact to get your team enabled.+> The Agent Runs tab is currently gated. Your Vercel team needs the feature enabled before it appears. If you don't see it, reach out to your Vercel contact to get your team enabled.++Agent Runs is separate from the OpenTelemetry exporters configured in [Observability](./instrumentation). Those still work and are the recommended path if you want spans in Braintrust, Datadog, or another third-party backend.++## How Eve sits behind a host framework-Agent Runs is separate from the OpenTelemetry exporters configured in [`instrumentation.ts`](./instrumentation). Those still work and are the recommended path if you want spans in Braintrust, Datadog, or another third-party backend.+You can deploy an Eve app on its own, or mount it inside a host web framework that owns the rest of the site (marketing pages, a dashboard, other API routes). The host keeps its own routing and serves Eve's routes through the framework integration. Either way, the agent surface and HTTP contract are identical. For mounting Eve in Next.js (`withEve`) and the other supported frameworks, see [Frontend](./frontend/nextjs).## Checklist-- [ ] `eve build` succeeds and writes `.vercel/output`.+- [ ] `eve build` succeeds, and writes `.vercel/output` when `VERCEL` is set.- [ ] Provider keys and route-auth secrets are set in Vercel env vars.- [ ] The sandbox backend matches the environment (`vercel()` or `defaultBackend()`).- [ ] Build-time prewarm reused or built templates without failing.- [ ] `placeholderAuth()` is replaced with your real policy.+- [ ] `vercel deploy` succeeds.+- [ ] The health, session, and stream routes respond on the deployment URL.## What to read next-- [Auth & route protection](./auth-and-route-protection): secure the routes you deployed-- [instrumentation.ts](./instrumentation): tracing, run tags, and the error catalog+- [Auth and route protection](./auth-and-route-protection): secure the routes you deployed+- [Observability](./instrumentation): tracing, run tags, and common failures- [Sandbox](../sandbox): backends, lifecycle, and credential brokeringdiff --git a/docs/guides/dev-tui.md b/docs/guides/dev-tui.mdindex b15b6229b..44bc580f0 100644--- a/docs/guides/dev-tui.md+++ b/docs/guides/dev-tui.md@@ -1,44 +1,116 @@---title: "Dev TUI"-description: "Drive an Eve agent locally in an interactive terminal UI: chat, stream, approve tools, answer questions, tune the display, and point it at a deployment."+description: "Drive an Eve agent locally in an interactive terminal UI. Chat, stream, approve tools, answer questions, tune the display, and point it at a deployment."----`eve dev` boots the local runtime and drops you into an interactive terminal UI. You chat with the agent, watch it stream, approve its tool calls, and answer the questions it asks back:+`eve dev` boots the local runtime and drops you into an interactive terminal UI. You chat with the agent, watch it stream, approve its tool calls, and answer the questions it asks back.```basheve dev```-On startup the TUI prints a brand line with your agent's name, plus a rotating tip (local sessions only):+On startup the TUI prints a brand line with your agent's name, plus a rotating tip (local sessions only).```texteve weather-agentUse /channels to add more ways to reach your agent.```-If agent discovery reported problems, an error/warning count renders between the two lines. Instructions, tools, skills, and subagents are one `eve info` away, and `/help` lists every command.+If agent discovery reported problems, an error and warning count renders between the two lines. Instructions, tools, skills, and subagents are one `eve info` away, and `/help` lists every command. The TUI also runs a startup check. A missing model-provider setup surfaces as an attention line (`⚠ 1 setup issue: model provider not linked · /model`) so the fix is visible before the first message fails, with each command's outcome hanging under it on a `⎿` connector.-From there the conversation streams straight into your terminal's normal scrollback — your prompts, the agent's replies, reasoning, tool calls, nested subagents, connection-authorization prompts, and any captured `stdout`, `stderr`, or sandbox lifecycle lines — so you keep native scrolling, copy/paste, and a transcript that persists after you exit. Each turn is rendered without boxes: a colored gutter glyph marks who's speaking, tool calls collapse to a one-line summary (`✓ get_weather city="SF" → 73°F`), and a subagent's work is indented beneath its `◆` header. A sticky footer keeps you oriented. When input is ready, the prompt stays bare until you type; while a turn or setup action owns the terminal, only its live status is shown. Beneath the prompt or status, a persistent line shows the model, the session's token flow (`↑ 394.4K ↓ 4.3K`), the linked Vercel project and team (`▲ my-agent (acme)`), and a yellow `/deploy pending` marker once a channel added this session still needs `/deploy`. The Vercel segment stays hidden until the directory is linked. Press `Enter` to send; `Ctrl+C` interrupts a running turn or quits at the prompt. Slash commands: `/new` starts a fresh session and `/exit` quits.+## Reading the transcript-When `eve dev` runs the server locally, five more slash commands manage the project without leaving the session. `/vc` installs the Vercel CLI (a global install with your package manager) when it is missing — the fix command the "Vercel CLI not found" diagnostic points at. `/login` signs in to Vercel through the CLI's browser flow: the panel waits while you authenticate in the browser and Cancel stops waiting. These are the prerequisites the others route to — a logged-out `/model` link, `/channels` Slack provisioning, and `/deploy` all point you at `/login` (or `/vc` when the CLI itself is absent) instead of failing with a raw error, and a `403` from a team that enforces SSO routes to `/login` too (re-authenticating completes the team's SSO). Bare `/model` opens a configure menu that loops until Done (or Esc). "Change model" runs the same searchable model picker setup uses (the AI Gateway catalog, pre-selected on the model the runtime is serving); a model change is written into your agent's authored source, and the command reports success only after Eve confirms the new id (`/model <provider/model-id>` applies one directly, skipping the menu). The provider row opens the provider questions: which model provider to use (picking something other than AI Gateway shows wiring instructions for your own provider and stops there, leaving any existing setup untouched) and how to connect to AI Gateway — paste your own `AI_GATEWAY_API_KEY`, saved straight to `.env.local`, or connect via a project, which asks for a Vercel team and then opens that team's existing-project list (picking again re-links) before pulling the project's environment so an AI Gateway credential lands in `.env.local`; the dev server reloads env files automatically, no restart needed. The row demands attention (a bold yellow "Configure provider" with "Required to enable the agent") until a link or gateway credential is detected, then names the connection (e.g. "AI Gateway (Linked to my-project in my-team)") after, and each action's latest outcome stays visible beneath the menu (e.g. "✓ Model changed to openai/gpt-5.5"). `/channels` shows the agent's channel list — already-registered channels render as checked, focusable rows with an "Already installed" hint — and adds the one you pick, including the Slack Connect provisioning, then installs the dependencies the scaffold added so the dev server can load the new channels right away; after each addition the list repaints with the channel checked, until Done (or Esc) leaves the flow. `/deploy` ships the agent to Vercel production, linking first when the directory is unlinked. Each command echoes as an invocation line, asks through a bordered panel that takes the input area's place — one question at a time, clearly separate from the chat transcript — and finishes with a one-line `⎿` result; loading states stay on the ephemeral status line instead of piling into the transcript. These commands are not available when connected to a remote server with `--url`, and when a turn fails because AI Gateway authentication is missing or stale, the error points you at `/model` directly. The TUI also checks at startup: a missing model-provider setup surfaces as an attention line — `⚠ 1 setup issue: model provider not linked · /model` — so the fix is visible before the first message fails, and a logged-out Vercel session surfaces the same way as `⚠ 1 setup issue: not logged in · /login` (or `Vercel CLI not found · /vc` when the CLI itself is absent). Each command's outcome hangs under it with the `⎿` connector.+The conversation streams straight into your terminal's normal scrollback, so you keep native scrolling, copy and paste, and a transcript that persists after you exit. The scrollback holds your prompts, the agent's replies, reasoning, tool calls, nested subagents, connection-authorization prompts, and any captured `stdout`, `stderr`, or sandbox lifecycle lines.-In the AI Gateway connection picker, "Connect via a project" is disabled when the Vercel CLI is missing, the CLI session is logged out, or Vercel cannot be reached. The disabled reason points to `/vc`, `/login`, or the network problem, while "Use my own key" remains available.+Each turn renders without boxes. A colored gutter glyph marks who is speaking, tool calls collapse to a one-line summary (`✓ get_weather city="SF" → 73°F`), and a subagent's work is indented beneath its `◆` header. When input is ready, the prompt stays bare until you type. While a turn or setup action owns the terminal, only its live status shows.-The prompt input behaves like a shell line editor: `↑`/`↓` cycle through the messages you've sent this session, `←`/`→`, Home/End, and `Ctrl+A`/`Ctrl+E` move the caret, and `Ctrl+U`/`Ctrl+K`/`Ctrl+W` kill the line, the rest of the line, or the previous word. If a turn fails terminally — the server session dies or the connection drops — the TUI starts a fresh session and notes it inline so you can keep going (server-side context resets with the old session). Errors render compactly, with docs links highlighted, and a code bug escaping your agent's own code shows its stack trace dim beneath the error headline. Captured server `stdout`/`stderr` renders as dim, indented log runs behind a `│` rule — consecutive lines from the same source share one label — while sandbox lifecycle lines use their own label. Dev-server rebuilds condense further, into one status row that updates in place: `tui/setup-panel.ts changed · rebuilding…`, then `· rebuilt`. Only the latest rebuild shows, and paths shrink to their last two components. By default, `eve dev` shows `stderr` and keeps stdout and sandbox lines buffered but hidden. `/loglevel <all|stderr|sandbox|none>` switches what the transcript shows retroactively, and `--logs` sets the starting mode. Bare `/loglevel` reports the current mode. At the idle prompt, `Ctrl+L` cycles `none → all → stderr → sandbox → none` and briefly shows the selected mode in the status line; `Ctrl+R` redraws.+A persistent line beneath the prompt or status shows the model, the session's token flow (`↑ 394.4K ↓ 4.3K`), the linked Vercel project and team (`▲ my-agent (acme)`), and a yellow `/deploy pending` marker once a channel added this session still needs `/deploy`. The Vercel segment stays hidden until the directory is linked.-The agent will sometimes need something from you, and the TUI asks inline. Tool approvals are a `y`/`n`. Option questions let you pick with `↑`/`↓` and `Enter`, or you can type a freeform answer. If a tool needs an authorized [connection](../connections), the URL shows up right in the transcript, and the turn picks back up once you've finished the flow.+Errors render compactly with docs links highlighted. A code bug escaping your agent's own code shows its stack trace dim beneath the error headline. Dev-server rebuilds condense into one status row that updates in place (`tui/setup-panel.ts changed · rebuilding…`, then `· rebuilt`); only the latest rebuild shows, and paths shrink to their last two components.-Density flags accept `full` / `collapsed` / `auto-collapsed` / `hidden`:+## Slash commands++Each command echoes as an invocation line, asks through a bordered panel that takes the input area's place (one question at a time, separate from the chat transcript), and finishes with a one-line `⎿` result. Loading states stay on the ephemeral status line instead of piling into the transcript.++| Command | Does |+| ----------- | --------------------------------------------------------------------------------------------------------------------------------- |+| `/model` | Opens a configure menu that loops until Done (or Esc). See [Configure the model and provider](#configure-the-model-and-provider). |+| `/channels` | Shows the agent's channel list and adds the one you pick. See [Add a channel](#add-a-channel). |+| `/deploy` | Ships the agent to Vercel production, linking the directory first when it is unlinked. |+| `/loglevel` | Switches which logs the transcript shows. See [Control what logs show](#control-what-logs-show). |+| `/new` | Starts a fresh session. |+| `/exit` | Quits the TUI. |+| `/help` | Lists every command. |++`/model`, `/channels`, and `/deploy` manage the project and are available only when `eve dev` runs the server locally, not when connected to a remote server with `--url`.++### Configure the model and provider++Bare `/model` opens the configure menu. "Change model" runs the same searchable model picker setup uses (the Vercel AI Gateway catalog, pre-selected on the model the runtime is serving). A model change is written into your agent's authored source, and the command reports success only after Eve confirms the new id. `/model <provider/model-id>` applies one directly, skipping the menu.++The provider row opens the provider questions: which model provider to use, and how to connect. Picking something other than Vercel AI Gateway shows wiring instructions for your own provider and stops there, leaving any existing setup untouched. For Vercel AI Gateway, you either paste your own `AI_GATEWAY_API_KEY` (saved straight to `.env.local`) or connect via a project. Connecting via a project asks for a Vercel team, opens that team's existing-project list (picking again re-links), then pulls the project's environment so an AI Gateway credential lands in `.env.local`. The dev server reloads env files automatically, with no restart needed.++The provider row demands attention (a bold yellow "Configure provider" with "Required to enable the agent") until a link or gateway credential is detected, then names the connection afterward (for example "AI Gateway (Linked to my-project in my-team)"). Each action's latest outcome stays visible beneath the menu (for example "✓ Model changed to openai/gpt-5.5"). When a turn fails because AI Gateway authentication is missing or stale, the error points you at `/model` directly.++### Add a channel++`/channels` shows the agent's channel list. Already-registered channels render as checked, focusable rows with an "Already installed" hint. Picking one adds it (including the Slack Connect provisioning), then installs the dependencies the scaffold added so the dev server can load the new channels right away. After each addition the list repaints with the channel checked, until Done (or Esc) leaves the flow.++## Keyboard shortcuts++The prompt input behaves like a shell line editor.++| Key | Action |+| ---------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |+| `Enter` | Send the message. |+| `Ctrl+C` | Interrupt a running turn, or quit at the prompt. |+| `↑` / `↓` | Cycle through the messages you have sent this session. |+| `←` / `→`, `Home` / `End`, `Ctrl+A` / `Ctrl+E` | Move the caret. |+| `Ctrl+U` / `Ctrl+K` / `Ctrl+W` | Kill the whole line, the rest of the line, or the previous word. |+| `Ctrl+L` | Cycle the log display mode (`none → all → stderr → sandbox → none`) and briefly show the mode in the status line. |+| `Ctrl+R` | Redraw the screen. |++If a turn fails terminally (the server session dies or the connection drops), the TUI starts a fresh session and notes it inline so you can keep going. Server-side context resets with the old session.++## Answer the agent inline++When the agent needs something from you, the TUI asks inline.++- Tool approvals are a `y` or `n`.+- Option questions let you pick with `↑` / `↓` and `Enter`, or you can type a freeform answer.+- If a tool needs an authorized [connection](../connections), the URL shows up right in the transcript, and the turn picks back up once you finish the flow.++## Control what logs show++By default, `eve dev` shows `stderr` and keeps stdout and sandbox lines buffered but hidden. Captured server `stdout` and `stderr` render as dim, indented log runs behind a `│` rule (consecutive lines from the same source share one label), while sandbox lifecycle lines use their own label.++- `/loglevel <all|stderr|sandbox|none>` switches what the transcript shows, retroactively. Bare `/loglevel` reports the current mode.+- `--logs <all|stderr|sandbox|none>` sets the starting mode at launch (default `stderr`).+- `Ctrl+L` at the idle prompt cycles `none → all → stderr → sandbox → none`.++## Display flags++Density flags control how much of each section renders. They accept `full`, `collapsed`, `auto-collapsed`, or `hidden`.```basheve dev --tools full --assistant-response-stats tokens --context-size 200000```-Other useful flags: `--subagents`, `--reasoning`, `--logs <all|stderr|sandbox|none>`, `--host`/`--port`, and `--no-ui` (headless, also the automatic fallback when stdout isn't a TTY).+| Flag | Values | Effect |+| ----------------------------------- | -------------------------------------------------- | ------------------------------------------------------- |+| `--tools <mode>` | `full` / `collapsed` / `auto-collapsed` / `hidden` | How tool calls render (default `auto-collapsed`). |+| `--reasoning <mode>` | `full` / `collapsed` / `auto-collapsed` / `hidden` | How reasoning renders (default `full`). |+| `--subagents <mode>` | `full` / `collapsed` / `auto-collapsed` / `hidden` | How subagent sections render. |+| `--connection-auth <mode>` | `full` / `collapsed` / `auto-collapsed` / `hidden` | How connection authorization renders. |+| `--assistant-response-stats <mode>` | `tokens` / `tokensPerSecond` | Which statistic the assistant header shows. |+| `--context-size <tokens>` | a token count | Model context window size, shown as a usage percentage. |+| `--logs <mode>` | `all` / `stderr` / `sandbox` / `none` | Which server and agent logs to show (default `stderr`). |++Connection flags: `--host` and `--port` bind the local server, and `--no-ui` runs headless (also the automatic fallback when stdout is not a TTY). See the [CLI](../reference/cli) for the full flag list.## Remote: `eve dev <url>`-Pass a URL and the TUI talks to a running deployment instead of spinning up a local server. That's handy for a Vercel preview or your production app:+Pass a URL and the TUI talks to a running deployment instead of starting a local server, which is handy for a Vercel preview or your production app.```basheve dev https://<your-app>@@ -48,5 +120,5 @@ The bare URL is shorthand for `--url`. `--host`, `--port`, and `--no-ui` are ign## What to read next-- [instrumentation.ts](./instrumentation): OpenTelemetry, hooks, and the error catalog.+- [Observability](./instrumentation): OpenTelemetry, run tags, and common failures.- [CLI](../reference/cli): every command and flag.diff --git a/docs/guides/dynamic-capabilities.md b/docs/guides/dynamic-capabilities.mdindex 07b141e7b..c85013ddf 100644--- a/docs/guides/dynamic-capabilities.md+++ b/docs/guides/dynamic-capabilities.md@@ -3,13 +3,13 @@ title: "Dynamic Capabilities"description: "Resolve tools, skills, and instructions at runtime with defineDynamic: the resolver events, execution order, and how dynamic tools survive step boundaries."----Sometimes you can't name a tool until the session starts. `defineDynamic` resolves capabilities from a session event at runtime rather than declaring them up front, which is what you want when the right tools, skills, or instructions hinge on who the caller is, what tenant they belong to, feature flags, or external data. The [tools](../tools), [skills](../skills), and [instructions](../instructions) guides each point here for their dynamic form.+`defineDynamic` resolves tools, skills, and instructions at runtime from a session event instead of declaring them up front. Reach for it when the right capabilities aren't known until the session starts, because they hinge on who the caller is, what tenant they belong to, feature flags, or external data. The [tools](../tools), [skills](../skills), and [instructions](../instructions) guides each point here for their dynamic form.## Dynamic toolsPass `defineDynamic` an `events` object whose handlers return either a single `defineTool(...)`, a `Record<string, defineTool(...)>`, or `null` for no tools. Wrap every entry in `defineTool()`. The wrapper stamps them so their `execute` functions survive workflow step boundaries.-The example below builds one tool per warehouse table. A map return names tools `slug__key`, so the model sees `query__orders`, `query__users`, and so on:+The example below builds one tool per warehouse table. A map return names tools `slug__key`, so the model sees `query__orders`, `query__users`, and so on.```ts title="agent/tools/query.ts"import { defineDynamic, defineTool } from "eve/tools";@@ -33,6 +33,10 @@ export default defineDynamic({});```+### `execute` must be an inline function++Write `execute` as an inline function expression, arrow, or method shorthand placed directly as the property value. The bundler transform does not detect `execute: myFn` or `execute: makeFn()`, so those tools work on the first step but do not survive replay (re-running a step after a crash or resume; see [Execution model & durability](../concepts/execution-model-and-durability)). On later steps the transform reconstructs each `execute` from its stored closure variables instead of re-running the resolver, which is why it has to be inline.+### Naming| Return shape | File | Tool name(s) |@@ -51,33 +55,45 @@ A single return produces one tool named after the file slug, identical to a stat| `turn.started` | Once per turn | Every model call in the turn || `step.started` | Before each model call | That model call |-**Limitation.** `execute` must be an inline function (function expression, arrow, or method shorthand written directly as the property value). `execute: myFn` or `execute: makeFn()` is not detected by the transform, so the tool works on the first step but won't survive replay.-### Execution order-When a stream event fires, three things happen in order: the channel adapter handler runs and the event is written to the durable stream, then stream-event [hooks](./hooks) fire, then dynamic tool resolvers subscribed to that event run and update the tool set. The tool loop reads the current set right before each model call, so a mid-turn update is visible on the next call.+When a stream event fires, three things happen in order.++1. The channel adapter handler runs and the event is written to the durable stream.+2. Stream-event [hooks](./hooks) fire.+3. Dynamic tool resolvers subscribed to that event run and update the tool set.++The tool loop reads the current set right before each model call, so a mid-turn update is visible on the next call.A single file can declare handlers for several events, and the most recently fired one owns that file's tool set. Re-resolve on `turn.started` to replace what `session.started` returned:```ts title="agent/tools/catalog.ts"+import { defineDynamic, defineTool } from "eve/tools";+import { z } from "zod";+import { runReadOnly, searchCatalog } from "../lib/catalog.js";+export default defineDynamic({events: {"session.started": async (_event, ctx) => ({query: defineTool({- /* ... */+ description: "Run a read-only query.",+ inputSchema: z.object({ sql: z.string() }),+ execute: ({ sql }) => runReadOnly(sql),}),}),// On each turn, re-resolve. Replaces this file's session.started tools for later calls."turn.started": async (_event, ctx) => ({search: defineTool({- /* ... */+ description: "Search the catalog.",+ inputSchema: z.object({ term: z.string() }),+ execute: ({ term }) => searchCatalog(term),}),}),},});```-Resolvers across files run concurrently. On later steps the bundler transform reconstructs each `execute` from its stored closure variables instead of re-running the resolver, which is why `execute` has to be inline.+Resolvers across files run concurrently.## Dynamic skillsdiff --git a/docs/guides/dynamic-workflows.md b/docs/guides/dynamic-workflows.mdindex 3cc95386c..cbfc9de1e 100644--- a/docs/guides/dynamic-workflows.md+++ b/docs/guides/dynamic-workflows.md@@ -3,11 +3,11 @@ title: "Dynamic Workflows"description: "The experimental Workflow tool: let the model orchestrate its own subagents from model-authored JavaScript as one durable step."----The experimental `Workflow` tool lets the model write JavaScript that coordinates the agent's own subagents as a single durable step: running them in sequence, feeding one result into the next, fanning out over a list, and combining the results. You flip on the capability; the model decides and runs the orchestration. Think of it as the agents-only slice of code mode.+The experimental `Workflow` tool lets the model write JavaScript that coordinates the agent's own subagents as a single durable step. The program can run them in sequence, feed one result into the next, fan out over a list, and combine the results. You enable the capability and the model decides and runs the orchestration. It is the agents-only slice of [code mode](../agent-config#other-defineagent-fields) (the broader `codeMode` flag that routes all of an agent's tools through model-authored JavaScript).-A single turn can already call several subagents, and parallel tool calls dispatch concurrently. What a workflow adds is _programmatic_ coordination: how many subagents to run based on an earlier result, which output feeds which call, and how to combine everything. That's logic the model can't express as a few one-off calls.+A single turn can already call several subagents, and parallel tool calls dispatch concurrently. What a workflow adds is _programmatic_ coordination. The program decides how many subagents to run based on an earlier result, which output feeds which call, and how to combine everything. That is logic the model cannot express as a few one-off calls.-## Enable it+## Enable the Workflow toolRe-export the opt-in marker as the default export of `agent/tools/workflow.ts`. The marker name carries the "experimental" warning, but the tool the model actually sees is named `Workflow`.@@ -26,27 +26,46 @@ export default defineAgent({});```-Ask for a "weekly business review": the model map-reduces `analyst` over the metrics it picks (width decided at runtime) and resumes if a child parks for approval.+When asked for a weekly business review, the model picks the metrics, runs one `analyst` per metric in parallel, and combines the findings. The program below is the kind of JavaScript the model authors. It fans `analyst` out over a runtime-decided list of metrics and merges the results:-## What it can orchestrate+```js+const metrics = ["revenue", "signups", "churn"];+const findings = await Promise.all(+ metrics.map((metric) => tools.analyst({ message: `Summarize last week's ${metric}.` })),+);+return findings.join("\n\n");+```++Each `tools.analyst(...)` call dispatches a child subagent, so the parent stream records one `subagent.called` per metric and one `subagent.completed` as each finishes:++```json+{ "type": "subagent.called", "data": { "name": "analyst", "toolName": "analyst", "callId": "call_1", "childSessionId": "ses_a1", "sequence": 0 } }+{ "type": "subagent.called", "data": { "name": "analyst", "toolName": "analyst", "callId": "call_2", "childSessionId": "ses_a2", "sequence": 1 } }+{ "type": "subagent.called", "data": { "name": "analyst", "toolName": "analyst", "callId": "call_3", "childSessionId": "ses_a3", "sequence": 2 } }+{ "type": "subagent.completed", "data": { "subagentName": "analyst", "callId": "call_1", "output": "..." } }+{ "type": "subagent.completed", "data": { "subagentName": "analyst", "callId": "call_2", "output": "..." } }+{ "type": "subagent.completed", "data": { "subagentName": "analyst", "callId": "call_3", "output": "..." } }+```++## What a workflow can orchestrate-A workflow reaches only this agent's own agents: the built-in `agent` (a copy of itself), declared [subagents](../subagents), and [remote agents](./remote-agents). That's the whole list. No files, network, shell, skills, or connections. It's a coordination layer over subagents, not a place to do other work. Each call can still request structured output via `outputSchema`, exactly like a direct subagent delegation.+A workflow reaches only this agent's own agents: the built-in `agent` (a copy of itself), declared [subagents](../subagents), and [remote agents](./remote-agents). That is the whole list. No files, network, shell, skills, or connections. A workflow is a coordination layer over subagents, not a place to do other work. Each call can still request structured output via `outputSchema`, exactly like a direct subagent delegation.## Where the JavaScript runs-The orchestration code never touches the agent's process. The runtime hands the program text to a small isolated JavaScript engine (a QuickJS sandbox) and runs it there. Nothing from the host realm crosses in: no `process`, no `globalThis` from the agent, no `import`/`require`. The program can reach exactly two things, the agent functions bridged in as `tools.<name>` and the ordinary language built-ins.+The orchestration code never touches the agent's process. The runtime hands the program text to a small isolated JavaScript engine (a QuickJS sandbox) and runs it there. Nothing from the host realm crosses in, so there is no `process`, no `globalThis` from the agent, and no `import`/`require`. The program can reach exactly two things, the agent functions bridged in as `tools.<name>` and the ordinary language built-ins.-That's an allowlist, not a denylist. The sandbox can't read files, open a socket, or see an environment variable because those simply aren't present, not because each one is blocked in turn. When the program calls an agent function, that call bridges back out to the runtime, which dispatches it just like a direct delegation. The orchestration glue stays inside the sandbox.+That is an allowlist, not a denylist. The sandbox cannot read files, open a socket, or see an environment variable because those are not present, not because each one is blocked in turn. When the program calls an agent function, that call bridges back out to the runtime, which dispatches it exactly like a direct delegation. The orchestration glue stays inside the sandbox.-## How it behaves+## Durability, approvals, and observability-- **Durable.** The whole orchestration counts as one step. Subagents dispatched together run concurrently, and if a run parks on a long-running or human-gated child, it resumes where it left off after a restart.-- **HITL-safe.** A subagent that needs approval mid-run surfaces its request to the user, and the workflow picks back up once that's answered, same as direct delegation.+- **Durable.** The whole orchestration counts as one step. Subagents dispatched together run concurrently, and if a run parks (suspends durably without holding compute; see [Execution model & durability](../concepts/execution-model-and-durability)) on a long-running or human-gated child, it resumes where it left off after a restart.+- **Approval-safe.** A subagent that needs human approval (HITL, human-in-the-loop) mid-run surfaces its request to the user, and the workflow picks back up once that is answered, same as direct delegation.- **Observable.** Every orchestrated subagent emits the usual `subagent.called` / `subagent.completed` events on the parent stream and gets its own child session and stream. The telemetry matches direct delegation, so existing dashboards and cost attribution keep working.## Relationship to code mode-Code mode is the broader version: the model drives _all_ of an agent's tools (files, shell, web, and agents) from JavaScript. A workflow carves out the agents-only slice, just the subagents. The two don't interfere. Enabling the `Workflow` tool leaves code mode untouched, and an agent can run both at once.+[Code mode](../agent-config#other-defineagent-fields) is the broader version, where the model drives _all_ of an agent's tools (files, shell, web, and agents) from JavaScript. A workflow covers only the subagents. The two do not interfere. Enabling the `Workflow` tool leaves code mode untouched, and an agent can run both at once.## What to read nextdiff --git a/docs/guides/frontend/nextjs.mdx b/docs/guides/frontend/nextjs.mdxindex f47da8dbb..b89d6e0cf 100644--- a/docs/guides/frontend/nextjs.mdx+++ b/docs/guides/frontend/nextjs.mdx@@ -3,7 +3,13 @@ title: "Next.js"description: "Run an Eve agent and a Next.js app as one project with withEve."----`eve/next` lets you ship a Next.js frontend and an Eve agent as a single project. Wrap your config with `withEve()` and the two run together: one dev server, one Vercel deploy. [`useEveAgent`](./overview) finds the mounted routes on its own, so there's no CORS to fight and no URL env vars to keep in sync.+`eve/next` ships a Next.js frontend and an Eve agent as a single project. Wrap your config with `withEve()` to run both from one dev server and one Vercel deploy. [`useEveAgent`](./overview) finds the mounted routes on its own, so there's no CORS to configure and no URL env vars to keep in sync.++## Prerequisites++- The `eve` package installed in your project (`npm install eve@latest`).+- An existing Eve agent directory. If you don't have one, start from [Getting started](../../getting-started).+- A Next.js app to mount the agent in.## Wrap the Next.js config@@ -16,7 +22,7 @@ const nextConfig: NextConfig = {};export default withEve(nextConfig);```-By default `withEve()` looks for an `agent/` folder next to your Next.js project root. If the agent lives somewhere else, point at it with `eveRoot`:+By default `withEve()` looks for an `agent/` folder inside your Next.js project root. If the agent lives somewhere else, point at it with `eveRoot`:```tsexport default withEve(nextConfig, {@@ -28,15 +34,15 @@ export default withEve(nextConfig, {All fields are optional.-| Option | Type | Default | Purpose |-| ----------------------- | --------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `eveRoot` | `string` | Next.js app root | Path to the Eve app root, relative to `process.cwd()` unless absolute. Set it when the agent lives outside the Next.js project. |-| `eveBuildCommand` | `string` | `"eve build"` | Build command for the generated Eve Vercel service. Use it when the Eve service needs project-specific prework, without changing the Next.js build. |-| `configureVercelOutput` | `boolean` | `true` | Set to `false` to skip creating or updating `.vercel/output/config.json`. By default `withEve` writes the `experimentalServices` entries for both apps. |-| `servicePrefix` | `string` | `"/_eve_internal/eve"` | Private Vercel route namespace for the Eve service. Must match the Eve service's mount in your Vercel Build Output config when you set it manually. |-| `devServerTimeoutMs` | `number` | `180000` | Maximum time to wait for the Eve development server to become available. |+| Option | Type | Default | Purpose |+| ----------------------- | --------- | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |+| `eveRoot` | `string` | Next.js app root | Path to the Eve app root, relative to `process.cwd()` unless absolute. Set it when the agent lives outside the Next.js project. |+| `eveBuildCommand` | `string` | `"eve build"` | Build command for the generated Eve Vercel service. Use it when the Eve service needs project-specific prework, without changing the Next.js build. |+| `configureVercelOutput` | `boolean` | `true` | When `true`, `withEve` writes the `experimentalServices` entries for both apps to `.vercel/output/config.json`. Set to `false` to skip that step. |+| `servicePrefix` | `string` | `"/_eve_internal/eve"` | Private Vercel route namespace for the Eve service. Must match the Eve service's mount in your Vercel Build Output config when you set it manually. |+| `devServerTimeoutMs` | `number` | `180000` | Maximum time to wait for the Eve development server to become available. |-For unusually slow cold starts, increase the development timeout:+For slow cold starts, increase the development timeout:```tsexport default withEve(nextConfig, {@@ -46,7 +52,7 @@ export default withEve(nextConfig, {## Call the hook-With `withEve()` in `next.config.ts`, the Eve routes are same-origin, so client code can call [`useEveAgent`](./overview) without naming a host. Cookie-based auth just works, whether that's Auth.js or any session cookie, since the browser already sends those cookies on every Eve request. For non-cookie schemes, attach the credentials yourself:+With `withEve()` in `next.config.ts`, the Eve routes are same-origin, so client code can call [`useEveAgent`](./overview) without naming a host. Cookie-based auth (Auth.js or any session cookie) needs no extra wiring, since the browser already sends those cookies on every Eve request. For non-cookie schemes, attach the credentials yourself:```tsxconst agent = useEveAgent({@@ -56,7 +62,16 @@ const agent = useEveAgent({});```-Before deploying a user-facing app, add `agent/channels/eve.ts` so production requests run your app's auth policy. See [Channels](../../channels/overview) and [Auth & route protection](../auth-and-route-protection).+The default Eve channel is fail-closed. With no `agent/channels/eve.ts` authored, Eve registers `eveChannel({ auth: [localDev(), vercelOidc()] })`: `localDev()` opens the routes on localhost, `vercelOidc()` admits Vercel OIDC callers in production, and everything else gets a `401`. To run your app's own auth policy, add `agent/channels/eve.ts`:++```ts title="agent/channels/eve.ts"+import { eveChannel } from "eve/channels/eve";+import { localDev, vercelOidc } from "eve/channels/auth";++export default eveChannel({ auth: [localDev(), vercelOidc()] });+```++For a public demo, use `none()` (also from `eve/channels/auth`) to skip authentication. See [Channels](../../channels/overview) and [Auth & route protection](../auth-and-route-protection).## Dev vs deploy topology@@ -69,13 +84,13 @@ Before deploying a user-facing app, add `agent/channels/eve.ts` so production re});```-- **Local production build.** `next build && next start` proxies Eve routes to `http://127.0.0.1:4274`. Change the port with `EVE_NEXT_PRODUCTION_PORT`:+- **Local production build.** `next build && next start` serves the Eve runtime from its built `.output/server/index.mjs` on a stable local port (`4274`) and proxies the Eve routes to it. Run `eve build` first so that output exists. Change the port with `EVE_NEXT_PRODUCTION_PORT`:```bashEVE_NEXT_PRODUCTION_PORT=5000 npm run build && npm start```-- **Non-Vercel hosts.** If the Eve service lives on a separate origin, tell Next.js where to find it with `EVE_NEXT_PRODUCTION_ORIGIN`:+- **Non-Vercel hosts.** When the Eve service lives on a separate origin, tell Next.js where to find it with `EVE_NEXT_PRODUCTION_ORIGIN`:```bashEVE_NEXT_PRODUCTION_ORIGIN=https://agent.example.com npm run builddiff --git a/docs/guides/frontend/nuxt.mdx b/docs/guides/frontend/nuxt.mdxindex 1db7908fb..0bd04e427 100644--- a/docs/guides/frontend/nuxt.mdx+++ b/docs/guides/frontend/nuxt.mdx@@ -3,7 +3,13 @@ title: "Nuxt"description: "Run an Eve agent and a Nuxt app as one project with the eve/nuxt module."----The `eve/nuxt` module folds a Nuxt frontend and an Eve agent into a single project: one dev server, one Vercel deploy. The auto-imported [`useEveAgent`](./use-eve-agent-vue) composable finds the mounted routes on its own, so you skip the usual CORS headaches and URL env vars.+The `eve/nuxt` module runs a Nuxt frontend and an Eve agent as a single project from one dev server and one Vercel deploy. The auto-imported [`useEveAgent`](./use-eve-agent-vue) composable finds the mounted routes on its own, so there's no CORS to configure and no URL env vars to keep in sync.++## Prerequisites++- The `eve` package installed in your project (`npm install eve@latest`).+- An existing Eve agent directory. If you don't have one, start from [Getting started](../../getting-started).+- A Nuxt app to mount the agent in.## Register the module@@ -24,9 +30,11 @@ export default defineNuxtConfig({});```+The `eve` key accepts only two options, `eveRoot` and `eveBuildCommand`.+## Call the composable-`useEveAgent` (`eve/vue`) is auto-imported, so a component can call it without an explicit import and without naming a host:+`useEveAgent` (`eve/vue`) is auto-imported, so a component calls it without an explicit import and without naming a host:```vue<script setup lang="ts">@@ -52,7 +60,16 @@ async function handleSubmit() {</template>```-Out of the box the module gives Eve a framework default channel. When you want to pick the route auth policy yourself, add `agent/channels/eve.ts` and swap `none()` for a helper like `vercelOidc()` on protected apps. See [Channels](../../channels/overview) and [Auth & route protection](../auth-and-route-protection).+The default Eve channel is fail-closed. With no `agent/channels/eve.ts` authored, Eve registers `eveChannel({ auth: [localDev(), vercelOidc()] })`: `localDev()` opens the routes on localhost, `vercelOidc()` admits Vercel OIDC callers in production, and everything else gets a `401`. To run your own auth policy, add `agent/channels/eve.ts`:++```ts title="agent/channels/eve.ts"+import { eveChannel } from "eve/channels/eve";+import { localDev, vercelOidc } from "eve/channels/auth";++export default eveChannel({ auth: [localDev(), vercelOidc()] });+```++For a public demo, use `none()` (also from `eve/channels/auth`) to skip authentication. See [Channels](../../channels/overview) and [Auth & route protection](../auth-and-route-protection).## Dev vs deploy topology@@ -68,7 +85,7 @@ Out of the box the module gives Eve a framework default channel. When you want t});```-- **Non-Vercel hosts.** Point Nuxt at a separate Eve origin with `EVE_NUXT_PRODUCTION_ORIGIN`. To override the local port (it defaults to `4274`), use `EVE_NUXT_PRODUCTION_PORT`:+- **Non-Vercel hosts.** Point Nuxt at a separate Eve origin with `EVE_NUXT_PRODUCTION_ORIGIN`. To override the local port (default `4274`), use `EVE_NUXT_PRODUCTION_PORT`:```bashEVE_NUXT_PRODUCTION_ORIGIN=https://agent.example.com npm run builddiff --git a/docs/guides/frontend/overview.mdx b/docs/guides/frontend/overview.mdxindex 71398b6e6..181df4119 100644--- a/docs/guides/frontend/overview.mdx+++ b/docs/guides/frontend/overview.mdx@@ -3,22 +3,22 @@ title: "Overview"description: "Put an Eve agent behind a browser chat UI with useEveAgent."----The frontend helpers put a browser chat or agent UI on top of an Eve agent. `useEveAgent()` does the heavy lifting: it opens a durable session, sends turns, streams the reply back, and turns the raw event stream into render-ready state. React is the reference implementation, and [Vue](./use-eve-agent-vue) and [Svelte](./use-eve-agent-svelte) ship the same surface.+The frontend helpers put a browser chat or agent UI on top of an Eve agent. `useEveAgent()` opens a durable session, sends turns, streams the reply back, and turns the raw event stream into render-ready state. React is the reference implementation; [Vue](./use-eve-agent-vue) and [Svelte](./use-eve-agent-svelte) ship the same surface.## The integration model-A browser UI is just a client of the agent's HTTP routes (the [Eve channel](../../channels/overview)). Two layers wire it up:+A browser UI is a client of the agent's HTTP routes (the [Eve channel](../../channels/overview)). Two layers wire it up:- **The framework integration** mounts the Eve routes on your app's origin, so the browser never crosses a CORS boundary or reads an env var to find the agent. Pick yours: [Next.js](./nextjs) (`withEve`), [Nuxt](./nuxt) (the `eve/nuxt` module), or [SvelteKit](./sveltekit) (the `eveSvelteKit` Vite plugin). On any other stack the hook talks to same-origin `/eve/v1/*` routes directly, or you pass an explicit `host`.- **The hook** (`useEveAgent`) holds the session state, streaming, errors, and composer status. It defaults to same-origin Eve routes such as `/eve/v1/session`.-For a guided setup, the [Guides](/docs/skills/eve-add-next) walk through the wiring step by step: [add a Next.js frontend to an existing Eve agent](/docs/skills/eve-add-next), or [add Eve to an existing Next.js app](/docs/skills/eve-add-agent).+The per-framework pages below walk through the wiring step by step: [Next.js](./nextjs), [Nuxt](./nuxt), and [SvelteKit](./sveltekit).For scripts, server-to-server calls, evals, tests, or custom clients that do not need framework UI state, use the [TypeScript SDK](../client/overview) directly.## Basic chat (React)-The hook lives in `eve/react`. Render `data.messages`, gate the composer on `status`, and send text with `send`. That's the whole loop:+The hook lives in `eve/react`. Render `data.messages`, gate the composer on `status`, and send text with `send`:```tsx"use client";@@ -72,7 +72,7 @@ export function Chat() {| `stop` | Abort the active request. || `reset` | Clear local events, data, errors, and the local session cursor. |-Most chat UIs only need `data.messages` and `status`. Drop down to `events` when you want to render lower-level activity (tool calls, reasoning deltas) that the default reducer doesn’t surface.+Most chat UIs only need `data.messages` and `status`. Drop down to `events` to render lower-level activity such as tool calls and reasoning deltas that the default reducer doesn't surface.`data.messages` are `EveMessage[]` following the AI SDK `UIMessage` convention, so they drop straight into any AI SDK UI primitive that accepts a `UIMessage[]`. Parts include user text, assistant text, reasoning, tool calls, tool results, and input requests.@@ -96,7 +96,7 @@ await agent.send({});```-Assistant text, reasoning, tool calls, and tool results stream into `data` as they arrive, and `status` moves from `ready` to `submitted` to `streaming` and back. Call `stop()` to abort the active request. Call `reset()` to clear local state so the next send starts a fresh durable session.+Assistant text, reasoning, tool calls, and tool results stream into `data` as they arrive, and `status` moves from `ready` to `submitted` to `streaming` and back. Call `stop()` to abort the active request, and `reset()` to clear local state so the next send starts a fresh durable session.## Human-in-the-loop prompts@@ -115,11 +115,11 @@ if (request) {}```-`request.prompt` and `request.options` give you what you need to render the approve and deny UI. The default reducer marks the part as responded right away, then updates it again once Eve streams the resumed result.+`request.prompt` and `request.options` give you what you need to render the approve and deny UI. The default reducer marks the part as responded immediately, then updates it again once Eve streams the resumed result.## Attach page context per turn-`clientContext` adds ephemeral context for the next model call and nothing more. Strings (or an array of strings) become user-role context messages; an object is JSON-serialized into one. It rides along with a message or HITL response, so it never dispatches a turn on its own and never lands in durable session history. Pass it directly to `send()`:+`clientContext` adds ephemeral context for the next model call only. Strings (or an array of strings) become user-role context messages; an object is JSON-serialized into one. It rides along with a message or HITL response, so it never dispatches a turn on its own and never lands in durable session history. Pass it directly to `send()`:```tsxawait agent.send({@@ -182,11 +182,11 @@ const agent = useEveAgent({ reducer: toolCounter });// agent.data is ToolLog```-`reduce(data, event)` receives both authoritative Eve stream events and client projection events (`client.message.submitted`, `client.message.failed`, `client.input.responded`). Handle the client events too if you want optimistic and HITL state in your projection. Otherwise, just return `data` unchanged for them.+`reduce(data, event)` receives both authoritative Eve stream events and client projection events (`client.message.submitted`, `client.message.failed`, `client.input.responded`). Handle the client events too if you want optimistic and HITL state in your projection. Otherwise, return `data` unchanged for them.## Resumable sessions-The browser conversation lives durably on the server. Persist the `session` cursor and you can pick it back up after a reload:+The browser conversation lives durably on the server. Persist the `session` cursor to pick it back up after a reload:```tsxconst [initialSession] = useState(() => {@@ -231,4 +231,4 @@ const agent = useEveAgent({- [Sessions, runs & streaming](../../concepts/sessions-runs-and-streaming): the event stream and session cursor- [Channels](../../channels/overview): the HTTP routes the hook talks to- [TypeScript SDK](../client/overview): the lower-level client underneath the frontend hooks-- [Guides](/docs/skills/eve-add-next): step-by-step guides for wiring Eve into Next.js+- [Next.js](./nextjs): step-by-step setup for wiring Eve into a Next.js appdiff --git a/docs/guides/frontend/sveltekit.mdx b/docs/guides/frontend/sveltekit.mdxindex 6f07faf6d..aad460a71 100644--- a/docs/guides/frontend/sveltekit.mdx+++ b/docs/guides/frontend/sveltekit.mdx@@ -3,7 +3,13 @@ title: "SvelteKit"description: "Run an Eve agent and a SvelteKit app as one project with the eveSvelteKit Vite plugin."----`eve/sveltekit` lets you run a SvelteKit frontend and an Eve agent as one project instead of two services you have to keep in sync. The `eveSvelteKit()` Vite plugin puts both on one dev server and one Vercel deploy, and [`useEveAgent`](./use-eve-agent-svelte) finds the mounted routes on its own. No CORS config, no URL env vars.+`eve/sveltekit` runs a SvelteKit frontend and an Eve agent as one project instead of two services. The `eveSvelteKit()` Vite plugin puts both on one dev server and one Vercel deploy, and [`useEveAgent`](./use-eve-agent-svelte) finds the mounted routes on its own. There's no CORS to configure and no URL env vars to keep in sync.++## Prerequisites++- The `eve` package installed in your project (`npm install eve@latest`).+- An existing Eve agent directory. If you don't have one, start from [Getting started](../../getting-started).+- A SvelteKit app to mount the agent in.## Register the Vite plugin@@ -32,6 +38,8 @@ export default defineConfig({});```+The plugin accepts only two options, `eveRoot` and `eveBuildCommand`.+## Call the bindingWith the plugin in `vite.config.ts`, components call [`useEveAgent`](./use-eve-agent-svelte) from `eve/svelte` and don't pass a host:@@ -61,11 +69,20 @@ With the plugin in `vite.config.ts`, components call [`useEveAgent`](./use-eve-a</form>```-Out of the box the plugin uses a framework default channel. To set the route auth policy yourself, add `agent/channels/eve.ts` and swap `none()` for a helper like `vercelOidc()` on protected apps. See [Channels](../../channels/overview) and [Auth & route protection](../auth-and-route-protection).+The default Eve channel is fail-closed. With no `agent/channels/eve.ts` authored, Eve registers `eveChannel({ auth: [localDev(), vercelOidc()] })`: `localDev()` opens the routes on localhost, `vercelOidc()` admits Vercel OIDC callers in production, and everything else gets a `401`. To set your own auth policy, add `agent/channels/eve.ts`:++```ts title="agent/channels/eve.ts"+import { eveChannel } from "eve/channels/eve";+import { localDev, vercelOidc } from "eve/channels/auth";++export default eveChannel({ auth: [localDev(), vercelOidc()] });+```++For a public demo, use `none()` (also from `eve/channels/auth`) to skip authentication. See [Channels](../../channels/overview) and [Auth & route protection](../auth-and-route-protection).## Dev vs deploy topology-- **Local dev.** `npm run dev` boots the Eve dev server next to SvelteKit and proxies the Eve routes to it, so the browser only ever hits the SvelteKit origin. `npm run build && npm run preview` behaves the same: the preview server gets its own Eve route proxy and either reuses the shared Eve server or starts one.+- **Local dev.** `npm run dev` boots the Eve dev server next to SvelteKit and proxies the Eve routes to it, so the browser only ever hits the SvelteKit origin. `npm run build && npm run preview` behaves the same way: the preview server gets its own Eve route proxy and either reuses the shared Eve server or starts one.- **Vercel.** The SvelteKit app and the Eve runtime deploy as a single project. The web app is public; the Eve runtime sits behind it on the same origin. Use `eveBuildCommand` for a project-specific agent build:```tsdiff --git a/docs/guides/frontend/use-eve-agent-svelte.mdx b/docs/guides/frontend/use-eve-agent-svelte.mdxindex 3c5181788..a961c8e1e 100644--- a/docs/guides/frontend/use-eve-agent-svelte.mdx+++ b/docs/guides/frontend/use-eve-agent-svelte.mdx@@ -3,7 +3,7 @@ title: "useEveAgent (Svelte)"description: "Svelte 5 binding that drives an Eve agent session from the browser."----`useEveAgent()` from `eve/svelte` is the browser side of an Eve session in a Svelte 5 app. Call it once and you get a long-lived session you can send turns to, with every stream event projected into rune-friendly reactive data. On SvelteKit, the [Vite plugin](./sveltekit) wires up the routes. The [frontend overview](./overview) covers the model shared across frameworks.+`useEveAgent()` from `eve/svelte` is the browser side of an Eve session in a Svelte 5 app. Call it once for a long-lived session you can send turns to, with every stream event projected into rune-friendly reactive data. On SvelteKit, the [Vite plugin](./sveltekit) wires up the routes. The [frontend overview](./overview) covers the model shared across frameworks.## Basic usage@@ -23,16 +23,16 @@ Import from `eve/svelte` and read the reactive getters directly. No `$` prefix:## What it returns-| Property | Type | Description |-| --------- | -------------------- | ------------------------------------------------------------------------- |-| `data` | `TData` | Projected state. With the default reducer, `EveMessageData` (`messages`). |-| `status` | `UseEveAgentStatus` | `"ready"`, `"submitted"`, `"streaming"`, or `"error"`. |-| `error` | `Error \| undefined` | Last transport-level error. |-| `events` | `readonly ...[]` | Raw server events for this session. |-| `session` | `SessionState` | Snapshot of session state. |-| `send` | `(input) => Promise` | Send text or a full turn (multi-part, attachments, HITL responses). |-| `stop` | `() => void` | Abort the in-flight request. |-| `reset` | `() => void` | Clear state and start a new session. |+| Property | Type | Description |+| --------- | ------------------------------------------- | ------------------------------------------------------------------------- |+| `data` | `TData` | Projected state. With the default reducer, `EveMessageData` (`messages`). |+| `status` | `UseEveAgentStatus` | `"ready"`, `"submitted"`, `"streaming"`, or `"error"`. |+| `error` | `Error \| undefined` | Last transport-level error. |+| `events` | `readonly HandleMessageStreamEvent[]` | Raw server events for this session. |+| `session` | `SessionState` | Snapshot of session state. |+| `send` | `(input: SendTurnPayload) => Promise<void>` | Send text or a full turn (multi-part, attachments, HITL responses). |+| `stop` | `() => void` | Abort the in-flight request. |+| `reset` | `() => void` | Clear state and start a new session. |These state fields are reactive getters, so read them straight from templates, `$derived`, or `$effect`. They are not stores, so don't prefix them with `$`.@@ -62,20 +62,44 @@ These state fields are reactive getters, so read them straight from templates, `</form>```-When a turn is more than plain text, reach for `send()`. Attachments follow the AI SDK `UserContent` format:+When a turn is more than plain text, reach for `send()`. Attachments follow the AI SDK `UserContent` format. Send file data as a base64 `data:` URL so it survives the JSON transport:```ts+const bytes = new Uint8Array(await file.arrayBuffer());+const base64 = btoa(String.fromCodePoint(...bytes));+await agent.send({message: [{ type: "text", text: "Describe this image." },- { type: "file", data: fileBytes, mediaType: "image/png" },+ { type: "file", data: `data:${file.type};base64,${base64}`, mediaType: file.type },],});```## Human-in-the-loop prompts-A tool opts into approval with `needsApproval` ([Tools](../../tools)). When one fires, the pending request rides along on a `dynamic-tool` part of the latest message. Read it, then answer with `agent.send({ inputResponses })`. This find-and-answer flow is identical across frameworks, so the full example lives in the [Frontend overview](./overview#human-in-the-loop-prompts).+A tool opts into approval with `needsApproval` ([Tools](../../tools)). When one fires, the pending request rides along on a `dynamic-tool` part of the latest message at `part.toolMetadata?.eve?.inputRequest`. Read it, then answer through the same session with `agent.send({ inputResponses })`:++```ts+import type { EveDynamicToolPart, EveMessagePart } from "eve/svelte";++const isDynamicToolPart = (part: EveMessagePart): part is EveDynamicToolPart =>+ part.type === "dynamic-tool";++const request = agent.data.messages+ .at(-1)+ ?.parts.filter(isDynamicToolPart)+ .map((part) => part.toolMetadata?.eve?.inputRequest)+ .find((value) => value !== undefined);++if (request) {+ await agent.send({+ inputResponses: [{ requestId: request.requestId, optionId: "approve" }],+ });+}+```++The find-and-answer flow is identical across frameworks. The [React hook reference](./overview) covers the longer walkthrough.## Stop, reset, and resume@@ -104,6 +128,74 @@ const agent = useEveAgent({});```+## Attach page context per turn++`clientContext` adds ephemeral context for the next model call and nothing more. Strings (or an array of strings) become user-role context messages; an object is JSON-serialized into one. It rides along with a message or HITL response, never dispatches a turn on its own, and never lands in durable session history. Pass it to `send()`:++```ts+await agent.send({+ message: "What should I do on this screen?",+ clientContext: { route: "/billing", plan: "pro", seatsUsed: 4 },+});+```++To attach the same context to every turn without threading it through each call site, pass `prepareSend`. It runs right before each send and returns the (possibly augmented) turn:++```ts+const agent = useEveAgent({+ prepareSend: (input) => ({+ ...input,+ clientContext: { route: location.pathname },+ }),+});+```++## Lifecycle callbacks++The binding takes a few per-turn callbacks:++- `onEvent(event)`: fires for each Eve stream event as it arrives.+- `onError(error)`: fires with the last `Error` when a turn fails.+- `onFinish(snapshot)`: fires with the final snapshot once a turn settles.+- `onSessionChange(session)`: fires when the session cursor advances. Persist it to resume across reloads.++```ts+const agent = useEveAgent({+ onEvent: (event) => console.debug(event.type),+ onError: (error) => console.error(error.message),+ onFinish: (snapshot) => console.log(snapshot.status),+});+```++Two more options tune turn behavior:++- `optimistic` (default `true`): projects submitted user messages into `data` before Eve confirms them with a `message.received` event. These are reducer-facing projection events only; `events` stays the authoritative Eve stream.+- `maxReconnectAttempts` (default `3`): stream reconnection budget per turn.++## Custom reducer++The default reducer projects events into `{ messages }` (`EveMessageData`). To shape `data` differently, pass a `reducer` implementing `EveAgentReducer<TData>`:++```ts+import { useEveAgent } from "eve/svelte";+import type { EveAgentReducer } from "eve/svelte";++interface ToolLog {+ readonly toolCalls: number;+}++const toolCounter: EveAgentReducer<ToolLog> = {+ initial: () => ({ toolCalls: 0 }),+ reduce: (data, event) =>+ event.type === "actions.requested" ? { toolCalls: data.toolCalls + 1 } : data,+};++const agent = useEveAgent({ reducer: toolCounter });+// agent.data is ToolLog+```++`reduce(data, event)` receives both authoritative Eve stream events and client projection events (`client.message.submitted`, `client.message.failed`, `client.input.responded`). Handle the client events too if you want optimistic and HITL state in your projection. Otherwise, return `data` unchanged for them.+## What to read next- [SvelteKit](./sveltekit): Vite plugin setupdiff --git a/docs/guides/frontend/use-eve-agent-vue.mdx b/docs/guides/frontend/use-eve-agent-vue.mdxindex 119cc82c7..e5318d3dd 100644--- a/docs/guides/frontend/use-eve-agent-vue.mdx+++ b/docs/guides/frontend/use-eve-agent-vue.mdx@@ -3,7 +3,7 @@ title: "useEveAgent (Vue)"description: "Vue composable that drives an Eve agent session from the browser."----`useEveAgent()` from `eve/vue` is how a Vue app talks to an Eve session. It opens a long-lived session and sends turns, and it folds every stream event into reactive data you can bind in a template. Nuxt auto-imports it through the [module](./nuxt), and the [frontend overview](./overview) covers the shared model.+`useEveAgent()` from `eve/vue` is how a Vue app talks to an Eve session. It opens a long-lived session, sends turns, and folds every stream event into reactive data you can bind in a template. Nuxt auto-imports it through the [module](./nuxt), and the [frontend overview](./overview) covers the shared model.## Basic usage@@ -25,18 +25,18 @@ const { data } = useEveAgent();## What it returns-| Property | Type | Description |-| --------- | --------------------------------- | ------------------------------------------------------------------------- |-| `data` | `ComputedRef<TData>` | Projected state. With the default reducer, `EveMessageData` (`messages`). |-| `status` | `ComputedRef<UseEveAgentStatus>` | `"ready"`, `"submitted"`, `"streaming"`, or `"error"`. |-| `error` | `ComputedRef<Error \| undefined>` | Last transport-level error. |-| `events` | `ComputedRef<...>` | Raw server events for this session. |-| `session` | `ComputedRef<SessionState>` | Snapshot of session state. |-| `send` | `(input) => Promise` | Send text or a full turn (multi-part, attachments, HITL responses). |-| `stop` | `() => void` | Abort the in-flight request. |-| `reset` | `() => void` | Clear state and start a new session. |+| Property | Type | Description |+| --------- | -------------------------------------------------- | ------------------------------------------------------------------------- |+| `data` | `ComputedRef<TData>` | Projected state. With the default reducer, `EveMessageData` (`messages`). |+| `status` | `ComputedRef<UseEveAgentStatus>` | `"ready"`, `"submitted"`, `"streaming"`, or `"error"`. |+| `error` | `ComputedRef<Error \| undefined>` | Last transport-level error. |+| `events` | `ComputedRef<readonly HandleMessageStreamEvent[]>` | Raw server events for this session. |+| `session` | `ComputedRef<SessionState>` | Snapshot of session state. |+| `send` | `(input: SendTurnPayload) => Promise<void>` | Send text or a full turn (multi-part, attachments, HITL responses). |+| `stop` | `() => void` | Abort the in-flight request. |+| `reset` | `() => void` | Clear state and start a new session. |-The first five are `ComputedRef`s; the rest are methods. Destructure whatever you need: refs keep their reactivity through destructuring. Read them with `.value` in `<script>`, and unwrapped in `<template>`.+The first five are `ComputedRef`s; the rest are methods. Destructure whatever you need, since refs keep their reactivity through destructuring. Read them with `.value` in `<script>`, and unwrapped in `<template>`.## Send a message@@ -64,7 +64,7 @@ async function handleSubmit() {</template>```-For anything beyond plain text, reach for `send()`. Attachments follow the AI SDK `UserContent` format:+For anything beyond plain text, reach for `send()`. Attachments follow the AI SDK `UserContent` format. Send file data as a base64 `data:` URL so it survives the JSON transport:```vue<script setup lang="ts">@@ -75,10 +75,12 @@ const { send } = useEveAgent();async function onFileChange(event: Event) {const file = (event.target as HTMLInputElement).files?.[0];if (!file) return;+ const bytes = new Uint8Array(await file.arrayBuffer());+ const base64 = btoa(String.fromCodePoint(...bytes));await send({message: [{ type: "text", text: "Describe this image." },- { type: "file", data: new Uint8Array(await file.arrayBuffer()), mediaType: file.type },+ { type: "file", data: `data:${file.type};base64,${base64}`, mediaType: file.type },],});}@@ -87,7 +89,30 @@ async function onFileChange(event: Event) {## Human-in-the-loop prompts-A tool opts into approval with `needsApproval` ([Tools](../../tools)). When it triggers, the pending request shows up as a `dynamic-tool` part on the latest message. Read it and answer with `send({ inputResponses })`. That find-and-answer flow is the same across every framework, so the full example lives in the [Frontend overview](./overview#human-in-the-loop-prompts).+A tool opts into approval with `needsApproval` ([Tools](../../tools)). When it triggers, the pending request shows up as a `dynamic-tool` part on the latest message at `part.toolMetadata?.eve?.inputRequest`. Read it, then answer through the same session with `send({ inputResponses })`:++```ts+import type { EveDynamicToolPart, EveMessagePart } from "eve/vue";++const { data, send } = useEveAgent();++const isDynamicToolPart = (part: EveMessagePart): part is EveDynamicToolPart =>+ part.type === "dynamic-tool";++const request = data.value.messages+ .at(-1)+ ?.parts.filter(isDynamicToolPart)+ .map((part) => part.toolMetadata?.eve?.inputRequest)+ .find((value) => value !== undefined);++if (request) {+ await send({+ inputResponses: [{ requestId: request.requestId, optionId: "approve" }],+ });+}+```++The find-and-answer flow is the same across every framework. The [React hook reference](./overview) covers the longer walkthrough.## Stop, reset, and resume@@ -116,6 +141,74 @@ const agent = useEveAgent({});```+## Attach page context per turn++`clientContext` adds ephemeral context for the next model call and nothing more. Strings (or an array of strings) become user-role context messages; an object is JSON-serialized into one. It rides along with a message or HITL response, never dispatches a turn on its own, and never lands in durable session history. Pass it to `send()`:++```ts+await send({+ message: "What should I do on this screen?",+ clientContext: { route: "/billing", plan: "pro", seatsUsed: 4 },+});+```++To attach the same context to every turn without threading it through each call site, pass `prepareSend`. It runs right before each send and returns the (possibly augmented) turn:++```ts+const agent = useEveAgent({+ prepareSend: (input) => ({+ ...input,+ clientContext: { route: location.pathname },+ }),+});+```++## Lifecycle callbacks++The composable takes a few per-turn callbacks:++- `onEvent(event)`: fires for each Eve stream event as it arrives.+- `onError(error)`: fires with the last `Error` when a turn fails.+- `onFinish(snapshot)`: fires with the final snapshot once a turn settles.+- `onSessionChange(session)`: fires when the session cursor advances. Persist it to resume across reloads.++```ts+const agent = useEveAgent({+ onEvent: (event) => console.debug(event.type),+ onError: (error) => console.error(error.message),+ onFinish: (snapshot) => console.log(snapshot.status),+});+```++Two more options tune turn behavior:++- `optimistic` (default `true`): projects submitted user messages into `data` before Eve confirms them with a `message.received` event. These are reducer-facing projection events only; `events` stays the authoritative Eve stream.+- `maxReconnectAttempts` (default `3`): stream reconnection budget per turn.++## Custom reducer++The default reducer projects events into `{ messages }` (`EveMessageData`). To shape `data` differently, pass a `reducer` implementing `EveAgentReducer<TData>`:++```ts+import { useEveAgent } from "eve/vue";+import type { EveAgentReducer } from "eve/vue";++interface ToolLog {+ readonly toolCalls: number;+}++const toolCounter: EveAgentReducer<ToolLog> = {+ initial: () => ({ toolCalls: 0 }),+ reduce: (data, event) =>+ event.type === "actions.requested" ? { toolCalls: data.toolCalls + 1 } : data,+};++const agent = useEveAgent({ reducer: toolCounter });+// agent.data.value is ToolLog+```++`reduce(data, event)` receives both authoritative Eve stream events and client projection events (`client.message.submitted`, `client.message.failed`, `client.input.responded`). Handle the client events too if you want optimistic and HITL state in your projection. Otherwise, return `data` unchanged for them.+## What to read next- [Nuxt](./nuxt): module setupdiff --git a/docs/guides/hooks.md b/docs/guides/hooks.mdindex 1044071d3..0e7d5252b 100644--- a/docs/guides/hooks.md+++ b/docs/guides/hooks.md@@ -3,7 +3,7 @@ title: "Hooks"description: "Subscribe to runtime stream events from agent/hooks/."----Hooks are Eve's authored extension points for the runtime event stream. A hook subscribes to stream events and runs side effects after each event is durably recorded: audit logging, metrics and alerting, or persisting every session and message to your own database for analytics. Reach for one when you want to observe what the agent does without writing a tool, a context provider, or a channel adapter handler.+Hooks are Eve's authored extension points for the runtime event stream. A hook subscribes to stream events and runs side effects after each event is durably recorded, such as audit logging, metrics and alerting, or persisting every session and message to your own database for analytics. Reach for one to observe what the agent does without writing a tool, a context provider (a value made available across a step), or a channel adapter handler (a handler defined on a channel's adapter; see [Channels](../channels)).## Define a hook@@ -22,31 +22,13 @@ export default defineHook({});```-The slug is the path-relative basename: `agent/hooks/audit.ts` becomes `"audit"`, and `agent/hooks/auth/load-profile.ts` becomes `"auth/load-profile"`.+The slug is the path-relative basename. `agent/hooks/audit.ts` becomes `"audit"`, and `agent/hooks/auth/load-profile.ts` becomes `"auth/load-profile"`.-`defineHook`, `HookDefinition`, and `HookContext` live on `eve/hooks`. The `defineState` helper lives on `eve/context`.+`defineHook`, `HookDefinition`, and `HookContext` live on `eve/hooks`.-## Shape+A hook file declares stream-event subscribers under the `events` map, keyed by event type, with `*` matching every event. Subscribe to any event in the runtime stream vocabulary documented in [Sessions, runs and streaming](../concepts/sessions-runs-and-streaming), including the lifecycle events `session.started`, `turn.completed`, `message.completed`, and `action.result`. Handlers are observe-only. They cannot inject model context. To contribute runtime model messages, use `defineDynamic` and `defineInstructions` in `agent/instructions/`.-A hook file declares stream-event subscribers under the `events` map:--```ts-defineHook({- events: {- "session.started"(event, ctx) {- /* ... */- },- "turn.completed"(event, ctx) {- /* ... */- },- "*"(event, ctx) {- /* wildcard: fires for every event */- },- },-});-```--Handlers are observe-only: they cannot inject model context. To contribute runtime model messages, use `defineDynamic` + `defineInstructions` in `agent/instructions/`.+## Hook structure and contextEvery handler receives the same `HookContext`:@@ -89,51 +71,23 @@ export default defineHook({Returns `undefined` when the result doesn't match, or when `isError` is `true`. For authored tools the return includes `{ output, toolName, callId }` with `output` typed as the tool's `TOutput`. For connections it includes `{ output, toolName, connectionToolName, callId }` with `output` as `unknown`.-## Stream events--Side-effect-only handlers for accepted runtime events. Subscribe by event type, or use `*` for every event:--```ts title="agent/hooks/observability.ts"-import { defineHook } from "eve/hooks";-import { datadogCounter } from "../lib/datadog";-import { postToHoneycomb } from "../lib/honeycomb";--export default defineHook({- events: {- async "session.started"(_event, ctx) {- await postToHoneycomb({ event: "session.started", sessionId: ctx.session.id });- },- async "message.completed"(event) {- await postToHoneycomb({ event: "message.completed", payload: event.data });- },- async "*"(event) {- datadogCounter(`eve.event.${event.type}`).increment();- },- },-});-```--### Execution order+## Execution orderWhen a stream event fires, three things happen in order:-1. Emit: the channel adapter handler runs, then the event is written to the durable stream.-2. Hooks: stream-event hooks fire (typed handlers first, then the `*` wildcard). Return values are ignored.-3. Dynamic tool resolvers: resolvers subscribed to the event type run and update the tool set.+1. Emit. The channel adapter handler runs, then the event is written to the durable stream.+2. Hooks. Stream-event hooks fire (typed handlers first, then the `*` wildcard). Return values are ignored.+3. Dynamic tool resolvers. Resolvers subscribed to the event type run and update the tool set.Hooks always run after the event is durably recorded, so if a hook throws, the stream stays consistent.-## Errors--| Stage | On throw |-| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| `events.*` | Propagates through the emit composer and surfaces as `turn.failed`. If a hook subscribed to a failure-cascade event also throws, it escalates to `session.failed`. |+## What happens when a hook throws-For belt-and-suspenders semantics inside a hook, wrap the body in `try`/`catch`. Eve treats a thrown hook as a real failure.+A thrown handler propagates through the emit composer and surfaces as `turn.failed`. If a hook subscribed to a failure-cascade event also throws, it escalates to `session.failed`. For belt-and-suspenders semantics inside a hook, wrap the body in `try`/`catch`. Eve treats a thrown hook as a real failure.## Subagent isolation-Subagents may carry their own `agent/hooks/` directory. Subagent hooks fire only inside the subagent scope: parent-agent hooks do not fire for subagent turns, and subagent hooks see only the subagent's own context.+Subagents may carry their own `agent/hooks/` directory. Subagent hooks fire only inside the subagent scope. Parent-agent hooks do not fire for subagent turns, and subagent hooks see only the subagent's own context.## Hook vs tool vs provider@@ -150,5 +104,5 @@ Stream-event hooks and channel adapter event handlers are structurally identical- [Tools](../tools)- [Context control](../concepts/context-control)-- [Session context](./session-context)-- [Sessions, runs & streaming](../concepts/sessions-runs-and-streaming)+- [Session context](../reference/typescript-api)+- [Sessions, runs and streaming](../concepts/sessions-runs-and-streaming)diff --git a/docs/guides/instrumentation.md b/docs/guides/instrumentation.mdindex 8ea7b3742..b716a028b 100644--- a/docs/guides/instrumentation.md+++ b/docs/guides/instrumentation.md@@ -1,13 +1,13 @@---title: "instrumentation.ts"-description: "Trace an agent with OpenTelemetry, read the workflow run tags Eve emits, and debug discovery with eve info and the error catalog."+description: "Trace an agent with OpenTelemetry in instrumentation.ts, read the workflow run tags Eve emits, and debug discovery with eve info and the common-failures table."---`instrumentation.ts` is where you configure how an Eve agent is observed. The framework auto-discovers `agent/instrumentation.ts` and runs it at server startup before any agent code. Its presence implicitly enables telemetry, so there is no separate `isEnabled` toggle.## Three observability surfaces-Eve observes an agent through three distinct surfaces. They do not all live in this file, and they write to different places, so it helps to keep them apart:+Eve observes an agent through three distinct surfaces. They do not all live in this file, and they write to different places:| Surface | Configured in `instrumentation.ts`? | What it is || -------------------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |@@ -15,7 +15,7 @@ Eve observes an agent through three distinct surfaces. They do not all live in t| **OpenTelemetry export** | Yes: `setup`, `recordInputs`, `recordOutputs`, `functionId` | Where AI SDK spans are exported and what they record. || **Runtime context events** | Yes: `events["step.started"]` | Per-model-call values written into the AI SDK's runtime context, which the AI SDK carries onto its spans. |-The two configurable surfaces send AI SDK spans to your OpenTelemetry backend. Workflow run tags are a separate system: they live on the Vercel Workflow run and are queryable in the Workflow dashboard, not on your OTel spans. The sections below cover what you configure here; [Workflow run tags](#workflow-run-tags) documents what Eve emits on its own.+The two configurable surfaces send AI SDK spans to your OpenTelemetry backend. Workflow run tags are a separate system, queryable in the Workflow dashboard rather than on your OTel spans. The sections below cover what you configure here; [Workflow run tags](#workflow-run-tags) documents what Eve emits on its own.## Define instrumentation@@ -40,7 +40,7 @@ Export the result of `defineInstrumentation` as the default export.## OpenTelemetry-The `setup` callback is invoked by the framework at server startup with the resolved agent name. Use it to register your OTel provider (for example `registerOTel` from `@vercel/otel`). The `context.agentName` is resolved at compile time from your project (the package's `name`, falling back to the app directory name), so you never need to hard-code a service name.+Use the `setup` callback to register your OTel provider (for example `registerOTel` from `@vercel/otel`). The framework invokes it at server startup with the resolved agent name. `context.agentName` is resolved at compile time from your project (the package's `name`, falling back to the app directory name), so you never hard-code a service name.Any OTel-compatible backend works (Braintrust, Honeycomb, Datadog, Jaeger). Install the exporter package you need and configure it in the callback.@@ -54,7 +54,7 @@ The third configurable surface, [runtime context events](#runtime-context), atta## Runtime context-_Runtime context_ is an [AI SDK concept](https://ai-sdk.dev/docs/reference/ai-sdk-core/stream-text): a user-defined object that flows through a generation lifecycle. Eve exposes it through `events["step.started"]`, a callback that runs once Eve has assembled the model input for an attempt and returns `{ runtimeContext }`. Because Eve registers the AI SDK's OpenTelemetry integration with runtime context enabled, those returned values ride onto the model-call span and its children. That is the reason this surface exists. The returned field is named `runtimeContext`, not `metadata`, because AI SDK v7 carries per-call attributes on runtime context rather than a dedicated metadata field.+_Runtime context_ is an [AI SDK concept](https://ai-sdk.dev/docs/reference/ai-sdk-core/stream-text): a user-defined object that flows through a generation lifecycle. Eve exposes it through `events["step.started"]`, a callback that runs once Eve has assembled the model input for an attempt and returns `{ runtimeContext }`. Because Eve registers the AI SDK's OpenTelemetry integration with runtime context enabled, those returned values ride onto the model-call span and its children. The field is named `runtimeContext`, not `metadata`, because AI SDK v7 carries per-call attributes on runtime context rather than a dedicated metadata field.Use it when the values depend on the current session, turn, step, channel, or model input:@@ -80,8 +80,6 @@ export default defineInstrumentation({});```-For authored channels, Eve emits compiler-owned typings keyed by the channel filename. A file at `agent/channels/support.ts` narrows as `channel:support`, either by checking `input.channel.kind === "channel:support"` or by using `isChannel(input.channel, supportChannel)`.-The callback receives:- `session`: the session id, current and initiator auth, and parent session lineage when this is a child run@@ -90,7 +88,7 @@ The callback receives:- `channel`: the channel's `kind` and the metadata projected by the active channel- `modelInput`: the final instructions and messages passed to the model call-A channel exposes its identity through `kind`, the discriminant you narrow on. For authored channels it is `channel:<name>`, where `<name>` is the channel's filename under `agent/channels/`, so `agent/channels/support.ts` is `channel:support`. Framework channels use `http`, `schedule`, or `subagent`; an unrecognized or absent kind normalizes to `unknown`. The kind is also emitted as the `eve.channel.kind` span attribute.+A channel exposes its identity through `kind`, the discriminant you narrow on. For authored channels it is `channel:<name>`, where `<name>` is the channel's filename under `agent/channels/`, so `agent/channels/support.ts` is `channel:support`. Framework channels use `http`, `schedule`, or `subagent`, and an unrecognized or absent kind normalizes to `unknown`. The kind is also emitted as the `eve.channel.kind` span attribute. Eve emits compiler-owned typings keyed by the channel filename, so you can narrow either by checking `input.channel.kind === "channel:support"` or by using `isChannel(input.channel, supportChannel)`.Channel metadata is channel-owned. Built-in channels expose only the fields they choose to make observable; Slack, for example, projects `channelId`, `teamId`, `threadTs`, and `triggeringUserId` from its durable channel state. User-authored channels expose their own projection by returning `metadata(state)` from `defineChannel`. Runtime instrumentation never falls back to raw channel state.@@ -115,7 +113,7 @@ Eve creates the `ai.eve.turn` parent span per turn and passes enriched telemetrySeparately from OpenTelemetry, Eve tags every workflow run with reserved `$eve.*` attributes. These live on the Vercel Workflow run, queryable in the Workflow dashboard, not on OTel spans, and you do not configure them: they are framework-owned and emitted automatically on every session, turn, and subagent run, whether or not an `instrumentation.ts` file is present. Authored code cannot set or override the `$eve.` namespace.-Their job is to let a dashboard reconstruct the tree of runs behind a single agent invocation and surface model and token usage without reading run bodies.+They let a dashboard reconstruct the tree of runs behind a single agent invocation and surface model and token usage without reading run bodies.Structural tags describe each run's place in the tree:@@ -134,7 +132,7 @@ Per-turn usage tags are written on each step of a turn, accumulating cumulativeTag writes are best-effort: a failure is logged once per process and then swallowed, so a broken tag emit never breaks the agent.-These tags power the **Agent Runs** tab in the Vercel dashboard. When you deploy on Vercel, the platform auto-detects `eve` as the framework and surfaces an Agent Runs view under your project's **Observability** tab, where you can browse sessions and drill into each conversation's trace — no `instrumentation.ts` required. The tab is currently gated per team; see [Deployment](./deployment#view-runs-in-the-dashboard) for enablement. Agent Runs is separate from the OpenTelemetry export above: use OTel when you want spans in Braintrust, Datadog, or another third-party backend.+These tags power the **Agent Runs** tab in the Vercel dashboard. When you deploy on Vercel, the platform auto-detects `eve` as the framework and surfaces an Agent Runs view under your project's **Observability** tab, where you can browse sessions and drill into each conversation's trace, with no `instrumentation.ts` required. The tab is currently gated per team. See [Deployment](./deployment#view-runs-in-the-dashboard) for enablement. Agent Runs is separate from the OpenTelemetry export above. Use OTel when you want spans in Braintrust, Datadog, or another third-party backend.## Debugging@@ -151,17 +149,17 @@ When `eve build` fails on discovery errors, the CLI prints the full diagnostics### Common failures-| Symptom | Likely cause and fix |-| --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Tool not discovered (the model never sees it) | Run `eve info`. Confirm the file is in the right slot (`agent/tools/<name>.ts`) and default-exports `defineTool(...)`, and check `.eve/diagnostics.json` for shape errors. `schedules/` are root-only. |-| Model won't call a tool it should | Tighten the tool `description` and `inputSchema`; put procedural guidance in a [skill](../skills), not the description. Confirm it's in the active set with `eve info`. |-| Stuck on `session.waiting` | The turn is parked on an approval, a question, or a connection sign-in. Answer it, or POST a follow-up with the `continuationToken` (a stale token is rejected). |-| 401 on production routes | Expected: auth fails closed. Replace `placeholderAuth()`, and set `VERCEL_PROJECT_ID` and environment so `vercelOidc()` accepts user tokens. See [Auth & route protection](./auth-and-route-protection). |-| Build fails with discovery errors | Read the printed diagnostics and `.eve/diagnostics.json`; confirm the root-vs-subagent boundary is valid and secrets come from env vars. |+| Symptom | Likely cause and fix |+| --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Tool not discovered (the model never sees it) | Run `eve info`. Confirm the file is in the right slot (`agent/tools/<name>.ts`) and default-exports `defineTool(...)`, and check `.eve/diagnostics.json` for shape errors. `schedules/` are root-only. |+| Model won't call a tool it should | Tighten the tool `description` and `inputSchema`; put procedural guidance in a [skill](../skills), not the description. Confirm it's in the active set with `eve info`. |+| Stuck on `session.waiting` | The turn is parked on an approval, a question, or a connection sign-in. Answer it, or POST a follow-up with the `continuationToken` (a stale token is rejected). |+| 401 on production routes | Expected: auth fails closed. Replace `placeholderAuth()`, and set `VERCEL_PROJECT_ID` and environment so `vercelOidc()` accepts user tokens. See [Auth and route protection](./auth-and-route-protection). |+| Build fails with discovery errors | Read the printed diagnostics and `.eve/diagnostics.json`; confirm the root-vs-subagent boundary is valid and secrets come from env vars. |## What to read next- [`agent.ts`](../agent-config)- [Hooks](./hooks): observe the runtime event stream-- [Dev TUI](./dev-tui): drive the agent locally+- [Local Development](./dev-tui): drive the agent locally- [Evals](../evals/overview): repeatable scored checksdiff --git a/docs/guides/remote-agents.md b/docs/guides/remote-agents.mdindex 865c29df9..c396e328f 100644--- a/docs/guides/remote-agents.md+++ b/docs/guides/remote-agents.md@@ -3,9 +3,9 @@ title: "Remote Agents"description: "Call another Eve deployment as a subagent with defineRemoteAgent: same lowered tool shape, outbound auth, durable callback dispatch."----Sometimes the specialist you want to delegate to isn't a directory in your repo, it's a separately owned agent living behind its own URL. `defineRemoteAgent` lets you call another Eve deployment as if it were a local subagent.+`defineRemoteAgent` calls a separately deployed Eve agent as if it were a local subagent. Reach for it when the specialist you delegate to is a separately owned agent behind its own URL rather than a directory in your repo.-The file lives under `agent/subagents/`, so its tool name is still derived from the path. There's no `name` field.+The file lives under `agent/subagents/`, so its tool name is derived from the path. There's no `name` field.```ts title="agent/subagents/weather.ts"import { defineRemoteAgent } from "eve";@@ -20,20 +20,22 @@ export default defineRemoteAgent({`defineRemoteAgent` accepts:-- `url`: the remote Eve deployment root. Required.-- `description`: the model-visible delegation description. Required.-- `auth`: optional outbound auth hook from `eve/agents/auth`.-- `headers`: optional static or lazy request headers.-- `path`: optional session-create path; defaults to `/eve/v1/session`.-- `outputSchema`: optional structured return type the caller requires (lowered to JSON Schema at compile time and enforced by the remote like any task-mode output schema).+| Parameter | Type | Required | Default | Description |+| -------------- | ------------------------------- | -------- | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |+| `url` | `string` | Yes | n/a | Base URL of the remote Eve deployment to call. |+| `description` | `string` | Yes | n/a | Model-visible delegation description. |+| `auth` | `OutboundAuthFn` | No | none | Outbound auth hook from `eve/agents/auth`. |+| `headers` | `HeadersValue` | No | none | Static or lazily resolved request headers. |+| `path` | `string` | No | `/eve/v1/session` | Route appended to `url` for the create-session request. |+| `outputSchema` | `StandardSchema \| JSON Schema` | No | none | Structured return type the caller requires. Lowered to JSON Schema at compile time and enforced by the remote like any task-mode output schema. |## The lowered tool-A remote agent lowers to the same `{ message, outputSchema? }` tool shape as a local subagent. The parent packs everything the remote needs into `message`; the remote never sees the parent's history. Set `outputSchema` (here or per call) and the remote runs in task mode, returning structured output as the tool result.+A remote agent lowers to the same `{ message, outputSchema? }` tool shape as a local subagent. The parent packs everything the remote needs into `message`. The remote never sees the parent's history. Set `outputSchema` (here or per call) and the remote runs in task mode (a single-shot delegation that returns one structured result instead of an open conversation; see [Subagents](../subagents)), returning structured output as the tool result.## Outbound auth-`auth` is an `OutboundAuthFn` from `eve/agents/auth`. It attaches request headers to the outbound dispatch:+`auth` is an `OutboundAuthFn` from `eve/agents/auth` that attaches request headers to the outbound dispatch:| Helper | Header || ------------------------------- | ---------------------------------------------------------------------------- |@@ -41,17 +43,19 @@ A remote agent lowers to the same `{ message, outputSchema? }` tool shape as a l| `bearer(token)` | `Authorization: Bearer <token>` (static or lazily resolved) || `basic({ username, password })` | `Authorization: Basic …` |-If you're calling another Vercel-deployed Eve agent, reach for `vercelOidc()`: the remote verifies the OIDC token to authorize the caller. See [Auth & route protection](./auth-and-route-protection) for the receiving side.+If you are calling another Vercel-deployed Eve agent, reach for `vercelOidc()`. The remote verifies the OIDC token to authorize the caller. See [Auth & route protection](./auth-and-route-protection) for the receiving side.-## Callback / park dispatch+## How remote dispatch and callbacks work-A local subagent runs inline. A remote one runs in its own deployment, so dispatch has to be asynchronous:+A local subagent runs inline. A remote one runs in its own deployment, so dispatch is asynchronous:1. The parent starts a task-mode session on the remote's `POST /eve/v1/session`, passing a framework callback URL.-2. The parent turn parks durably until the remote posts a terminal callback, holding no compute while it waits.+2. The parent turn parks (suspends durably without holding compute; see [Execution model & durability](../concepts/execution-model-and-durability)) until the remote posts a terminal callback.3. When the callback arrives, the parent resumes and surfaces the result.-The parent stream carries the same `subagent.called`, `action.result`, and `subagent.completed` events as local delegation. For a remote call, `subagent.called.data.remote.url` records the target. A failed _start_ comes back as a failed tool result, so the caller can explain or recover within the same session. Terminal callback delivery runs as a durable Workflow step on the callee: a failed callback POST is rethrown rather than marking the task complete, which puts redelivery under Workflow retry policy.+The parent stream carries the same `subagent.called`, `action.result`, and `subagent.completed` events as local delegation. For a remote call, `subagent.called.data.remote.url` records the target.++Both failure paths surface to the parent as a failed tool result, so the caller can explain or recover within the same session. A failed _start_ returns the error inline. A remote that starts and then fails posts a terminal failure callback, which the parent receives as an errored subagent result carrying the remote's error (or `REMOTE_AGENT_FAILED` when none is supplied). Terminal callback delivery runs as a durable step on the underlying workflow engine (see [Execution model & durability](../concepts/execution-model-and-durability)). A failed callback POST is rethrown rather than marking the task complete, so the engine retries it.## What to read nextdiff --git a/docs/guides/session-context.md b/docs/guides/session-context.mdindex 3cda64651..c8dc9dd94 100644--- a/docs/guides/session-context.md+++ b/docs/guides/session-context.md@@ -10,11 +10,11 @@ Eve exposes runtime state through the `ctx` parameter passed to tool `execute`,- `ctx.getSkill(identifier)`: handle for a named skill visible to the current agent- `defineState(name, initial)`: typed durable state with `get()` and `update()` (imported from `eve/context`)-These APIs work only inside active authored runtime execution such as tools, channel event handlers, and authored hooks. They throw when called outside a managed context.+These APIs work only inside active authored runtime execution, including tools, channel event handlers, and authored hooks. They throw when called outside a managed context.## `ctx.session`-Use `ctx.session` when you need durable runtime metadata about the current execution.+`ctx.session` exposes durable runtime metadata about the current execution.```ts title="agent/tools/who_called_me.ts"import { defineTool } from "eve/tools";@@ -46,7 +46,7 @@ Public session fields:- `turn.sequence`- optional `parent`-Important behavior:+Behavior:- `auth.current` is the caller for the active inbound turn.- `auth.initiator` is the caller that started the durable session.@@ -63,14 +63,14 @@ const sandbox = await ctx.getSandbox();const result = await sandbox.run({ command: "npm test" });```-Important behavior:+Behavior:-- It takes no arguments: each agent has exactly one sandbox.+- It takes no arguments. Each agent has exactly one sandbox.- It is async because Eve binds or restores sandbox state lazily.- It only works when sandbox access is attached to the active runtime path.-- Visibility is node-local: a subagent sees its own sandbox, not the parent's.+- Visibility is node-local. A subagent sees its own sandbox, not the parent's.-`SandboxSession` also exposes `resolvePath(path)` for cases where authored code needs the live backend-native path for a logical `/workspace/...` location before passing it to shell code or a child process.+`SandboxSession` also exposes `resolvePath(path)`, which returns the live backend-native path for a logical `/workspace/...` location. Use it when authored code needs that path before passing it to shell code or a child process.See [Sandbox](../sandbox) for lifecycle details.@@ -83,20 +83,20 @@ const skill = ctx.getSkill("research");const notes = await skill.file("references/checklist.md").text();```-Important behavior:+Behavior:-- It is synchronous; file content is read lazily from the active sandbox.+- It is synchronous. File content is read lazily from the active sandbox.- It only works when sandbox access is attached to the active runtime path.- `identifier` is the path-derived skill id.- Visibility follows the current agent's sandbox.-- Missing skills surface when a file accessor reads a missing sandbox path.+- A missing skill surfaces when a file accessor reads a missing sandbox path.- The returned handle exposes `name` and `file(relativePath)`.See [Skills](../skills) for the full authoring model.## Custom state with `defineState`-Use `defineState` when your agent needs durable typed state that tools, hooks, and channel handlers can share. State survives across workflow step boundaries. Declare the handle at module scope so every importer shares it:+Use `defineState` when your agent needs durable typed state that tools, hooks, and channel handlers can share. State survives workflow step boundaries. Declare the handle at module scope so every importer shares it:```ts title="agent/lib/budget.ts"import { defineState } from "eve/context";@@ -139,7 +139,7 @@ The framework sets up a context container before invoking authored code:3. Authored code runs inside the managed scope, so `ctx` and `defineState` accessors resolve automatically.4. After the step, the framework commits mutable state (for example sandbox changes) back to the durable session.-This lifecycle is fully managed by the framework. Authored code only needs to use `ctx` and the public accessors.+The framework manages this lifecycle. Authored code only uses `ctx` and the public accessors.## What to read nextdiff --git a/docs/guides/state.md b/docs/guides/state.mdindex 425c412fd..601deda95 100644--- a/docs/guides/state.md+++ b/docs/guides/state.md@@ -3,7 +3,7 @@ title: "State"description: "Durable per-session memory with defineState: get() and update(), persisted across step boundaries."----`defineState` is a typed, named slot of durable per-session memory for an agent. Use it when the agent has to remember something between the turns of a conversation (a running budget, a glossary, a checklist) and you don't want to stand up an external store for it. The values survive workflow step boundaries, so they outlast crashes, redeploys, and days-long sessions.+`defineState` is a typed, named slot of durable per-session memory for an agent. Use it when the agent has to remember something between conversation turns (a running budget, a glossary, a checklist) and you don't want to stand up an external store for it. The values survive workflow step boundaries, so they outlast crashes, redeploys, and days-long sessions.```tsimport { defineState } from "eve/context";@@ -16,14 +16,19 @@ Pass `defineState(name, initial)` a stable string `name` (namespace it to your a- `get()`: read the current value. Returns `initial()` on first access within a context.- `update(fn)`: replace the value with `fn(current)`.-Use the handle from inside a tool, hook, or other framework-managed runtime code:+Declare the handle once at module scope and import it wherever you read or write the slot. Use it from inside a tool, hook, or other framework-managed runtime code:-```ts title="agent/tools/spend.ts"+```ts title="agent/lib/budget.ts"import { defineState } from "eve/context";++export const budget = defineState("my-agent.budget", () => ({ count: 0, cap: 25 }));+```++```ts title="agent/tools/spend.ts"import { defineTool } from "eve/tools";import { z } from "zod";--const budget = defineState("my-agent.budget", () => ({ count: 0, cap: 25 }));+import { budget } from "../lib/budget.js";+import { runQuery } from "../lib/warehouse.js";export default defineTool({description: "Run a query, counting it against the session budget.",@@ -43,20 +48,31 @@ export default defineTool({State is durable by default and does not reset between turns. If you want a clean slate every turn, overwrite it from a lifecycle [hook](./hooks) on `turn.started`:-```ts-budget.update(() => ({ count: 0, cap: 25 }));+```ts title="agent/hooks/reset-budget.ts"+import { defineHook } from "eve/hooks";+import { budget } from "../lib/budget.js";++export default defineHook({+ events: {+ async "turn.started"() {+ budget.update(() => ({ count: 0, cap: 25 }));+ },+ },+});```+The hook imports the same module-scope `budget` handle as the tool, so both read and write the same slot.+## State is never shared with subagentsEvery [subagent](../subagents) starts with its own fresh state, whether it's a built-in `agent` copy or a declared specialist. `defineState` values never cross the parent/child boundary, even when the child is a copy of the same agent.## State vs. connection-side storage-`defineState` is for conversation-scoped working memory that lives and dies with the session: counters, the current plan, what the user has told you this conversation. Anything that has to outlive the session, be shared across sessions or users, or be queried independently of a turn belongs in an external store, either a [connection](../connections) or your own database. State is not a database. It's the agent's short-term memory, persisted durably for the life of the session.+`defineState` holds conversation-scoped working memory that lives and dies with the session, including counters, the current plan, and what the user has told you this conversation. It is the agent's short-term memory, persisted durably for the life of the session. Anything that has to outlive the session, be shared across sessions or users, or be queried independently of a turn belongs in an external store, either a [connection](../connections) or your own database.## What to read next- Read state inside dynamic resolvers → [Dynamic capabilities](./dynamic-capabilities)- How step durability works → [Execution model & durability](../concepts/execution-model-and-durability)-- The `ctx` accessors available alongside state → [Tools](../tools)+- The `ctx` accessors available alongside state → [TypeScript API](../reference/typescript-api)diff --git a/docs/instructions.mdx b/docs/instructions.mdxindex c39160d69..f6a84fb29 100644--- a/docs/instructions.mdx+++ b/docs/instructions.mdx@@ -3,19 +3,17 @@ title: "Instructions"description: "Author the agent's always-on system prompt with instructions.md or instructions.ts."----Instructions are the always-on system prompt. Use them for whatever should hold on every turn: a rule, a persona, a constraint. This is the agent's permanent identity, not a procedure it pulls in when the moment calls for it.--Eve prepends the instructions to every model call in the session.+Instructions are the always-on system prompt, the agent's permanent identity rather than a procedure it pulls in when the moment calls for it. Use them for anything that should hold on every turn, such as a rule, a persona, or a constraint. Eve prepends the instructions to every model call in the session.## Author instructions-In the simplest case, instructions are a markdown file at the agent root. Whatever you write is the prompt.+At minimum, instructions are a markdown file at the agent root. Whatever you write is the prompt:```md title="agent/instructions.md"You are a concise assistant. Use tools when they are available.```-Keep this file to stable behavior that applies on every turn: identity, tone, standing rules.+Keep this file to stable behavior such as identity, tone, and standing rules.## Markdown vs TypeScript@@ -30,11 +28,15 @@ export default defineInstructions({});```-`defineInstructions` takes one field, `markdown`, which is the resolved prompt text. A module-backed prompt runs once at build time. Eve captures the resulting markdown into the compiled manifest, so the runtime serves the same prompt every session and never re-runs the module.+`defineInstructions` takes one field, `markdown`, the resolved prompt text. A module-backed prompt runs once at build time. Eve captures the resulting markdown into the compiled manifest, so the runtime serves the same prompt every session and never re-runs the module.++## Split instructions across a directory++For more than one file, add an `agent/instructions/` directory. Eve reads its entries non-recursively and accepts both `.md` files and `.ts` modules (a `.ts` file can wrap `defineInstructions` or `defineDynamic`). Entries combine in alphabetical order by filename (`localeCompare`).-Got more than one file? An `agent/instructions/` directory works too. Use either `instructions.md` or `instructions.ts` at the agent root, not both.+A flat `agent/instructions.md` (or `.ts`) at the agent root and the directory can coexist. The root file's content comes first, then the sorted directory entries. You cannot author both `instructions.md` and `instructions.ts` at the root; that pairing is a build error.-## How it differs from skills+## Instructions vs skillsInstructions and [skills](./skills) both feed text into the model's context. The difference is timing:@@ -43,13 +45,13 @@ Instructions and [skills](./skills) both feed text into the model's context. The| `instructions.md` / `.ts` | Always on, every turn | Permanent identity and standing rules || `agent/skills/*` | On demand, when the model calls `load_skill` | Optional procedures that should not bloat every turn |-Keep instructions short and stable. Long or situational procedures belong in skills, where they only enter context when the request calls for them. See [Skills](./skills).+Keep instructions short and stable. Long or situational procedures belong in [skills](./skills), where they only enter context when the request calls for them.Instructions never run code. When you need typed executable behavior, reach for a [tool](./tools).## Dynamic instructions-Need the prompt resolved at runtime from session context (auth, tenant, channel)? Wrap `defineInstructions` in a `defineDynamic` resolver. See [Dynamic capabilities](./guides/dynamic-capabilities).+To resolve the prompt at runtime from session context (auth, tenant, or channel), wrap `defineInstructions` in a `defineDynamic` resolver. See [Dynamic capabilities](./guides/dynamic-capabilities).## What to read nextdiff --git a/docs/introduction.md b/docs/introduction.mdindex 724cdb638..772fd5f24 100644--- a/docs/introduction.md+++ b/docs/introduction.md@@ -5,7 +5,7 @@ description: "How an Eve agent is laid out as files, what runs when a message arEve is a framework for building durable agents as ordinary files in a TypeScript project.-Instead of describing your whole agent in one large configuration object, you give each part a clear home: instructions go in one file, tools in one folder, channels in another. Eve discovers that structure and turns it into an agent that runs locally, serves HTTP, connects to other platforms, and keeps working across many turns.+Instead of one large configuration object, each part of your agent gets a clear home. Instructions go in one file, tools in one folder, channels in another. Eve discovers that structure and turns it into an agent that runs locally, serves HTTP, connects to other platforms, and keeps working across many turns.## An Eve project at a glance@@ -37,9 +37,7 @@ Start with only `instructions.md` and `agent.ts`. Add the other folders when the## The files are the interface-Eve is [filesystem-first](./reference/project-layout): a file's location says what it does, and its path usually gives it a name.--For example, this file:+Eve is [filesystem-first](./reference/project-layout). A file's location says what it does, and its path usually gives it a name. For example, this file:```textagent/tools/get_weather.ts@@ -64,7 +62,7 @@ There is no separate registry to keep in sync. Add the file and Eve discovers it## What happens when a message arrives-Whether a message comes from a web app, the terminal, or Slack, the same flow runs. Eve turns the platform input into a message, gives the model its instructions, skills, tools, and conversation history, runs the work (calling tools and subagents as needed), saves the session and streams events, then delivers the result back in the form the platform expects.+The same flow runs whether a message comes from a web app, the terminal, or Slack. Eve turns the platform input into a message, gives the model its instructions, skills, tools, and conversation history, runs the work (calling tools and subagents as needed), saves the session and streams events, then delivers the result back in the form the platform expects.That keeps agent behavior portable. Your weather tool does not need to know whether the question came from a browser or from Slack.@@ -72,13 +70,13 @@ That keeps agent behavior portable. Your weather tool does not need to know whetAn Eve session is more than one request and one response. It can:-- stream progress while work is happening-- call tools and subagents-- pause for [approval or a human answer](./tools)-- resume after that answer arrives-- keep durable state across turns+- Stream progress while work is happening+- Call tools and subagents+- Pause for [approval or a human answer](./tools)+- Resume after that answer arrives+- Keep durable state across turns-Under the hood, Eve uses the open-source [Workflow SDK](https://workflow-sdk.dev) to make sessions durable, resumable, and crash-safe. Eve handles that machinery so your tools can focus on the work itself.+Under the hood, Eve uses the open-source [Workflow SDK](https://workflow-sdk.dev) to make sessions durable, resumable, and crash-safe. Eve handles that machinery so your tools focus on the work itself.## Grow the project by adding capabilities@@ -93,7 +91,7 @@ As the agent grows, each concern still has a predictable home:| [`schedules/`](./schedules) | Recurring or scheduled work || `lib/` | Shared code imported by the other agent files |-The result stays readable before it runs: the directory tells you what the agent can do.+The result stays readable before it runs. The directory tells you what the agent can do.## What to read nextdiff --git a/docs/reference/cli.md b/docs/reference/cli.mdindex 50b101e3a..a21ce07ad 100644--- a/docs/reference/cli.md+++ b/docs/reference/cli.md@@ -1,38 +1,57 @@---title: "CLI"-description: "eve command reference: info, build, start, dev, eval."+description: "Reference for every eve CLI command: init, info, build, start, dev, link, deploy, eval, and channels."----The `eve` binary (`bin: eve`) runs from your app root, and every command loads `.env`/`.env.local` from that root before it does anything else.+The `eve` binary (`bin: eve`) runs from your app root, and every command first loads `.env`/`.env.local` from that root. Running `eve` with no command runs `eve dev`.## Commands-| Command | Does |-| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |-| `eve info` | Print the resolved application: discovered tools, skills, subagents, schedules, channels, routes, artifact paths, and discovery diagnostics |-| `eve build` | Compile `.eve/` artifacts and build the host output; prints the output directory |-| `eve start` | Serve the built `.output/` app; prints the listening URL |-| `eve dev` | Start the local dev server and open the terminal UI |-| `eve dev <url>` | Connect the UI to an existing server URL (e.g. a remote deployment) instead of booting a local server |-| `eve link` | Link the directory to a Vercel project and pull AI Gateway credentials |-| `eve deploy` | Deploy the agent to Vercel production (links first if needed) |-| `eve eval` | Run evals against the local app or a remote target |-| `eve channels add [kind]` | Scaffold a channel interactively, or by kind (`slack` \| `web`) |-| `eve channels list` | List user-authored channels |+| Command | Description |+| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |+| `eve init [target]` | Scaffold a new agent, or add one to an existing project directory |+| `eve info` | Print the resolved application, including discovered tools, skills, subagents, schedules, channels, routes, artifact paths, and discovery diagnostics |+| `eve build` | Compile `.eve/` artifacts and build the host output; prints the output directory |+| `eve start` | Serve the built `.output/` app; prints the listening URL |+| `eve dev` | Start the local dev server and open the terminal UI |+| `eve dev <url>` | Connect the UI to an existing server URL (e.g. a remote deployment) instead of booting a local server |+| `eve link` | Link the directory to a Vercel project and pull AI Gateway credentials |+| `eve deploy` | Deploy the agent to Vercel production (links first if needed) |+| `eve eval` | Run evals against the local app or a remote target |+| `eve channels add [kind]` | Scaffold a channel interactively, or by kind (`slack` \| `web`) |+| `eve channels list` | List user-authored channels |When `eve build` fails on discovery errors, it prints the full diagnostics report (severity, message, source path) and the diagnostics artifact path.+## `eve init`++```bash+eve init [target] [--channel-web-nextjs]+```++The optional `target` decides the mode:++- A name (`eve init my-agent`) scaffolds a fresh project in a new `my-agent/` directory.+- An existing directory, including `.` for the current one (`eve init .`), adds an agent to that project. The project needs a `package.json`, the `agent/` files must not exist yet, and the missing `eve`, `ai`, and `zod` dependencies are added without touching anything else.+- Omitting the target scaffolds or updates the current directory, the same as `eve init .`.++Either mode installs dependencies, initializes Git, and runs `eve dev` through the project's package manager.++| Flag | Type | Default | Description |+| ---------------------- | ---- | ------- | -------------------------------------------------------------------------------------------------------------------------------------- |+| `--channel-web-nextjs` | flag | off | Add the Web Chat application (a Next.js app). Rejected when adding to an existing project; run `eve channels add web` there afterward. |+## `eve info````basheve info [--json]```-| Flag | Effect |-| -------- | ------------ |-| `--json` | Emit as JSON |+| Flag | Type | Default | Description |+| -------- | ---- | ------- | ------------ |+| `--json` | flag | off | Emit as JSON |-When something behaves unexpectedly, run this first. It confirms a file was discovered, lists the active surface, and surfaces discovery diagnostics, all faster than booting the dev server.+Run this first when something behaves unexpectedly. It confirms a file was discovered, lists the active surface, and surfaces discovery diagnostics, all faster than booting the dev server.## `eve build`@@ -44,7 +63,7 @@ No flags. Compiles to `.eve/` and builds the host output, then prints the builtUseful artifacts written under `.eve/` (preserved even on partial failure):-| Artifact | Tells you |+| Artifact | Description || ---------------------------------------------- | ---------------------------------------------------- || `.eve/discovery/agent-discovery-manifest.json` | What Eve found on disk || `.eve/discovery/diagnostics.json` | Authored-shape errors and warnings |@@ -58,10 +77,10 @@ Useful artifacts written under `.eve/` (preserved even on partial failure):eve start [--host <host>] [--port <port>]```-| Flag | Effect |-| --------------- | ---------------------------------------------------- |-| `--host <host>` | Host interface to bind |-| `--port <port>` | Port to listen on (defaults to `$PORT`, then `3000`) |+| Flag | Type | Default | Description |+| --------------- | ------ | ------------------ | ---------------------- |+| `--host <host>` | string | all interfaces | Host interface to bind |+| `--port <port>` | number | `$PORT`, then 3000 | Port to listen on |Serves the previously built output. Prints the listening URL.@@ -72,27 +91,27 @@ eve dev [options]eve dev https://your-app.vercel.app```-Pass a bare URL as the only argument and the UI connects to that server instead of booting a local one (same as `--url`). That's handy for smoke-testing a preview or production deployment. The interactive UI turns off in a non-TTY terminal.--| Flag | Effect |-| ----------------------------------- | ----------------------------------------------------------------------------------------- |-| `--host <host>` | Host interface to bind |-| `--port <port>` | Port to listen on (defaults to `$PORT`, then `2000`) |-| `-u, --url <url>` | Connect to an existing server URL instead of starting one |-| `--no-ui` | Start the server without an interactive UI |-| `--name <name>` | Title shown in the terminal UI (defaults to the app folder name) |-| `--input <text>` | Pre-fill the prompt input after launching the UI (editable; not auto-submitted) |-| `--tools <mode>` | Tool-call rendering: `full` \| `collapsed` \| `auto-collapsed` \| `hidden` |-| `--reasoning <mode>` | Reasoning rendering: `full` \| `collapsed` \| `auto-collapsed` \| `hidden` |-| `--subagents <mode>` | Subagent-section rendering: `full` \| `collapsed` \| `auto-collapsed` \| `hidden` |-| `--connection-auth <mode>` | Connection-authorization rendering: `full` \| `collapsed` \| `auto-collapsed` \| `hidden` |-| `--assistant-response-stats <mode>` | Assistant header statistic: `tokens` \| `tokensPerSecond` |-| `--context-size <tokens>` | Model context window size, shown as a usage percentage |-| `--logs <mode>` | Server/agent logs to show: `all` \| `stderr` \| `sandbox` \| `none` |+Pass a bare URL as the only argument and the UI connects to that server instead of booting a local one (same as `--url`), which lets you smoke-test a preview or production deployment. The interactive UI turns off in a non-TTY terminal.++| Flag | Type | Default | Description |+| ----------------------------------- | ------ | ------------------ | ----------------------------------------------------------------------------------------- |+| `--host <host>` | string | all interfaces | Host interface to bind |+| `--port <port>` | number | `$PORT`, then 3000 | Port to listen on |+| `-u, --url <url>` | string | none | Connect to an existing server URL instead of starting one |+| `--no-ui` | flag | UI on | Start the server without an interactive UI |+| `--name <name>` | string | app folder name | Title shown in the terminal UI |+| `--input <text>` | string | none | Pre-fill the prompt input after launching the UI (editable, not auto-submitted) |+| `--tools <mode>` | enum | `auto-collapsed` | Tool-call rendering: `full` \| `collapsed` \| `auto-collapsed` \| `hidden` |+| `--reasoning <mode>` | enum | `full` | Reasoning rendering: `full` \| `collapsed` \| `auto-collapsed` \| `hidden` |+| `--subagents <mode>` | enum | `auto-collapsed` | Subagent-section rendering: `full` \| `collapsed` \| `auto-collapsed` \| `hidden` |+| `--connection-auth <mode>` | enum | `full` | Connection-authorization rendering: `full` \| `collapsed` \| `auto-collapsed` \| `hidden` |+| `--assistant-response-stats <mode>` | enum | `tokensPerSecond` | Assistant header statistic: `tokens` \| `tokensPerSecond` |+| `--context-size <tokens>` | number | none | Model context window size, shown as a usage percentage |+| `--logs <mode>` | enum | `stderr` | Server/agent logs to show: `all` \| `stderr` \| `sandbox` \| `none` |Local dev writes the active server process ID to `.eve/dev-process.pid`. If another `eve dev` starts for the same agent while that process is still running, Eve exits with a message that includes the command to stop the existing server.-Local dev keeps immutable runtime source snapshots under `.eve/dev-runtime/snapshots/` so in-flight sessions keep a consistent code revision while new prompts pick up rebuilds. `eve dev` prunes stale runtime snapshots and old local sandbox templates in the background on startup; stopping `eve dev` and deleting `.eve/dev-runtime/snapshots/` or `.eve/sandbox-cache/local/templates/` is safe when you want a manual cleanup.+Local dev keeps immutable runtime source snapshots under `.eve/dev-runtime/snapshots/` so in-flight sessions hold a consistent code revision while new prompts pick up rebuilds. On startup, `eve dev` prunes stale runtime snapshots and old local sandbox templates in the background. For manual cleanup, stop `eve dev` and delete `.eve/dev-runtime/snapshots/` or `.eve/sandbox-cache/local/templates/`.## `eve link`@@ -100,7 +119,7 @@ Local dev keeps immutable runtime source snapshots under `.eve/dev-runtime/snapseve link```-Links the current directory to an existing Vercel project by selecting a team and then a project, then pulls the project's environment so an AI Gateway credential (`VERCEL_OIDC_TOKEN` or `AI_GATEWAY_API_KEY`) lands in `.env.local`, and verifies one actually did. Running it again re-links: the pickers always run, and the new choice wins. Interactive only — in CI, use `vercel link --project <name> --yes` instead. A running `eve dev` reloads env files automatically, so no restart is needed after the pull.+Links the current directory to an existing Vercel project. You select a team and then a project, and Eve pulls the project's environment so an AI Gateway credential (`VERCEL_OIDC_TOKEN` or `AI_GATEWAY_API_KEY`) lands in `.env.local`, then verifies one actually did. Running it again re-links: the pickers always run, and the new choice wins. The command is interactive only; in CI, use `vercel link --project <name> --yes` instead. A running `eve dev` reloads env files automatically, so you don't need to restart after the pull.## `eve deploy`@@ -108,7 +127,7 @@ Links the current directory to an existing Vercel project by selecting a team aneve deploy```-Deploys the agent to Vercel production (`vercel deploy --prod`), installing dependencies first and pulling environment variables after. An already-linked project deploys with or without a TTY (non-interactive runs pass the non-interactive `vercel` flags); an unlinked directory walks the `eve link` pickers when a terminal is present, and exits with guidance otherwise.+Deploys the agent to Vercel production (`vercel deploy --prod`), installing dependencies first and pulling environment variables after. An already-linked project deploys with or without a TTY (non-interactive runs pass the non-interactive `vercel` flags). An unlinked directory walks the `eve link` pickers when a terminal is present, and exits with guidance otherwise.## `eve eval`@@ -118,19 +137,46 @@ eve eval [evalId...] [--url <url>] [options]Runs all discovered evals when no eval ids are given; ids match exactly or by directory prefix (`eve eval weather` runs everything under `evals/weather/`). Exits `0` when every eval passed its checks, `1` when any eval failed (a failed check, an execution error, or a `--strict` threshold miss), `2` on configuration errors.-| Flag | Effect |-| ----------------------- | ---------------------------------------------- |-| `--url <url>` | Remote agent URL (skip local host startup) |-| `--tag <tag...>` | Run only evals carrying a tag |-| `--strict` | Below-threshold scores also fail the exit code |-| `--list` | Print discovered evals without running them |-| `--timeout <ms>` | Per-eval timeout in milliseconds |-| `--max-concurrency <n>` | Max concurrent eval executions (default 8) |-| `--json` | Output results as JSON |-| `--skip-report` | Skip eval-defined reporters (e.g. Braintrust) |+| Flag | Type | Default | Description |+| ----------------------- | ------ | ------- | ---------------------------------------------- |+| `--url <url>` | string | none | Remote agent URL (skip local host startup) |+| `--tag <tag...>` | string | none | Run only evals carrying a tag |+| `--strict` | flag | off | Below-threshold scores also fail the exit code |+| `--list` | flag | off | Print discovered evals without running them |+| `--timeout <ms>` | number | none | Per-eval timeout in milliseconds |+| `--max-concurrency <n>` | number | 8 | Max concurrent eval executions |+| `--json` | flag | off | Output results as JSON |+| `--junit <path>` | string | none | Write JUnit XML results to a file |+| `--skip-report` | flag | off | Skip eval-defined reporters (e.g. Braintrust) |+| `--verbose` | flag | off | Stream per-eval `t.log` lines to stdout |See [Evals](../evals/overview) for authoring evals.+## `eve channels add`++```bash+eve channels add [kind] [-f] [-y]+```++Scaffolds a channel into `agent/channels/`. With no `kind` it prompts interactively; pass a `kind` (`slack` \| `web`) to scaffold one directly.++| Flag | Type | Default | Description |+| ------------- | ---- | ------- | --------------------------------------------------------- |+| `-f, --force` | flag | off | Overwrite existing channel files |+| `-y, --yes` | flag | off | Assume yes for confirmations; requires an explicit `kind` |++## `eve channels list`++```bash+eve channels list [--json]+```++Lists the user-authored channels in the current project.++| Flag | Type | Default | Description |+| -------- | ---- | ------- | -------------- |+| `--json` | flag | off | Output as JSON |+## Recommended loop1. Edit files under `agent/`.diff --git a/docs/reference/meta.json b/docs/reference/meta.jsonindex 95edf9b9e..c667486ff 100644--- a/docs/reference/meta.json+++ b/docs/reference/meta.json@@ -1,4 +1,4 @@{"title": "Reference",- "pages": ["typescript-api", "cli", "project-layout"]+ "pages": ["http-api", "typescript-api", "cli", "project-layout"]}diff --git a/docs/reference/project-layout.md b/docs/reference/project-layout.mdindex a5a24b6ce..10e9a797e 100644--- a/docs/reference/project-layout.md+++ b/docs/reference/project-layout.md@@ -9,14 +9,14 @@ Eve builds an agent by walking the filesystem under `agent/`. Each directory isIdentity comes from the path. You never write a `name` or `id` field on a `define*` call.-| Path | Becomes |+| Path | Resolves to || ------------------------------------- | --------------------- || `agent/tools/get_weather.ts` | tool `get_weather` || `agent/connections/linear.ts` | connection `linear` || `agent/skills/summarize.md` | skill `summarize` || `agent/subagents/researcher/agent.ts` | subagent `researcher` |-The root agent takes its name from the enclosing `package.json` `name`. A subagent takes its name from its directory.+The root agent takes its name from the enclosing `package.json` `name`, falling back to the app-root directory name when `package.json` has no `name`. A subagent takes its name from its directory.## Recommended layout@@ -24,38 +24,43 @@ The root agent takes its name from the enclosing `package.json` `name`. A subagemy-agent/├── package.json├── tsconfig.json-└── agent/- ├── agent.ts- ├── instructions.md- ├── instrumentation.ts- ├── channels/- ├── connections/- ├── hooks/- ├── skills/- ├── lib/- ├── sandbox/- ├── tools/- ├── schedules/- └── subagents/+├── agent/+│ ├── agent.ts+│ ├── instructions.md+│ ├── instrumentation.ts+│ ├── channels/+│ ├── connections/+│ ├── hooks/+│ ├── skills/+│ ├── lib/+│ ├── sandbox/+│ ├── tools/+│ ├── schedules/+│ └── subagents/+└── evals/```+Evals live in `evals/` at the app root, a sibling of `agent/`, not inside it. See [Evals](../evals/overview).+## Slot table-| Path | Holds | Notes |-| ------------------------------------------------------- | ------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `agent.ts` | Runtime config | Model, modelOptions, compaction, build, experimental. See [Agent config](../agent-config). |-| `instructions.md` / `instructions.ts` / `instructions/` | Base system prompt | A flat file, or a directory of `.md` and `.ts` files. Static sources compose at build time. Dynamic sources (`defineDynamic` + `defineInstructions`) resolve at runtime. |-| `instrumentation.ts` | Telemetry config | OTel exporter and AI SDK span settings; auto-discovered and run before agent code. |-| `channels/` | HTTP / messaging entrypoints | Root-only today. |-| `connections/` | External service connections (MCP, OpenAPI) | One connection per file; name derived from filename. |-| `hooks/` | Lifecycle and stream-event subscribers | Module-backed only. Recursive directories supported. |-| `skills/` | On-demand procedures and capability packs | Flat markdown, module-backed skills, or packaged skills. Seeded into `/workspace/skills/...`. |-| `lib/` | Shared authored helper code | Import-only; not mounted into the workspace. |-| `sandbox.ts` or `sandbox/sandbox.ts` | The agent's single sandbox | Use top-level `sandbox.ts` for a definition-only override; use `sandbox/sandbox.ts` + `sandbox/workspace/**` to also seed files. Framework default applies when neither is authored. Supported on root and local subagents. |-| `sandbox/workspace/**` | Files seeded into the sandbox | Mirrored into `/workspace/...` at session bootstrap. |-| `tools/` | Typed executable integrations | Module-backed only. |-| `schedules/` | Recurring jobs | Each schedule is `<name>.ts` (default-exported `defineSchedule`) or `<name>.md` (frontmatter `cron:` + prompt body). Recursive nesting supported. Root-only today. |-| `subagents/` | Specialist child agents | Each child is its own local package under `subagents/<id>/`. |+The Subagents column states whether a local subagent (`subagents/<id>/`) can author the slot. A declared subagent inherits nothing from the root; it discovers its own slots. See [Subagents](../subagents).++| Path | Description | Subagents | Notes |+| ------------------------------------------------------- | ------------------------------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `agent.ts` | Runtime config | Yes | Model, modelOptions, compaction, build, experimental. See [Agent config](../agent-config). |+| `instructions.md` / `instructions.ts` / `instructions/` | Base system prompt | Optional | A flat file, or a directory of `.md` and `.ts` files. Static sources compose at build time. Dynamic sources (`defineDynamic` + `defineInstructions`) resolve at runtime. Required on the root, optional on subagents. |+| `instrumentation.ts` | Telemetry config | No | OTel exporter and AI SDK span settings, auto-discovered and run before agent code. Root-only. |+| `channels/` | HTTP / messaging entrypoints | No | Root-only. |+| `connections/` | External service connections (MCP, OpenAPI) | Yes | One connection per file; name derived from filename. |+| `hooks/` | Lifecycle and stream-event subscribers | Yes | Module-backed only. Recursive directories supported. |+| `skills/` | On-demand procedures and capability packs | Yes | Flat markdown, module-backed skills, or packaged skills. Seeded into `/workspace/skills/...`. |+| `lib/` | Shared authored helper code | Yes | Import-only; not mounted into the workspace. |+| `sandbox.ts` or `sandbox/sandbox.ts` | The agent's single sandbox | Yes | Use top-level `sandbox.ts` for a definition-only override; use `sandbox/sandbox.ts` + `sandbox/workspace/**` to also seed files. Framework default applies when neither is authored. |+| `sandbox/workspace/**` | Files seeded into the sandbox | Yes | Mirrored into `/workspace/...` at session bootstrap. |+| `tools/` | Typed executable integrations | Yes | Module-backed only. |+| `schedules/` | Recurring jobs | No | Each schedule is `<name>.ts` (default-exported `defineSchedule`) or `<name>.md` (frontmatter `cron:` + prompt body). Recursive nesting supported. Root-only. |+| `subagents/` | Specialist child agents | Yes | Each child is its own local package under `subagents/<id>/`. Nested subagents are supported. |## What reaches the runtime workspace@@ -74,6 +79,7 @@ A local subagent lives under `subagents/<id>/` and uses the same `agent.ts` shapagent/subagents/researcher/├── agent.ts├── instructions.md+├── connections/├── hooks/├── skills/├── lib/@@ -86,7 +92,8 @@ Rules:- `agent.ts` is required, and must declare a `description`. The parent reads it on the lowered subagent tool to decide when to delegate.- `instructions.md` / `instructions.ts` is optional (unlike the root agent, where it is required).-- `channels/` and `schedules/` are not supported inside local subagents today.+- `connections/`, `hooks/`, `skills/`, `lib/`, `sandbox/`, and `tools/` are all supported, discovered from the subagent's own directory.+- `channels/` and `schedules/` are not supported inside local subagents.- Nested subagents are supported.## Flat layout@@ -106,7 +113,7 @@ Prefer the nested layout. It keeps the app root separate from the authored surfa## Why didn't Eve discover my file?-Run `eve info`. It lists the discovered surface and prints discovery diagnostics. From there, check that the file sits in the right authored slot (per the slot table above) and that the root-vs-subagent boundary is valid. Eve also writes inspectable artifacts under `.eve/` — see the debugging artifacts in [instrumentation.ts](../guides/instrumentation) and the [CLI](./cli) reference.+Run `eve info`. It lists the discovered surface and prints discovery diagnostics. From there, check that the file sits in the right authored slot (per the slot table above) and that the root-vs-subagent boundary is valid. Eve also writes inspectable artifacts under `.eve/`. See the debugging artifacts in [instrumentation.ts](../guides/instrumentation) and the [CLI](./cli) reference.## What to read nextdiff --git a/docs/reference/typescript-api.md b/docs/reference/typescript-api.mdindex b47c78a88..e1ca0a4c0 100644--- a/docs/reference/typescript-api.md+++ b/docs/reference/typescript-api.md@@ -54,7 +54,7 @@ A few non-`define*` helpers round out the set: `disableTool` and `ExperimentalWo## Runtime context (`ctx`)-`ctx` is passed to your tool `execute`, hook handlers, and channel event handlers. It is live only while authored code is actually running, so reaching for it at module top level throws. See [Session context](../guides/session-context) for the full model.+`ctx` is passed to your tool `execute`, hook handlers, and channel event handlers. It is live only while authored code is running, so reaching for it at module top level throws. See [Session context](../guides/session-context) for the full model.| Member | Use || -------------------------- | ----------------------------------------------------------------------------- |diff --git a/docs/sandbox.mdx b/docs/sandbox.mdxindex 79bdc5a76..a12c7cde7 100644--- a/docs/sandbox.mdx+++ b/docs/sandbox.mdx@@ -1,11 +1,11 @@---title: "Sandbox"-description: "The agent's isolated bash environment: built-in file tools, a seeded /workspace, backends, lifecycle, and network policy."+description: "The agent's isolated bash environment, including built-in file tools, a seeded /workspace, backends, lifecycle, and network policy."---The sandbox is the agent's isolated bash environment: a filesystem rooted at `/workspace` where it can run shell commands, execute scripts, and read or write files without ever touching your app runtime. Every Eve agent has exactly one. The built-in `bash`, `read_file`, `write_file`, `glob`, and `grep` tools already target it, and your authored code can too.-You author nothing for the agent to have a working sandbox; it exists by default. Override it only when you need to add setup, seed files, pick a backend, or lock down the network.+A working sandbox exists by default, with nothing to author. Override it only to add setup, seed files, pick a backend, or lock down the network.## Using the sandbox@@ -18,7 +18,7 @@ The model already has shell and file access through the default tools:| `glob` | find files by pattern || `grep` | search file contents |-All of them run with `/workspace` as the working directory. Any authored runtime function (a tool, a step, a model callback) can grab a live sandbox handle with `ctx.getSandbox()`.+All of them run with `/workspace` as the working directory. Any authored runtime function (a tool, a step, a model callback) can get a live sandbox handle with `ctx.getSandbox()`.```ts title="agent/tools/run_analysis.ts"import { defineTool } from "eve/tools";@@ -38,7 +38,7 @@ export default defineTool({`ctx.getSandbox()` takes no arguments, is async, and only works inside authored runtime execution.-`/workspace` is one namespace across every backend, so `/workspace/foo` points at the same file whether the backend is local or Vercel. When you need to interpolate a path into a generated command, `sandbox.resolvePath("repo/build.py")` anchors a relative path to its absolute `/workspace/repo/build.py` form. `readFile`, `writeFile`, and `run` do the same anchoring internally.+`/workspace` is one namespace across every backend, so `/workspace/foo` points at the same file whether the backend is local or Vercel. When you need to interpolate a path into a generated command, `sandbox.resolvePath("repo/build.py")` anchors a relative path to its absolute `/workspace/repo/build.py` form.The handle does more than `run` and `writeTextFile`. In every method, relative paths resolve from `/workspace` and absolute paths pass through untouched:@@ -53,7 +53,7 @@ The handle does more than `run` and `writeTextFile`. In every method, relative p| `resolvePath(path)` | anchor a relative path to its absolute `/workspace/...` form || `setNetworkPolicy(policy)` | change egress policy mid-turn (backend-dependent; see [Network policy](#network-policy)) |-Since `run` blocks until the command exits, reach for `spawn` when the process should keep running while the agent does other work:+Since `run` blocks until the command exits, use `spawn` when the process should keep running while the agent does other work:```tsconst sandbox = await ctx.getSandbox();@@ -66,7 +66,7 @@ A `SandboxProcess` exposes `stdout`/`stderr` byte streams, `wait()` (resolves wi`sandbox.id` is a stable per-session identifier that persists across reconnects to the same logical session. Use it as the cache key for per-session state that must outlive individual step executions.-The option types (`SandboxSpawnOptions`, `SandboxReadBinaryFileOptions`, `SandboxWriteBinaryFileOptions`, and so on) are named-exported from `eve/sandbox` alongside `SandboxProcess`.+The option types (`SandboxSpawnOptions`, `SandboxReadBinaryFileOptions`, `SandboxWriteBinaryFileOptions`, and so on) are named exports from `eve/sandbox`, alongside `SandboxProcess`.## Seeding `/workspace`@@ -80,7 +80,7 @@ agent/sandbox/scripts/run.sh ← lands at /workspace/scripts/run.sh```-Every file under `workspace/` mirrors into the sandbox cwd with its structure intact, and Eve lists the top-level entries to the model in the prompt automatically. One subtree is off limits: skill discovery already seeds skill files under `/workspace/skills/`, so authoring `agent/sandbox/workspace/skills/...` is rejected. Put those under `agent/skills/` instead.+Every file under `workspace/` mirrors into the sandbox cwd with its structure intact, and Eve lists the top-level entries to the model in the prompt automatically. One subtree is off limits. Skill discovery already seeds skill files under `/workspace/skills/`, so authoring `agent/sandbox/workspace/skills/...` is rejected; put those under `agent/skills/` instead.## Overriding the sandbox@@ -117,14 +117,14 @@ The backend decides where the sandbox runs. Eve ships four pinned factories from| `vercel()` | on [Vercel Sandbox](https://vercel.com/docs/sandbox). || `docker()` | locally in a Docker container, driven through the `docker` CLI. || `microsandbox()` | locally in a lightweight [microsandbox](https://www.npmjs.com/package/microsandbox) VM. |-| `justbash()` | locally in the pure-JS `just-bash` interpreter — no daemon or VM, but no real binaries either. |+| `justbash()` | locally in the pure-JS `just-bash` interpreter (no daemon or VM, but no real binaries either). || `defaultBackend()` | picks the best available: Vercel Sandbox on hosted Vercel → Docker → microsandbox → just-bash. |-Configuring a pinned factory uses that backend unconditionally — `docker()` always requires a reachable Docker daemon, `vercel()` always creates hosted sandboxes (including from local dev, with Vercel credentials).+Configuring a pinned factory uses that backend unconditionally. `docker()` always requires a reachable Docker daemon, and `vercel()` always creates hosted sandboxes (including from local dev, with Vercel credentials).With `backend` omitted, Eve uses `defaultBackend()`, which resolves on first use in priority order:-1. **Vercel Sandbox** when deploying on Vercel (`process.env.VERCEL` is set) — local container/VM runtimes can't run there.+1. **Vercel Sandbox** when deploying on Vercel (`process.env.VERCEL` is set), since local container/VM runtimes can't run there.2. **Docker** when a daemon is reachable through a Docker-compatible `docker` CLI (Docker Desktop, OrbStack, Colima, Podman via its docker-compatible CLI; override the binary with `EVE_DOCKER_PATH`).3. **microsandbox** when the host supports it: macOS on Apple Silicon, or glibc Linux with KVM enabled.4. **just-bash** as the dependency-free fallback.@@ -145,24 +145,24 @@ export default defineSandbox({### Docker-`docker()` drives the Docker CLI directly. The default base image is `ghcr.io/vercel/eve:latest`, Eve's published sandbox runtime image; Eve creates `/workspace` and verifies Bash during framework setup before authored bootstrap code runs. Configure it through `docker({ image, env, pullPolicy, networkPolicy })`; install authored runtime tools in sandbox bootstrap or provide them through a custom image. Templates are committed as local Docker images and reused across sessions when the sandbox source, seed files, `revalidationKey`, and Docker backend options still match; sessions run as long-lived containers whose filesystems persist `/workspace` changes across turns for the same durable session. `eve dev` prunes stale template images in the background.+`docker()` drives the Docker CLI directly. The default base image is `ghcr.io/vercel/eve:latest`, Eve's published sandbox runtime image. Eve creates `/workspace` and verifies Bash during framework setup, before authored bootstrap code runs. Configure it through `docker({ image, env, pullPolicy, networkPolicy })`, and install authored runtime tools in sandbox bootstrap or provide them through a custom image. Templates are committed as local Docker images and reused across sessions when the sandbox source, seed files, `revalidationKey`, and Docker backend options still match. Sessions run as long-lived containers whose filesystems persist `/workspace` changes across turns for the same durable session. `eve dev` prunes stale template images in the background.### microsandbox-`microsandbox()` runs each sandbox in a lightweight local VM with snapshot-backed templates, a `vercel-sandbox` user, and a firewall capable of domain-level network policies and credential brokering — the closest local match to hosted Vercel Sandbox. The default base image is `ghcr.io/vercel/eve:latest`, Eve's published sandbox runtime image; Eve verifies Bash, creates `/workspace`, and creates the sandbox user during framework setup before authored bootstrap code runs. Install authored runtime tools in sandbox bootstrap or provide them through a custom image. Supported hosts: macOS on Apple Silicon, or Linux (glibc) with KVM. The `microsandbox` npm package and its VM runtime are not bundled with Eve: `eve dev` installs both automatically when missing (disable with `setup: { autoInstall: false }`); production processes fail with actionable install errors instead.+`microsandbox()` runs each sandbox in a lightweight local VM with snapshot-backed templates, a `vercel-sandbox` user, and a firewall capable of domain-level network policies and credential brokering. It is the closest local match to hosted Vercel Sandbox. The default base image is `ghcr.io/vercel/eve:latest`, Eve's published sandbox runtime image. During framework setup, before authored bootstrap code runs, Eve verifies Bash and creates `/workspace` and the sandbox user. Install authored runtime tools in sandbox bootstrap or provide them through a custom image. Supported hosts are macOS on Apple Silicon, or Linux (glibc) with KVM. The `microsandbox` npm package and its VM runtime are not bundled with Eve, so `eve dev` installs both automatically when missing (disable with `setup: { autoInstall: false }`); production processes fail with actionable install errors instead.### just-bash-`justbash()` needs no daemon or VM, but commands run in a simulated bash with a virtual filesystem under `.eve/sandbox-cache/` — no real binaries (`git`, `node`, package managers) and no network isolation. The `just-bash` package is an optional peer dependency: `eve dev` installs it into your application automatically when missing (disable with `autoInstall: false`); production processes fail with an actionable install error instead.+`justbash()` needs no daemon or VM, but commands run in a simulated bash with a virtual filesystem under `.eve/sandbox-cache/`, with no real binaries (`git`, `node`, package managers) and no network isolation. The `just-bash` package is an optional peer dependency, so `eve dev` installs it into your application automatically when missing (disable with `autoInstall: false`); production processes fail with an actionable install error instead.-You can write your own backend too: a `SandboxBackend` is just an object with a `name`, a `create`, and an optional `prewarm`. See the `SandboxBackend*` types on `eve/sandbox`.+You can also write your own backend. A `SandboxBackend` is an object with a `name`, a `create`, and an optional `prewarm`. See the `SandboxBackend*` types on `eve/sandbox`.## LifecycleThere are two hooks, scoped differently:-- **`bootstrap({ use })`** is template-scoped and runs once when the template is built. Put reusable setup here, the kind every later session inherits: clone a baseline repo, install dependencies, seed files. Call `use()` to get a `SandboxSession`. Only template filesystem state and supported backend metadata carry into later sessions; config like network policy does not. If external inputs affect what bootstrap produces, set `revalidationKey: () => string` so Eve knows when to rebuild the template (authored sandbox source and seed contents are already tracked for you).-- **`onSession({ use, ctx })`** is durable-session-scoped and runs once per session. This is where per-session setup goes: network policy, resources, timeout, per-user credentials, one-time markers. Because it runs inside the active runtime context, it can read `ctx.session` and derive the current principal without baking credentials into the template. Call `use(opts?)` to get a `SandboxSession`; `opts` flow to the backend's update path after create.+- **`bootstrap({ use })`** is template-scoped and runs once when the template is built. Put reusable setup here that every later session inherits, such as cloning a baseline repo, installing dependencies, or seeding files. Call `use()` to get a `SandboxSession`. Only template filesystem state and supported backend metadata carry into later sessions; config like network policy does not. If external inputs affect what bootstrap produces, set `revalidationKey: () => string` so Eve knows when to rebuild the template (authored sandbox source and seed contents are already tracked for you).+- **`onSession({ use, ctx })`** is durable-session-scoped and runs once per session. Put per-session setup here, including network policy, resources, timeout, per-user credentials, and one-time markers. Because it runs inside the active runtime context, it can read `ctx.session` and derive the current principal without baking credentials into the template. Call `use(opts?)` to get a `SandboxSession`; `opts` flow to the backend's update path after create.```tsimport { defineSandbox } from "eve/sandbox";@@ -179,7 +179,7 @@ export default defineSandbox({});```-Sessions are persistent. When the VM shuts down (timeout, default 30 minutes), the filesystem is preserved and the sandbox resumes on the next message as if nothing happened, even days later.+Sessions are persistent, and how the underlying runtime idles out depends on the backend. On the Vercel backend, the VM times out after a period of inactivity (default 30 minutes); Eve preserves the filesystem and resumes the sandbox on the next message as if nothing happened, even days later. The Docker backend keeps a long-lived container per durable session and persists `/workspace` across turns without that timeout, and the just-bash backend stores its virtual filesystem under `.eve/sandbox-cache/`. In every case, `/workspace` survives between turns for the same session.## Network policy@@ -195,7 +195,7 @@ networkPolicy: {};```-Set it on the factory (`vercel({ networkPolicy: "deny-all" })`) and it applies before authored `bootstrap` code runs; framework-owned base setup may briefly keep egress open to install required packages. Set it in `onSession`'s `use()` to override per-session. The common pattern combines both: leave the factory open so `bootstrap` can `git clone`, then lock down in `onSession`. And to change the policy mid-turn, call `sandbox.setNetworkPolicy(...)` on the live handle.+Set it on the factory (`vercel({ networkPolicy: "deny-all" })`) and it applies before authored `bootstrap` code runs; framework-owned base setup may briefly keep egress open to install required packages. Set it in `onSession`'s `use()` to override per-session. The common pattern combines both: leave the factory open so `bootstrap` can `git clone`, then lock down in `onSession`. To change the policy mid-turn, call `sandbox.setNetworkPolicy(...)` on the live handle.Domain-level allow-lists and credential brokering are supported by `vercel()` and `microsandbox()`. The Docker backend honors only `"allow-all"` and `"deny-all"` (at creation and via `setNetworkPolicy`); the just-bash backend rejects `setNetworkPolicy` entirely.@@ -208,7 +208,7 @@ async onSession({ use }) {await use({networkPolicy: {allow: {- "github.com": [{ transform: [{ headers: { authorization: "Basic …" } }] }],+ "github.com": [{ transform: [{ headers: { authorization: "Basic your_base64_credentials_here" } }] }],"*": [],},},diff --git a/docs/schedules.mdx b/docs/schedules.mdxindex 667c6f7a7..c9635c460 100644--- a/docs/schedules.mdx+++ b/docs/schedules.mdx@@ -1,9 +1,9 @@---title: "Schedules"-description: "Run an agent on a cron cadence: a fire-and-forget prompt, or a handler that hands work off to a channel."+description: "Run an agent on a cron cadence, either a fire-and-forget prompt or a handler that hands work off to a channel."----A schedule is how the agent starts work on its own clock instead of waiting for an inbound message. Daily digests, data syncs, cleanup sweeps, heartbeats: anything that should fire on a cadence. Each one is a single file under `agent/schedules/` carrying a cron expression. Schedules are root-only, so declared subagents cannot have a `schedules/` directory.+A schedule starts the agent on its own clock instead of waiting for an inbound message. Use one for daily digests, data syncs, cleanup sweeps, heartbeats, or anything that should fire on a cadence. Each one is a single file under `agent/schedules/` carrying a cron expression. Schedules are root-only, so declared subagents cannot have a `schedules/` directory.The name comes from the path under `schedules/` (`agent/schedules/billing/sweep.ts` → `"billing/sweep"`), and nested directories are fine.@@ -25,11 +25,13 @@ interface ScheduleHandlerArgs {}```-`defineSchedule` is just a pass-through for types. The compiler is what enforces the one-of rule.+`defineSchedule` is a type-level pass-through. The compiler is what enforces the one-of rule.++`cron` is a standard 5-field string (`minute hour day-of-month month day-of-week`) with minute granularity. On Vercel, each schedule becomes a Vercel Cron Job, and Vercel evaluates the expression in UTC, so `"0 9 * * 1-5"` fires at 09:00 UTC on weekdays. `eve dev` never fires schedules on their cron cadence. To trigger one while iterating, use the dispatch route below.## Markdown form (fire-and-forget)-This is the minimal schedule. Eve runs the agent on the prompt and throws away the output, though the agent can still call tools, write to backends, and log along the way. We call this task mode. A task-mode session runs to completion or fails; it cannot park to wait for a person or an OAuth sign-in.+This is the minimal schedule. Eve runs the agent on the prompt and throws away the output, though the agent can still call tools, write to backends, and log along the way. We call this task mode. A task-mode session runs to completion or fails, and cannot park to wait for a person or an OAuth sign-in.```ts title="agent/schedules/heartbeat.ts"import { defineSchedule } from "eve/schedules";@@ -54,7 +56,7 @@ Sweep stale workflow state.## Handler form (`run`)-Reach for a handler when the schedule needs to deliver to a channel, branch on conditions, or compute its arguments at fire time. The handler is in full control. It has no channel of its own, so it passes the work to one with `receive`.+Use a handler when the schedule needs to deliver to a channel, branch on conditions, or compute its arguments at fire time. The handler is in full control. It has no channel of its own, so it passes the work to one with `receive`.```ts title="agent/schedules/daily-digest.ts"import { defineSchedule } from "eve/schedules";@@ -75,30 +77,30 @@ export default defineSchedule({});```-- `receive(channel, { message, target, auth })`: starts a session on another channel. Same contract as a route handler’s `args.receive`.-- `waitUntil(promise)`: extends the cron task’s lifetime so the parked session and any in-flight fetches settle before the task ends. Wrap the `receive` call in it.+- `receive(channel, { message, target, auth })`: starts a session on another channel. Same contract as a route handler's `args.receive`.+- `waitUntil(promise)`: extends the cron task's lifetime so the parked session and any in-flight fetches settle before the task ends. Wrap the `receive` call in it.- `appAuth`: the app principal (`{ authenticator: "app", principalId: "eve:app", principalType: "runtime" }`). Pass it as `receive(..., { auth: appAuth })` for work the agent does on its own behalf.-A handler-form session runs on the same durable runtime engine as any other session, so it can park, for instance when the channel handoff is waiting for a Slack reply. Only markdown task mode is barred from waiting.+A handler-form session runs on the same durable runtime engine as any other session, so it can park (durably suspend), for instance when the channel handoff is waiting for a Slack reply. Only markdown task mode is barred from waiting.## Trigger a schedule while iterating-In production the cron cadence is the only thing that fires a schedule, but waiting for the next tick gets old fast while iterating in `eve dev`. So the dev server mounts a one-shot dispatch route: fire a schedule by name, out of band, exactly once.+The dev server mounts a one-shot dispatch route that fires a schedule by name, out of band, exactly once. Since `eve dev` never runs schedules on their cron cadence, this is how you trigger one without waiting for the next production tick.```sh-curl -X POST http://localhost:2000/eve/v1/dev/schedules/heartbeat+curl -X POST http://localhost:3000/eve/v1/dev/schedules/heartbeat# -> { "scheduleId": "heartbeat", "sessionIds": ["..."] }```-`:scheduleId` is the path-derived schedule name (`agent/schedules/heartbeat.ts` → `heartbeat`; URL-encode the `/` in nested names). It runs the exact dispatch path the production cron handler uses and returns the started session ids as JSON, so you can subscribe to each one’s [stream](./concepts/sessions-runs-and-streaming) at `GET /eve/v1/session/:sessionId/stream`. An unknown id comes back `404` with `availableScheduleIds`, listing the schedules the app actually defines.+`:scheduleId` is the path-derived schedule name (`agent/schedules/heartbeat.ts` → `heartbeat`; URL-encode the `/` in nested names). It runs the exact dispatch path the production cron handler uses and returns the started session ids as JSON, so you can subscribe to each one's [stream](./concepts/sessions-runs-and-streaming) at `GET /eve/v1/session/:sessionId/stream`. An unknown id comes back `404` with `availableScheduleIds`, listing the schedules the app actually defines.The route is dev-only. Production builds never mount it, and it needs no auth since the dev server is local-only.## On Vercel-Hosted Vercel builds turn every `defineSchedule(...)` into a Vercel Cron Job, with each `cron` written as an entry in `.vercel/output/config.json`. Confirm discovery under Settings → Cron Jobs and watch execution history under Observability → Cron Jobs. Per-run logs land under Observability → Logs.+Hosted Vercel builds turn every `defineSchedule(...)` into a Vercel Cron Job, with each `cron` written as an entry in `.vercel/output/config.json`. Vercel evaluates these expressions in UTC. Confirm discovery under **Settings → Cron Jobs** and watch execution history under **Observability → Cron Jobs**. Per-run logs land under **Observability → Logs**.## What to read next-- Deliver schedule output to users → [Channels](./channels/overview)-- Inspect a schedule run → [Sessions, runs & streaming](./concepts/sessions-runs-and-streaming)+- [Channels](./channels/overview): deliver schedule output to users.+- [Sessions, runs & streaming](./concepts/sessions-runs-and-streaming): inspect a schedule run.diff --git a/docs/skills.mdx b/docs/skills.mdxindex 5e85bd1fb..fc2c5bbee 100644--- a/docs/skills.mdx+++ b/docs/skills.mdx@@ -3,7 +3,7 @@ title: "Skills"description: "Author load-on-demand procedures the model pulls into context with load_skill."----A skill is a model-loadable procedure that follows the `SKILL.md` convention: a markdown document (optionally a packaged directory with supporting files) that the model pulls into context on demand rather than carrying on every turn. Eve advertises each skill's description, and the model loads the full body only when a turn calls for it, the progressive-disclosure model the broader Agent Skills standard uses. A skill authored against that standard ports over as-is.+A skill is a model-loadable procedure that follows the `SKILL.md` convention. It is a markdown document, optionally a packaged directory with supporting files, that the model pulls into context on demand rather than carrying on every turn. Eve advertises each skill's description, and the model loads the full body only when a turn calls for it. This is progressive disclosure, the same model the broader Agent Skills standard uses, so a skill authored against that standard ports over as-is.## How loading works@@ -25,11 +25,11 @@ The smallest skill is a flat markdown file. The content is the procedure, and thUse the weather tool before answering forecast or temperature questions.```-A packaged skill is a directory: a `SKILL.md` plus sibling files like `references/`, `assets/`, and `scripts/`. The packaged `SKILL.md` must carry `description` frontmatter. Flat markdown skills may skip it.+A flat markdown skill can skip the `description` frontmatter. When it does, Eve advertises the first non-empty, non-code-fence line of the body with any leading `#`, `>`, `*`, or `-` marker stripped. If the body has no such line, Eve falls back to the literal `Instructions for the <name> skill.`, which is a weak routing hint, so add a `description` when you want the model to route on intent.-`agent/skills/research/SKILL.md`:+A packaged skill is a directory with a `SKILL.md` plus sibling files like `references/`, `assets/`, and `scripts/`. The packaged `SKILL.md` must carry `description` frontmatter; it has no filename slug to fall back on.-```md+```md title="agent/skills/research/SKILL.md"---description: Research unfamiliar topics before answering with confidence.---@@ -55,7 +55,9 @@ export default defineSkill({Eve generates `SKILL.md` from `markdown`, and each `files` entry becomes a package-relative sibling. Start with plain markdown and move to `defineSkill` only when you hit its limits.-Skills are scoped to the agent that declares them. A [subagent](./subagents)'s `skills/` are invisible to the root agent, and the reverse holds too. There's no shared-skill mechanism, so when you want to share executable helpers, put them in `lib/`.+## Skills are scoped per agent++Skills are scoped to the agent that declares them. A [subagent](./subagents)'s `skills/` are invisible to the root agent, and the reverse holds too. There's no shared-skill mechanism, so put shared executable helpers in `lib/`.## Read skill files at runtime@@ -70,7 +72,7 @@ The handle exposes the skill's `name` and `file(relativePath)`; file content is## Dynamic skills-Want a different skill per principal, tenant, or channel, like the caller's own team playbook? Wrap `defineSkill` in a `defineDynamic` resolver keyed on `ctx.session.auth`. See [Dynamic capabilities](./guides/dynamic-capabilities).+To serve a different skill per principal, tenant, or channel (the caller's own team playbook, say), wrap `defineSkill` in a `defineDynamic` resolver keyed on `ctx.session.auth`. See [Dynamic capabilities](./guides/dynamic-capabilities).## What to read nextdiff --git a/docs/subagents.mdx b/docs/subagents.mdxindex 19b4f3d3a..30f0256c7 100644--- a/docs/subagents.mdx+++ b/docs/subagents.mdx@@ -1,9 +1,9 @@---title: "Subagents"-description: "Delegate work to child agents: a copy of the agent itself, or declared specialists with their own sandbox and skills."+description: "Delegate work to child agents, either a copy of the agent itself or declared specialists with their own sandbox and skills."----A subagent is a child agent that one agent delegates a focused subtask to. Split work out into one when you want it to run in parallel, when the child should see a narrower set of tools, or when a specialist needs its own identity. There are two kinds.+A subagent is a child agent that one agent delegates a focused subtask to. Split work into one to run it in parallel, to give the child a narrower set of tools, or to give a specialist its own identity. There are two kinds, the built-in `agent` tool (a copy of the agent itself) and declared subagents (specialists with their own directory).## The built-in `agent` tool@@ -16,7 +16,7 @@ Every agent gets an `agent` tool by default. The model calls it to delegate a su}```-The copy shares the parent's sandbox and tools. A child's file writes are immediately visible to the parent, which is what makes parallel calls natural: fan out a few copies to fix different files at once. The copy inherits auth and connections, but starts with fresh conversation history and fresh state. If a declared subagent calls `agent`, the child is a copy of _that_ subagent, not the root.+The copy shares the parent's sandbox and tools, and a child's file writes are immediately visible to the parent. That is what makes parallel calls natural: fan out a few copies to fix different files at once. The copy inherits auth and connections, but starts with fresh conversation history and fresh state. If a declared subagent calls `agent`, the child is a copy of _that_ subagent, not the root.An authored tool at `agent/tools/agent.ts` takes priority over the built-in.@@ -47,30 +47,52 @@ agent/subagents/researcher/└── subagents/ # optional, nested subagents```-`schedules/` is not supported inside a declared subagent: schedules are root-only.+`schedules/` is not supported inside a declared subagent. Schedules are root-only.## The isolation boundary-A declared subagent gets its own independent sandbox and its own `skills/` set. Neither crosses the parent boundary:+A declared subagent inherits nothing from the root's authored slots. Discovery treats its directory as its own agent root, so it has only the instructions, tools, connections, skills, sandbox, hooks, and nested subagents authored under `agent/subagents/<id>/`. An absent slot falls back to the framework default, not to the root's version.-- The child sees only skills authored under `agent/subagents/<id>/skills/`. Root `agent/skills/` stay out of reach during its turns. When two subagents need the same procedure, duplicate the markdown under each, or share typed helpers via `lib/`.-- The child's sandbox does not inherit from the parent. It falls back to the framework default unless it authors `subagents/<id>/sandbox.ts`, or seeds files via `subagents/<id>/sandbox/workspace/`.+| Slot | Built-in `agent` tool | Declared subagent |+| ------------ | ----------------------------- | -------------------------------------- |+| Instructions | Inherited (copy of the agent) | Own `instructions.{md,ts}`, optional |+| Tools | Inherited | Own `tools/` |+| Connections | Inherited | Own `connections/` |+| Skills | Inherited | Own `skills/` |+| Sandbox | Shared with parent | Own `sandbox/`, else framework default |+| Hooks | Inherited | Own `hooks/` |+| State | Fresh | Fresh |+| Channels | Root-only | Root-only |+| Schedules | Root-only | Root-only |-The built-in `agent` tool is the exception: its children share the parent's sandbox and tools because they are copies of the same agent working on the same files.+For a declared subagent this means duplicating anything the child needs. When two subagents need the same procedure, copy the markdown under each `skills/` directory, or share typed helpers via `lib/`. The sandbox does not inherit from the parent; it falls back to the framework default unless the subagent authors `subagents/<id>/sandbox.ts` or seeds files via `subagents/<id>/sandbox/workspace/`.-`defineState` is never shared, for either kind: each child starts with fresh durable state.+The built-in `agent` tool is the exception. Its children share the parent's sandbox and tools because they are copies of the same agent working on the same files.++`defineState` is never shared, for either kind. Each child starts with fresh durable state.## What the parent sees-Eve lowers every subagent (built-in copy, declared, or [remote](./guides/remote-agents)) into a model-visible tool with the same `{ message, outputSchema? }` shape. The parent packs `message` with everything the child needs, since the child never sees the parent's history. Set `outputSchema` and the child runs in task mode, returning structured output as the tool result.+Eve lowers every subagent (built-in copy, declared, or [remote](./guides/remote-agents)) into a model-visible tool with the same `{ message, outputSchema? }` shape. The parent packs `message` with everything the child needs, since the child never sees the parent's history. Set `outputSchema` to run the child in task mode, returning structured output as the tool result.++A declared subagent's tool name is the bare path-derived name, with no prefix. `agent/subagents/researcher/` registers as the tool `researcher`. Unlike connection tools (`connection__<connection>__<tool>`), it carries no namespace, so the model, approvals, logs, and evals all reference it by that name. Its input schema is:++```ts+{+ message: string; // all context the child needs; it never sees the parent's history+ outputSchema?: object; // when set, the child runs in task mode and returns structured output+}+```++Because the name lives in the same runtime tool namespace as authored tools, a subagent named `researcher` collides with a tool named `researcher`. Eve rejects the build rather than picking a winner, so keep subagent directory names distinct from tool names.Each delegated subagent spins up its own child session and stream. The parent stream carries only the control-plane events `subagent.called` and `subagent.completed`. To follow the child's full progress, read `subagent.called.data.childSessionId` and subscribe at `GET /eve/v1/session/:childSessionId/stream`.## When to split-Split out a subagent when the task needs a different prompt or specialist role, a narrower tool surface, or its own runtime context. Don't reach for one when a [skill](./skills) would do: if the agent can keep its identity and just needs an optional procedure, a skill is the lighter choice.+Split out a subagent when the task needs a different prompt or specialist role, a narrower tool surface, or its own runtime context. Don't reach for one when a [skill](./skills) would do. If the agent can keep its identity and needs only an optional procedure, a skill is the lighter choice.## What to read next-- Call another Eve deployment as a subagent → [Remote agents](./guides/remote-agents)-- Have the model orchestrate its subagents programmatically (fan-out, map-reduce) → [Dynamic workflows](./guides/dynamic-workflows)+- [Remote agents](./guides/remote-agents): call another Eve deployment as a subagent.+- [Dynamic workflows](./guides/dynamic-workflows): have the model orchestrate its subagents programmatically (fan-out, map-reduce).diff --git a/docs/tools.mdx b/docs/tools.mdxindex d4fd17d45..47aa8f249 100644--- a/docs/tools.mdx+++ b/docs/tools.mdx@@ -3,7 +3,7 @@ title: "Tools"description: "Define typed actions the agent can call, and gate sensitive ones on human approval."----A tool is a typed action the agent can call: hit an API, run a query, write a file. The action stays in code you control. Tools run in your app runtime (full `process.env`), not the [sandbox](./sandbox).+A tool is a typed action the agent can call, such as hitting an API, running a query, or writing a file. The action stays in code you control. Tools run in your app runtime with full access to `process.env`, not in the [sandbox](./sandbox).## Define a tool@@ -33,7 +33,7 @@ When a tool returns structured data, add an optional `outputSchema`. With Zod or### The `ctx` parameter-`execute` gets a `ctx` carrying the runtime accessors you'll reach for:+`execute` gets a `ctx` carrying the runtime accessors:- `ctx.session`: session metadata, turn, auth, parent lineage.- `ctx.getSandbox()`: the live [sandbox](./sandbox) handle.@@ -41,13 +41,13 @@ When a tool returns structured data, add an optional `outputSchema`. With Zod orRunning in the app runtime is what lets a tool import shared code from `lib/`, read `process.env`, and take part in Eve’s durable pause/resume model.-Eve never runs authored tools during discovery: the model sees descriptors first, and only what it actually calls gets executed. Re-executing a step from the same input is idempotent, so tool side effects are not duplicated when a turn resumes after a crash.+Eve never runs authored tools during discovery. The model sees descriptors first, and only what it actually calls gets executed. Completed steps never re-run; Eve replays the recorded result. A step interrupted mid-execution re-runs, so make non-idempotent side effects like charges or emails idempotent, or gate them with approval.## Human-in-the-loop-HITL is not a separate system. It is just a tool that pauses for a person before (or instead of) running. Gate one on approval with `needsApproval` and the helpers from `eve/tools/approval`:+Human-in-the-loop (HITL) approval is a property of a tool that pauses for a person before (or instead of) running. Gate a tool on approval with `needsApproval` and the helpers from `eve/tools/approval`:-```ts+```ts title="agent/tools/refund_charge.ts"import { defineTool } from "eve/tools";import { always } from "eve/tools/approval";import { z } from "zod";@@ -68,13 +68,13 @@ export default defineTool({| `once()` | Require approval only the first time the tool runs in a session; auto-allow after. || `always()` | Require approval before every call. |-When the decision depends on the input, pass your own predicate instead of a helper. It receives `{ toolName, toolInput, approvedTools }` and returns a boolean. To require approval only when an amount crosses a threshold:+When the decision depends on the input, pass your own predicate instead of a helper. It receives `{ toolName, toolInput, approvedTools }` and returns a boolean. `toolInput` can be undefined, so guard the access. To require approval only when an amount crosses a threshold:```ts-needsApproval: ({ toolInput }) => toolInput.amount > 1000,+needsApproval: ({ toolInput }) => (toolInput?.amount ?? 0) > 1000,```-### The pause and resume+### How approval pause and resume worksApprovals and questions share one protocol:@@ -97,7 +97,7 @@ toModelOutput(output) {},```-It receives the full, typed `execute` return and only affects the model. Channel event handlers and hooks still get the full output on `action.result`, so a channel can render rich platform output (Slack Block Kit, say) the model never sees. Return `{ type: "text", value }` for a summary, or `{ type: "json", value }` for a smaller object.+`toModelOutput` receives the full, typed `execute` return and only affects the model. Channel event handlers and hooks still get the full output on `action.result`, so a channel can render rich platform output (Slack Block Kit, say) the model never sees. Return `{ type: "text", value }` for a summary, or `{ type: "json", value }` for a smaller object.## What to read nextdiff --git a/docs/tutorial/connect-a-warehouse.mdx b/docs/tutorial/connect-a-warehouse.mdxindex fb0b42924..ee41b05b3 100644--- a/docs/tutorial/connect-a-warehouse.mdx+++ b/docs/tutorial/connect-a-warehouse.mdx@@ -1,9 +1,11 @@----title: "Step 4: Connect a Warehouse"-description: "Let each user connect their own warehouse over an OAuth MCP via Vercel Connect."+title: "Connect a Warehouse"+description: "Part 4 of the Build an Agent tutorial. Let each user connect their own warehouse over an OAuth MCP via Vercel Connect."----The sample dataset got you running, but it's a stand-in. The next step is to point the agent at a real warehouse and let each user connect their own by signing in through their browser. That's what a connection is for: an MCP server the model reaches through tools, with auth that Eve drives for you.+The sample dataset got the analytics assistant running, but it's a stand-in. Now point the agent at a real warehouse and let each user connect their own by signing in through their browser. That's what a connection is for. It's an MCP server the model reaches through tools, with auth that Eve drives for you.++This step depends on Vercel Connect, which is in private beta. No Connect access? Keep the Step 3 sample dataset and read this step for the connection model. Steps 5 through 9 work against the sample dataset, so you can complete the tutorial without a warehouse.The filename sets the runtime name. Put the file at `agent/connections/warehouse.ts` and it registers as `"warehouse"`, with its tools surfaced as `connection__warehouse__<tool>`.@@ -24,7 +26,14 @@ export default defineMcpClientConnection({`"warehouse"` is the UID you chose when registering the Connect client. By default this OAuth is user-scoped. Each end-user authorizes in their own browser, and Eve resolves that user's token before every tool call.-Connect is in private beta. Once enabled: `npm install @vercel/connect`, create the Connect client (`vercel connect create <type> --name warehouse`), link it to your project, then `vercel link` and `vercel env pull` so `VERCEL_OIDC_TOKEN` is available locally. Full setup: [Connections](../connections).+Once Connect is enabled on your account, wire it up:++1. Install the package: `npm install @vercel/connect`.+2. Create the Connect client: `vercel connect create <type> --name warehouse`.+3. Link the client to your project.+4. Run `vercel link` and `vercel env pull` so `VERCEL_OIDC_TOKEN` is available locally.++For the full reference, see [Connections](../connections).## What the user sees@@ -34,7 +43,7 @@ Ask a question that needs the warehouse:How many enterprise customers signed up last month?```-The first time around, the model picks a warehouse tool but there's no token yet. So the turn parks and the channel shows a “Sign in” affordance. You authorize in the browser, and once the OAuth callback completes, the turn resumes from exactly that step (the durable parking from [Step 2](./how-it-runs)) and the query runs. Later calls in the session reuse the cached per-user token, so there's no prompt.+The first time, the model picks a warehouse tool but there's no token yet, so the turn parks and the channel shows a "Sign in" affordance. You authorize in the browser, and once the OAuth callback completes, the turn resumes from exactly that step (the durable parking from [Step 2](./how-it-runs)) and the query runs. Later calls in the session reuse the cached per-user token, so there's no prompt.## The token never reaches the model@@ -42,6 +51,6 @@ Right before each request to the MCP server, Eve resolves the bearer and sends iIf you want more control, gate the connection behind approval (`approval: once()`) or narrow which tools the model sees (`tools.allow`). See [Connections](../connections).-→ Next: [Step 5: Run analysis](./run-analysis)+→ Next: [Run analysis](./run-analysis)-Depth: [Connections](../connections) · [Auth & route protection](../guides/auth-and-route-protection)+Learn more: [Connections](../connections) · [Auth and route protection](../guides/auth-and-route-protection)diff --git a/docs/tutorial/first-agent.mdx b/docs/tutorial/first-agent.mdxindex 28ba740b1..6a1c35976 100644--- a/docs/tutorial/first-agent.mdx+++ b/docs/tutorial/first-agent.mdx@@ -1,22 +1,32 @@----title: "Step 1: Your First Agent"-description: "Scaffold the analytics assistant, give it an analyst persona, run it, and ask a question."+title: "Your First Agent"+description: "Part 1 of the Build an Agent tutorial. Scaffold the analytics assistant, give it an analyst persona, run it, and ask a question."----This tutorial builds one app end to end: a data analytics assistant. You ask in natural language, and over the next nine steps it learns to query a warehouse, run analysis in a sandbox, remember your team’s metric definitions, and refuse to torch your query budget without asking.+The Build an Agent tutorial constructs one app end to end, a data analytics assistant. You ask in natural language, and over the next nine steps it learns to query a warehouse, run analysis in a sandbox, remember your team's metric definitions, and refuse to exceed your query budget without asking.Step 1 gets it talking. The scaffold bundles a small sample dataset, so your first question works with zero setup.-## Scaffold+## Prerequisites++- Node 24 or newer and npm.+- A model credential. The scaffold's default model goes through the [Vercel AI Gateway](../getting-started), so you need `AI_GATEWAY_API_KEY` (or `VERCEL_OIDC_TOKEN` pulled via `vercel link`). A direct provider id like `anthropic/claude-opus-4.8` instead needs that provider's key, here `ANTHROPIC_API_KEY`.++If you have not run Eve before, complete [Getting Started](../getting-started) first. Without a credential, "Run the agent" below fails when the runtime tries to reach the model; the dev TUI's `/model` flow walks you through pasting a key or linking a project.++## Scaffold the agent```bashnpx eve@latest init analytics-assistant+cd analytics-assistant```The command writes the starter agent with Eve's default model and built-in HTTP APIchannel (`agent/channels/eve.ts`), installs dependencies, initializes Git, andstarts the development server. Stop the server before continuing with the edits-below. It does not create a Vercel project or deploy.+below. It does not create a Vercel project or deploy. `init` creates the+`analytics-assistant/` directory, so `cd` into it before running further+commands.## Set the model@@ -45,20 +55,20 @@ You are a senior data analyst. You answer questions about the team's data.Instructions are identity and standing rules. On-demand procedures belong in skills (Step 7), and actions belong in tools (Step 3). See [Instructions](../instructions).-## Run it+## Run the agent```bash-eve dev+npm run dev```-The local runtime boots and the dev TUI opens. Ask it something it can answer from general knowledge first:+The `init` scaffold writes a `dev` script that runs the `eve dev` binary from the project's `node_modules`. The local runtime boots and the dev TUI opens. Ask it something it can answer from general knowledge first:```textWhat's a good way to measure week-over-week retention?```-You’ll get a reply that follows the analyst persona. It can’t see your data yet (that’s Step 3). First, a look at what just happened under the hood.+You get a reply that follows the analyst persona. It can't see your data yet (that comes in Step 3). First, a look at what happened under the hood.-→ Next: [Step 2: How it runs](./how-it-runs)+→ Next: [How it runs](./how-it-runs)-Depth: [Getting Started](../getting-started) · [Instructions](../instructions)+Learn more: [Getting Started](../getting-started) · [Instructions](../instructions)diff --git a/docs/tutorial/guard-the-spend.mdx b/docs/tutorial/guard-the-spend.mdxindex 36d5feec8..db92bb9ac 100644--- a/docs/tutorial/guard-the-spend.mdx+++ b/docs/tutorial/guard-the-spend.mdx@@ -1,15 +1,17 @@----title: "Step 8: Guard the Spend"-description: "Gate expensive queries with cost-based approval: the agent pauses, asks, and resumes."+title: "Guard the Spend"+description: "Part 8 of the Build an Agent tutorial. Gate expensive queries with cost-based approval. The agent pauses, asks, and resumes."----A single warehouse query can scan terabytes and bill you for the privilege. So before the agent fires off an expensive scan, make it stop and check with you: for a costly query, the agent pauses, asks you, and resumes with your answer. That's human-in-the-loop, and you wire it up with one field on the tool.+A single warehouse query can scan terabytes and run up the bill. So before the analytics assistant fires off an expensive scan, make it stop and check with you. The agent pauses, asks you, and resumes with your answer. That's human-in-the-loop, and you wire it up with one field on the tool.`needsApproval` runs before `execute`. Return `true` and the turn parks on an approval request; you answer, and the run picks up from that exact step. The function gets the tool input, so you can make the decision cost-based.## Estimate, then gate-Add a cheap estimator (a real warehouse exposes a dry-run byte estimate, so keep the helper illustrative) and gate `run_sql` on it:+This step keeps `run_sql` on the Step 3 sample dataset so you can demo the gate locally. With a real warehouse you'd gate the warehouse connection tool from Step 4 the same way, on a dry-run byte estimate instead of the toy heuristic below.++Add a cheap estimator and gate `run_sql` on it:```ts title="agent/lib/cost.ts"// Illustrative: a real warehouse exposes a dry-run byte estimate.@@ -27,7 +29,7 @@ import { estimateScanGb } from "../lib/cost.js";const THRESHOLD_GB = 50;export default defineTool({- description: "Run a read-only SQL query against the warehouse.",+ description: "Run a read-only SQL query against the analytics tables.",inputSchema: z.object({ sql: z.string() }),// Cost-based gate: only the expensive queries need a human yes.needsApproval: ({ toolInput }) => estimateScanGb(toolInput?.sql ?? "") > THRESHOLD_GB,@@ -48,12 +50,12 @@ Ask for something that forces a large unfiltered scan:Total revenue across all customers, all time, broken out by day.```-The model proposes the query, `needsApproval` returns `true`, and the turn parks. The stream emits `input.requested`, then `session.waiting`. How the prompt looks depends on the channel: buttons in the TUI, Block Kit in Slack, a UI control on the web. Approve it and the run resumes from exactly that step, then the query runs. Deny it and the tool is skipped, with the model told why.+The model proposes the query, `needsApproval` returns `true`, and the turn parks. The stream emits `input.requested`, then `session.waiting`. How the prompt looks depends on the channel, whether buttons in the TUI, Block Kit in Slack, or a UI control on the web. Approve it and the run resumes from exactly that step, then the query runs. Deny it and the tool is skipped, with the model told why.Each session has exactly one active continuation. Answer an approval against a stale handle and it's rejected, so there's no way to double-resume the same parked turn.-The same machinery backs the built-in `ask_question` tool, where the model asks you mid-turn, and per-connection approval via `approval: once()`. See [Tools: human-in-the-loop](../tools).+The same machinery backs the built-in `ask_question` tool, where the model asks you mid-turn, and per-connection approval via `approval: once()`. See [Tools and human-in-the-loop](../tools).-→ Next: [Step 9: Ship it](./ship-it)+→ Next: [Ship it](./ship-it)-Depth: [Tools: human-in-the-loop](../tools)+Learn more: [Tools and human-in-the-loop](../tools)diff --git a/docs/tutorial/how-it-runs.mdx b/docs/tutorial/how-it-runs.mdxindex 8adf90466..217bf4d24 100644--- a/docs/tutorial/how-it-runs.mdx+++ b/docs/tutorial/how-it-runs.mdx@@ -1,15 +1,17 @@----title: "Step 2: How It Runs"-description: "Session, turn, and durable steps: what you just watched, and why it survives a crash."+title: "How It Runs"+description: "Part 2 of the Build an Agent tutorial. Session, turn, and durable steps, and why a turn survives a crash."----You sent one message and got one answer. Here's the model behind that, in three words.+The analytics assistant sent one message and got one answer. Three terms describe the model behind that.-**session** → your whole conversation (durable, can span days)-**turn** → one message you send and the work it triggers-**step** → a durable checkpoint within the turn+| Term | Meaning |+| ----------- | ------------------------------------------------- |+| **session** | Your whole conversation (durable, can span days). |+| **turn** | One message you send and the work it triggers. |+| **step** | A durable checkpoint within the turn. |-Each turn runs as a durable workflow, and Eve saves progress at every step. Restart in the middle of a turn and it picks up from the last completed step, without re-running your tool calls. A turn that's waiting on you (an approval, a question) resumes whenever you answer, even if that's much later.+Each turn runs as a durable workflow, and Eve saves progress at every step. Completed steps never re-run; Eve replays the recorded result. A step interrupted mid-execution re-runs, so make non-idempotent side effects like charges or emails idempotent, or gate them with approval. A turn that's waiting on you (an approval, a question) resumes whenever you answer, even if that's much later.That's why the features in the rest of this tutorial work the way they do:@@ -17,7 +19,7 @@ That's why the features in the rest of this tutorial work the way they do:- The metric glossary in Step 6 survives across turns. State is checkpointed at step boundaries, so it sticks.- The spend approval in Step 8 pauses the turn on your yes/no, then picks up exactly where it left off.-Your job is to author capabilities: tools, instructions, channels, skills. Eve drives the model↔tool loop and decides when a turn continues, waits, or ends. You never write that loop yourself.+You author capabilities, including tools, instructions, channels, and skills. Eve drives the model-to-tool loop and decides when a turn continues, waits, or ends. You never write that loop yourself.→ Next: [Step 3: Query sample data](./query-sample-data)diff --git a/docs/tutorial/query-sample-data.mdx b/docs/tutorial/query-sample-data.mdxindex b292c1883..010d7dc6e 100644--- a/docs/tutorial/query-sample-data.mdx+++ b/docs/tutorial/query-sample-data.mdx@@ -1,13 +1,13 @@----title: "Step 3: Query Sample Data"-description: "Add a run_sql tool over the bundled sample dataset and watch the tool loop."+title: "Query Sample Data"+description: "Part 3 of the Build an Agent tutorial. Add a run_sql tool over the bundled sample dataset and watch the tool loop."----Right now the agent can hold a conversation but it can't see a single row of data. So give it a tool. A tool is the action primitive: typed input goes in, your code runs, structured output comes back. The name the model sees is just the filename, so `agent/tools/run_sql.ts` becomes the tool `run_sql`.+The analytics assistant can hold a conversation, but it can't see a single row of data. Give it a tool. A tool is the action primitive. Typed input goes in, your code runs, structured output comes back. The name the model sees is the filename, so `agent/tools/run_sql.ts` becomes the tool `run_sql`.## A tiny sample dataset-To make the first query work without any setup, bundle a small in-memory dataset under `agent/lib/`. Keep it tiny. This is throwaway scaffolding, not the real warehouse (that comes in Step 4).+To make the first query work without setup, bundle a small in-memory dataset under `agent/lib/`. Keep it tiny. This is throwaway scaffolding, not the real warehouse (that comes in Step 4).```ts title="agent/lib/sample-db.ts"// A toy SQLite-in-memory stand-in. Swap for your real warehouse in Step 4.@@ -42,7 +42,7 @@ export async function runReadOnlySql(sql: string) {}```-## The tool+## Define the run_sql tool```ts title="agent/tools/run_sql.ts"import { defineTool } from "eve/tools";@@ -68,7 +68,7 @@ Tools run in your app runtime with full `process.env`, not in the sandbox. The `## Watch the tool loop-Restart `eve dev` and ask:+Restart the dev server with `npm run dev` and ask:```textWhich customer has spent the most, and how much?@@ -76,6 +76,6 @@ Which customer has spent the most, and how much?Watch the loop play out in the TUI. The model emits a `run_sql` call, Eve runs your `execute`, and the rows come back as a tool result. The model reads them and answers with a real number. Eve drove the whole loop. All you supplied was the tool.-→ Next: [Step 4: Connect a warehouse](./connect-a-warehouse)+→ Next: [Connect a warehouse](./connect-a-warehouse)-Depth: [Tools](../tools)+Learn more: [Tools](../tools)diff --git a/docs/tutorial/remember-definitions.mdx b/docs/tutorial/remember-definitions.mdxindex 37e43e153..03cd84b45 100644--- a/docs/tutorial/remember-definitions.mdx+++ b/docs/tutorial/remember-definitions.mdx@@ -1,9 +1,9 @@----title: "Step 6: Remember Definitions"-description: "Use defineState to remember the team's metric glossary across turns."+title: "Remember Definitions"+description: "Part 6 of the Build an Agent tutorial. Use defineState to remember the team's metric glossary across turns."----Every team has house definitions. “Active” means a purchase in the last 30 days, revenue is net of refunds, a “week” starts Monday. Re-explaining all of that on every turn is a waste. State gives the agent a place to keep it.+Every team has house definitions for the analytics assistant. "Active" means a purchase in the last 30 days, revenue is net of refunds, a "week" starts Monday. Re-explaining all of that on every turn is a waste. State gives the agent a place to keep them.`defineState(name, initial)` creates a typed, named slot that survives across step and turn boundaries within a session. You read it with `get()` and change it with `update()`.@@ -67,6 +67,6 @@ The second turn is a separate turn in the same session, yet the definition is stState is scoped to a session and isolated per agent, so a subagent starts with fresh state and never sees the parent's. Need to reset something each turn? Call `update(() => fresh)` in a lifecycle hook. More in [State](../guides/state).-→ Next: [Step 7: Team playbooks](./team-playbooks)+→ Next: [Team playbooks](./team-playbooks)-Depth: [State](../guides/state)+Learn more: [State](../guides/state)diff --git a/docs/tutorial/run-analysis.mdx b/docs/tutorial/run-analysis.mdxindex b9225d22e..4ab6c521a 100644--- a/docs/tutorial/run-analysis.mdx+++ b/docs/tutorial/run-analysis.mdx@@ -1,15 +1,15 @@----title: "Step 5: Run Analysis"-description: "Seed the warehouse schema into the sandbox workspace, then compute and chart beyond SQL."+title: "Run Analysis"+description: "Part 5 of the Build an Agent tutorial. Seed the warehouse schema into the sandbox workspace, then compute and chart beyond SQL."----SQL tells you the numbers, but a cohort curve, a forecast, or a chart needs real computation. That's what the sandbox is for: an isolated bash environment with a `/workspace` filesystem. Every agent gets exactly one.+SQL tells the analytics assistant the numbers, but a cohort curve, a forecast, or a chart needs real computation. That's what the sandbox is for. It's an isolated bash environment with a `/workspace` filesystem, and every agent gets exactly one.-There are two pieces. First seed reference files the model can read, then compute against them.+This takes two pieces. First seed reference files the model can read, then compute against them.## Seed the schema into the workspace-Mount the warehouse schema into the sandbox so the model isn't guessing at table shapes. Seeding uses the folder sandbox layout: anything under `agent/sandbox/workspace/` lands in the live `/workspace` cwd at session bootstrap.+Mount the warehouse schema into the sandbox so the model isn't guessing at table shapes. Seeding uses the folder sandbox layout, where anything under `agent/sandbox/workspace/` lands in the live `/workspace` cwd at session bootstrap.```textagent/sandbox/@@ -25,7 +25,7 @@ CREATE TABLE orders (id INT, customer_id INT, amount_cents INT, created_at DCREATE TABLE customers (id INT, name TEXT, plan TEXT, signed_up_at DATE);```-Top-level workspace entries get advertised to the model automatically, so it knows `schema.sql` is there to read. No `agent/sandbox/sandbox.ts` required. A `workspace/` folder keeps the default sandbox and just seeds your files into it.+Top-level workspace entries get advertised to the model automatically, so it knows `schema.sql` is there to read. No `agent/sandbox/sandbox.ts` required. A `workspace/` folder keeps the default sandbox and seeds your files into it.## Compute and chart in the sandbox@@ -67,13 +67,15 @@ export default defineTool({});```-Now ask for something past plain SQL:+This tool shells out to `python` with matplotlib, which the sandbox base image does not preinstall. Install the runtime in sandbox bootstrap (or bake it into a custom image) so `python plot.py` resolves. See [Sandbox](../sandbox) for where bootstrap runs.++Now ask for something past plain SQL. If you skipped Step 4, this still works against the Step 3 sample dataset:```text-Plot weekly revenue for the last 8 weeks.+Plot total order revenue per customer.```-The model queries the warehouse (Step 4) for the numbers, checks `schema.sql` to get the grain right, then calls `chart_series` to render the PNG in `/workspace`.+The model queries for the numbers (the warehouse from Step 4, or the sample dataset if you skipped it), checks `schema.sql` to get the grain right, then calls `chart_series` to render the PNG in `/workspace`.## Secrets stay out of the sandbox@@ -81,6 +83,6 @@ The sandbox has no `process.env` and no access to your app's secrets. Your warehThe local backend runs the sandbox on your laptop during `eve dev`; on Vercel it runs on Vercel Sandbox. Lifecycle, backends, and network policy are in [Sandbox](../sandbox).-→ Next: [Step 6: Remember definitions](./remember-definitions)+→ Next: [Remember definitions](./remember-definitions)-Depth: [Sandbox](../sandbox)+Learn more: [Sandbox](../sandbox)diff --git a/docs/tutorial/ship-it.mdx b/docs/tutorial/ship-it.mdxindex 7d1deff36..0943b3ee6 100644--- a/docs/tutorial/ship-it.mdx+++ b/docs/tutorial/ship-it.mdx@@ -1,27 +1,39 @@----title: "Step 9: Ship It"-description: "Put a web dashboard on the agent with useEveAgent, replace placeholderAuth, and deploy to Vercel."+title: "Ship It"+description: "Part 9 of the Build an Agent tutorial. Put a web dashboard on the agent with useEveAgent, replace placeholderAuth, and deploy to Vercel."----The assistant runs fine in the TUI. Now ship it for real: a web dashboard your team logs into, behind actual auth, deployed on Vercel. Three pieces to wire up: a React UI, the channel's auth, and the deploy itself.+The analytics assistant runs fine in the TUI. Now ship it for real, as a web dashboard your team logs into, behind actual auth, deployed on Vercel. There are three pieces to wire up. A React UI, the channel's auth, and the deploy itself.-## A dashboard with `useEveAgent`+## Add the Web Chat app++Step 1 scaffolded the agent without a web frontend. Add one now with `eve channels add`, run from the `analytics-assistant/` directory:-The dashboard talks to the built-in Eve HTTP channel (`agent/channels/eve.ts`). On the browser side, `useEveAgent` takes care of session creation, streaming, and HITL. In a Next.js app, wrap the config and the routes get wired automatically:+```bash+npx eve channels add web+```++This adds a Next.js app (`next.config.ts`, `app/page.tsx`, `app/_components/`) wired to the existing Eve channel, plus the chat UI components and their dependencies. Run `npm install` afterward to install the added packages. The generated `next.config.ts` wraps your config with `withEve`, which wires the Eve routes automatically:```ts title="next.config.ts"import type { NextConfig } from "next";import { withEve } from "eve/next";-export default withEve({} satisfies NextConfig);+const nextConfig: NextConfig = {};++export default withEve(nextConfig);```-```tsx title="app/dashboard/chat.tsx"+## A dashboard with `useEveAgent`++The dashboard talks to the built-in Eve HTTP channel (`agent/channels/eve.ts`). On the browser side, `useEveAgent` handles session creation, streaming, and HITL. The scaffold renders its chat from `app/_components/agent-chat.tsx`, mounted by `app/page.tsx`. That component is fuller than you need to start, so replace its contents with this minimal version:++```tsx title="app/_components/agent-chat.tsx""use client";import { useEveAgent } from "eve/react";-export function AnalyticsChat() {+export function AgentChat() {const agent = useEveAgent();const isBusy = agent.status === "submitted" || agent.status === "streaming";@@ -51,11 +63,37 @@ export function AnalyticsChat() {}```-`agent.data.messages` and `agent.status` cover most chat UIs. The hook also surfaces HITL prompts (the spend approval from [Step 8](./guard-the-spend)), so the dashboard can render approve/deny controls. Full API: [Frontend](../guides/frontend/overview).+The generated `app/page.tsx` already imports and renders this `AgentChat` export, so no other wiring is needed:++```tsx title="app/page.tsx"+import { AgentChat } from "@/app/_components/agent-chat";++export default function Page() {+ return <AgentChat />;+}+```++`agent.data.messages` and `agent.status` cover most chat UIs. The hook also surfaces HITL prompts (the spend approval from [Step 8](./guard-the-spend)), so the dashboard can render approve/deny controls. For the full API, see [Frontend](../guides/frontend/overview).## Replace `placeholderAuth`-The scaffold's channel ships with `placeholderAuth()`, which fails closed: it rejects production traffic so an unauthenticated app can't go live by accident. Swap it for your app's real auth before you deploy. Order matters here. List your app auth first, ahead of the catch-all helpers, so any entry that doesn't recognize the caller falls through to the next one:+The scaffold's channel ships with `placeholderAuth()`, which fails closed. It rejects production traffic so an unauthenticated app can't go live by accident. Swap it for your app's real auth before you deploy.++Your auth lives in one module that turns a request into a user. Create `agent/lib/auth.ts` and wire your real provider (a cookie session, Auth.js, Clerk) in here. The stub below returns a fixed user so the page compiles and runs end to end:++```ts title="agent/lib/auth.ts"+export interface AppUser {+ id: string;+ team: string;+}++// Replace with your real session/provider lookup.+export async function authenticate(_request: Request): Promise<AppUser | null> {+ return { id: "demo-user", team: "growth" };+}+```++Now point the channel at it. Replace the contents of `agent/channels/eve.ts`, which Step 7 left with a dev-only `devTeam` entry and `placeholderAuth()`. List your app auth first, ahead of the catch-all helpers, so any entry that doesn't recognize the caller falls through to the next one:```ts title="agent/channels/eve.ts"import { eveChannel } from "eve/channels/eve";@@ -81,7 +119,7 @@ export default eveChannel({That `team` attribute is exactly what the dynamic playbook in [Step 7](./team-playbooks) reads from `ctx.session.auth`. Identity is set in this one place and flows out to every capability from there.-## Deploy+## Deploy to Vercel```bashvercel deploy@@ -90,11 +128,29 @@ vercel deployOn Vercel, the web app stays public and the Eve runtime sits behind it on the same origin, with the sandbox running on Vercel Sandbox. You can smoke-test the deployment without leaving the CLI:```bash-eve dev https://your-analytics-app.vercel.app+npx eve dev https://your-analytics-app.vercel.app```That's the full assistant, deployed and authed. It queries the warehouse, runs analysis in a sandbox, charts the results, remembers your team's definitions, loads the right playbook per team, and asks before it spends.-Depth: [Frontend](../guides/frontend/overview) · [Auth & route protection](../guides/auth-and-route-protection) · [Deployment](../guides/deployment)+## What you learned++Across the nine steps you built and shipped one agent, and along the way you used:++- **Tools** to give the model typed actions (`run_sql`, `chart_series`, `define_metric`).+- **Connections** to reach a warehouse over an OAuth MCP, with per-user tokens Eve resolves for you.+- **The sandbox** to compute and chart beyond SQL in an isolated `/workspace`.+- **State** (`defineState`) to remember the team's glossary across turns.+- **Dynamic skills** (`defineDynamic`) to load the right team playbook per caller.+- **Human-in-the-loop** approval (`needsApproval`) to gate expensive queries.+- **Channel auth** to turn a request into an authenticated principal.+- **Deployment** to Vercel, with the runtime behind your web app.++## Next steps++- [Connections](../connections) for tool allowlists and per-connection approval.+- [Sandbox](../sandbox) for backends, lifecycle, and network policy.+- [Dynamic capabilities](../guides/dynamic-capabilities) for schema-derived dynamic tools, a read-only analyst subagent, and model-authored report workflows on this same example.+- [Auth and route protection](../guides/auth-and-route-protection) for production auth patterns.-Go deeper on this same example in [Advanced](../guides/dynamic-capabilities): schema-derived dynamic tools, a read-only analyst subagent, and model-authored report workflows.+Learn more: [Frontend](../guides/frontend/overview) · [Auth and route protection](../guides/auth-and-route-protection) · [Deployment](../guides/deployment)diff --git a/docs/tutorial/team-playbooks.mdx b/docs/tutorial/team-playbooks.mdxindex 981a54b73..a26fbaeb5 100644--- a/docs/tutorial/team-playbooks.mdx+++ b/docs/tutorial/team-playbooks.mdx@@ -1,15 +1,15 @@----title: "Step 7: Team Playbooks"-description: "Load the caller's team playbook with a dynamic skill keyed on the principal."+title: "Team Playbooks"+description: "Part 7 of the Build an Agent tutorial. Load the caller's team playbook with a dynamic skill keyed on the principal."----The glossary from [Step 6](./remember-definitions) is per-session. But your teams have standing analysis conventions (Growth runs cohort retention a particular way, Finance has its own revenue-recognition rules), and those shouldn't bleed across tenants. Load the right team's playbook for whoever is asking.+The glossary from [Step 6](./remember-definitions) is per-session. But your teams have standing analysis conventions for the analytics assistant (Growth runs cohort retention a particular way, Finance has its own revenue-recognition rules), and those shouldn't bleed across tenants. Load the right team's playbook for whoever is asking.-A skill is an on-demand procedure: the model pulls it in with `load_skill` only when a turn actually needs it. Make it dynamic and the skill gets decided at runtime instead of baked in. A `defineDynamic` resolver reads the session and returns a `defineSkill` (or nothing). Here we key that decision on the caller's identity in `ctx.session.auth`.+A skill is an on-demand procedure. The model pulls it in with `load_skill` only when a turn needs it. Make it dynamic and the skill gets decided at runtime instead of baked in. A `defineDynamic` resolver reads the session and returns a `defineSkill` (or nothing). Here you key that decision on the caller's identity in `ctx.session.auth`.## A playbook per principal-`ctx.session.auth.current` holds the most recent caller, or `null` if there isn't one. Its `attributes` are the claims your auth layer stamped on, team included. Read the team, look up that team's playbook, and emit a skill for it:+`ctx.session.auth.current` holds the most recent caller, or `null` if there isn't one. Its `attributes` are the claims your auth layer stamped on, including the team. Read the team, look up that team's playbook, and emit a skill for it:```ts title="agent/skills/team-playbook.ts"import { defineDynamic, defineSkill } from "eve/skills";@@ -48,16 +48,39 @@ export default defineDynamic({});```-`session.started` fires once per session. The resolver reads the team a single time, and the resulting skill stays available for every turn that follows. Returning `null` produces no skill at all, so a caller with no team simply gets no playbook.+`session.started` fires once per session. The resolver reads the team once, and the resulting skill stays available for every turn that follows. Returning `null` produces no skill, so a caller with no team gets no playbook.## See it route-A Growth user asks "what's our 8-week retention?" The model sees the playbook fits, calls `load_skill`, and applies the Growth conventions to that turn: weekly cohorts, no trial accounts. Ask the same question as a Finance user and you'll never see the Growth playbook. You get Finance's.+The team comes from authenticated claims, which the auth layer stamps on in [Step 9](./ship-it). Until then `ctx.session.auth.current` has no `team`, so the resolver returns `null` and no playbook loads. To verify routing now, stamp a team in local dev. Add a dev-only entry to `agent/channels/eve.ts` ahead of `localDev()`, and remove it before Step 9 wires real auth:-The team comes from authenticated claims, not from the message, so one tenant can't borrow another's playbook by asking nicely. (Those `attributes` are set by the auth layer in [Step 9](./ship-it).)+```ts title="agent/channels/eve.ts"+import { eveChannel } from "eve/channels/eve";+import { localDev, placeholderAuth, vercelOidc, type AuthFn } from "eve/channels/auth";++// Dev-only: stamp a team so Step 7's playbook resolver has something to read.+// Remove before Step 9.+const devTeam: AuthFn<Request> = () =>+ process.env.NODE_ENV === "production"+ ? null+ : {+ attributes: { team: "growth" },+ authenticator: "dev-team",+ principalId: "dev",+ principalType: "user",+ };++export default eveChannel({+ auth: [devTeam, localDev(), vercelOidc(), placeholderAuth()],+});+```++Restart with `npm run dev` and ask "what's our 8-week retention?" The model sees the Growth playbook fits, calls `load_skill`, and applies the Growth conventions to that turn (weekly cohorts, no trial accounts). Switch `team` to `"finance"`, restart, and the same question routes to Finance's playbook instead.++Because the team comes from authenticated claims, not from the message, one tenant can't borrow another's playbook through the message content.The same `defineDynamic` resolver drives dynamic tools and instructions too. For the full mechanism, see [Dynamic capabilities](../guides/dynamic-capabilities).-→ Next: [Step 8: Guard the spend](./guard-the-spend)+→ Next: [Guard the spend](./guard-the-spend)-Depth: [Skills](../skills) · [Dynamic capabilities](../guides/dynamic-capabilities)+Learn more: [Skills](../skills) · [Dynamic capabilities](../guides/dynamic-capabilities)diff --git a/package.json b/package.jsonindex 3d1674ab4..1e08f90d0 100644--- a/package.json+++ b/package.json@@ -15,7 +15,7 @@"changeset": "changeset","check:deps": "syncpack lint","dev": "node ./scripts/dev.mjs",- "docs:check": "node ./scripts/check-docs.mjs",+ "docs:check": "node ./scripts/check-docs.mjs && node ./scripts/check-doc-snippets.mjs && node ./scripts/check-doc-mdx.mjs","fix:deps": "syncpack fix-mismatches && syncpack format","fmt": "oxfmt","guard:fixtures": "node ./scripts/guard-test-fixtures.mjs",diff --git a/packages/eve/src/cli/run.ts b/packages/eve/src/cli/run.tsindex 2319f07ea..ed6525cb0 100644--- a/packages/eve/src/cli/run.ts+++ b/packages/eve/src/cli/run.ts@@ -638,7 +638,7 @@ function createCliProgram(logger: CliLogger, runtime: CliRuntimeOverrides): Comm.option("--json", "Output results as JSON").option("--junit <path>", "Write JUnit XML results to a file").option("--skip-report", "Skip eval-defined reporters (e.g. Braintrust)")- .option("--verbose", "Stream per-eval ctx.log lines to stdout")+ .option("--verbose", "Stream per-eval t.log lines to stdout").action(async (evalIds: string[], options: EvalCliOptions) => {const runEvalCommand = runtime.runEvalCommand ?? (await loadRunEvalCommand());await runEvalCommand(evalIds, options, logger);diff --git a/packages/eve/src/evals/runner/run-evals.ts b/packages/eve/src/evals/runner/run-evals.tsindex 1948b2a78..e9e46ddde 100644--- a/packages/eve/src/evals/runner/run-evals.ts+++ b/packages/eve/src/evals/runner/run-evals.ts@@ -33,7 +33,7 @@ export interface RunEvalsOptions {readonly maxConcurrency?: number;/** Overrides every eval's `timeoutMs` when set (CLI `--timeout`). */readonly timeoutMs?: number;- /** Receives `ctx.log` lines as evals run (used by `--verbose`). */+ /** Receives `t.log` lines as evals run (used by `--verbose`). */readonly onEvalLog?: (evalId: string, message: string) => void;}diff --git a/scripts/check-doc-mdx.mjs b/scripts/check-doc-mdx.mjsnew file mode 100644index 000000000..64887d328--- /dev/null+++ b/scripts/check-doc-mdx.mjs@@ -0,0 +1,73 @@+#!/usr/bin/env node+/**+ * CI lint that compiles every docs page with the MDX compiler so syntax errors+ * are caught before the docs site build (turbopack + fumadocs-mdx) hits them.+ *+ * `check-docs.mjs` validates frontmatter, nav coverage, and links, but it does+ * not parse MDX, so a stray tag (e.g. a leaked `</...>`) or unbalanced JSX slips+ * through to the build. This compiles each `.md` / `.mdx` file the same way the+ * site does (markdown vs MDX by extension) and fails on the first parse error.+ *+ * `@mdx-js/mdx` is a transitive dependency (via fumadocs-mdx) and is not+ * importable by bare specifier from the repo root, so resolve it from the pnpm+ * store by globbing for the installed version.+ */+import { readFileSync, readdirSync, statSync } from "node:fs";+import { relative, resolve } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";++const repoRoot = resolve(fileURLToPath(new URL("..", import.meta.url)));+const docsDir = `${repoRoot}/docs`;++function findMdxPackage() {+ const store = `${repoRoot}/node_modules/.pnpm`;+ let match;+ try {+ match = readdirSync(store).find((d) => /^@mdx-js\+mdx@/.test(d));+ } catch {+ return null;+ }+ if (!match) return null;+ return `${store}/${match}/node_modules/@mdx-js/mdx/index.js`;+}++const mdxPath = findMdxPackage();+if (!mdxPath) {+ process.stderr.write(+ "[docs:mdx] could not resolve @mdx-js/mdx from the pnpm store; run `pnpm install`.\n",+ );+ process.exit(1);+}+const { compile } = await import(pathToFileURL(mdxPath).href);++function walk(dir) {+ const out = [];+ for (const entry of readdirSync(dir)) {+ const full = `${dir}/${entry}`;+ if (statSync(full).isDirectory()) out.push(...walk(full));+ else if (entry.endsWith(".md") || entry.endsWith(".mdx")) out.push(full);+ }+ return out;+}++const files = walk(docsDir).filter((f) => relative(docsDir, f) !== "README.md");+const failures = [];+for (const abs of files) {+ const rel = relative(docsDir, abs);+ try {+ await compile(readFileSync(abs, "utf8"), { format: abs.endsWith(".mdx") ? "mdx" : "md" });+ } catch (err) {+ failures.push({ rel, message: String(err?.message ?? err).split("\n")[0] });+ }+}++if (failures.length === 0) {+ process.stdout.write(`[docs:mdx] ok — ${files.length} docs compile.\n`);+ process.exit(0);+}++process.stderr.write("[docs:mdx] FAIL\n\n");+for (const { rel, message } of failures) {+ process.stderr.write(` docs/${rel}\n → ${message}\n\n`);+}+process.exit(1);diff --git a/scripts/check-doc-snippets.mjs b/scripts/check-doc-snippets.mjsnew file mode 100644index 000000000..c05f6ea53--- /dev/null+++ b/scripts/check-doc-snippets.mjs@@ -0,0 +1,88 @@+#!/usr/bin/env node+/**+ * CI lint that validates the `eve` import paths used in documentation code+ * samples against the package's real `exports` map.+ *+ * Docs are the most-copied surface of the framework, and the cheapest way for+ * a sample to rot is to import from a subpath that no longer exists (or never+ * did). Full type-checking of every snippet is noisy because many blocks are+ * intentional fragments; validating import specifiers against the exports map+ * is deterministic and catches the highest-frequency failure with no false+ * positives.+ *+ * Checks every ```ts / ```typescript fenced block under /docs: any+ * `from "eve..."` / `import("eve...")` specifier must resolve to a real+ * subpath in packages/eve/package.json#exports.+ */+import { readdirSync, readFileSync, statSync } from "node:fs";+import { relative, resolve } from "node:path";+import { fileURLToPath } from "node:url";++const repoRoot = resolve(fileURLToPath(new URL("..", import.meta.url)));+const docsDir = `${repoRoot}/docs`;+const pkg = JSON.parse(readFileSync(`${repoRoot}/packages/eve/package.json`, "utf8"));++// Build the set of valid bare import specifiers from the exports map:+// "." -> "eve"+// "./tools" -> "eve/tools"+// "./channels/x" -> "eve/channels/x"+const validSpecifiers = new Set();+for (const key of Object.keys(pkg.exports ?? {})) {+ if (key === "./package.json") continue;+ validSpecifiers.add(key === "." ? "eve" : `eve/${key.slice(2)}`);+}++function walk(dir) {+ const out = [];+ for (const entry of readdirSync(dir)) {+ const full = `${dir}/${entry}`;+ if (statSync(full).isDirectory()) out.push(...walk(full));+ else if (entry.endsWith(".md") || entry.endsWith(".mdx")) out.push(full);+ }+ return out;+}++const fenceRe = /```(ts|tsx|typescript)\b[^\n]*\n([\s\S]*?)```/g;+// Capture the module specifier from static and dynamic imports/exports.+const specRe = /(?:from|import|export\s+\*\s+from)\s*\(?\s*["']([^"']+)["']/g;++const failures = [];+let blockCount = 0;+let specCount = 0;++for (const abs of walk(docsDir)) {+ const rel = relative(docsDir, abs);+ const source = readFileSync(abs, "utf8");+ let block;+ while ((block = fenceRe.exec(source)) !== null) {+ blockCount += 1;+ const code = block[2];+ let m;+ while ((m = specRe.exec(code)) !== null) {+ const spec = m[1];+ if (spec !== "eve" && !spec.startsWith("eve/")) continue; // only validate eve imports+ specCount += 1;+ if (!validSpecifiers.has(spec)) {+ failures.push({ file: rel, spec });+ }+ }+ }+}++if (failures.length === 0) {+ process.stdout.write(+ `[docs:snippets] ok — ${specCount} eve import path${specCount === 1 ? "" : "s"} across ${blockCount} code blocks resolve.\n`,+ );+ process.exit(0);+}++process.stderr.write("[docs:snippets] FAIL\n\n");+for (const { file, spec } of failures) {+ process.stderr.write(+ ` docs/${file}\n → imports \`${spec}\`, which is not an exported subpath of \`eve\`\n\n`,+ );+}+process.stderr.write(+ `Valid \`eve\` subpaths come from packages/eve/package.json#exports. Fix the import or add the export.\n`,+);+process.exit(1);diff --git a/scripts/check-docs.mjs b/scripts/check-docs.mjsindex 0d65dbc9a..4374d7cc7 100755--- a/scripts/check-docs.mjs+++ b/scripts/check-docs.mjs@@ -90,6 +90,7 @@ function collectNavReferences(rootDir) {continue;}if (entry === "---") continue;+ if (/^---.+---$/.test(entry)) continue; // labeled separator: ---Group name---if (entry.startsWith("[")) continue; // [Title](url) custom linkconst slug = entry.startsWith("!") ? entry.slice(1) : entry;const key = relDir ? `${relDir}/${slug}` : slug;@@ -179,6 +180,61 @@ for (const root of ROOTS) {}}+// 3. Internal links resolve. Every relative (./ ../) or site-absolute (/docs/)+// markdown link in a doc page must point at a real doc page or folder.+// fumadocs renders broken links as dead clicks; CI should catch them.+function checkLinks(rootDir) {+ const files = walkMarkdown(rootDir);+ const slugs = new Set();+ const dirs = new Set();+ for (const abs of files) {+ const rel = relative(rootDir, abs).split("\\").join("/");+ slugs.add(rel.replace(/\.mdx?$/, ""));+ let d = rel.includes("/") ? rel.slice(0, rel.lastIndexOf("/")) : "";+ while (d) {+ dirs.add(d);+ d = d.includes("/") ? d.slice(0, d.lastIndexOf("/")) : "";+ }+ }+ const linkRe = /\]\((\s*[^)]+?)\s*\)/g;+ for (const abs of files) {+ const rel = relative(rootDir, abs).split("\\").join("/");+ if (isExcluded(rel)) continue;+ const dirOfFile = rel.includes("/") ? rel.slice(0, rel.lastIndexOf("/")) : "";+ const source = readFileSync(abs, "utf8");+ let m;+ while ((m = linkRe.exec(source)) !== null) {+ let target = m[1].trim();+ if (!target) continue;+ // Only validate doc-internal links.+ const isRel = target.startsWith("./") || target.startsWith("../");+ const isSite = target.startsWith("/docs/") || target === "/docs";+ if (!isRel && !isSite) continue; // external, mailto, #anchor, bare /eve/* runtime route, etc.+ target = target.split("#")[0].split("?")[0];+ if (!target) continue; // pure in-page anchor+ let resolvedSlug;+ if (isSite) {+ resolvedSlug = target.replace(/^\/docs\/?/, "");+ } else {+ const base = dirOfFile ? `${rootDir}/${dirOfFile}` : rootDir;+ resolvedSlug = relative(rootDir, resolve(base, target)).split("\\").join("/");+ }+ resolvedSlug = resolvedSlug.replace(/\/$/, "").replace(/\.mdx?$/, "");+ if (resolvedSlug === "" || resolvedSlug === ".") continue; // docs root / index+ if (slugs.has(resolvedSlug)) continue;+ if (slugs.has(`${resolvedSlug}/index`)) continue;+ if (dirs.has(resolvedSlug)) continue; // folder link (sidebar group)+ failures.push({+ root: "docs",+ file: rel,+ issue: `broken internal link → \`${m[1].trim()}\` (resolves to \`${resolvedSlug}\`, no such page)`,+ });+ }+ }+}++checkLinks(ROOTS[0].dir);+if (failures.length === 0) {process.stdout.write(`[docs:check] ok — ${validatedCount} file${validatedCount === 1 ? "" : "s"} validated.\n`,