From 252c7a45f7116fb7ccb5f8a382b072bce2ae3480 Mon Sep 17 00:00:00 2001 From: Hugo Richard Date: Thu, 12 Nov 2026 15:44:53 +0000 Subject: [PATCH 1/3] docs: add self-improving agent guide Add a guide that connects the examples/eve agent to the Vercel MCP so it reads its own Agent Runs, with a weekly review schedule, a daily failure check, and a self-review skill. Add the page to the sidebar and the guides index, with a refresh-2 Nucleo icon. --- .../app/assets/icons/nucleo/refresh-2.svg | 1 + apps/docs/app/utils/docs-sidebar.ts | 3 +- apps/docs/content/docs/5.guides/1.index.md | 3 +- .../docs/5.guides/8.self-improving-agent.md | 221 ++++++++++++++++++ 4 files changed, 226 insertions(+), 2 deletions(-) create mode 100644 apps/docs/app/assets/icons/nucleo/refresh-2.svg create mode 100644 apps/docs/content/docs/5.guides/8.self-improving-agent.md diff --git a/apps/docs/app/assets/icons/nucleo/refresh-2.svg b/apps/docs/app/assets/icons/nucleo/refresh-2.svg new file mode 100644 index 0000000..73a44d8 --- /dev/null +++ b/apps/docs/app/assets/icons/nucleo/refresh-2.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/docs/app/utils/docs-sidebar.ts b/apps/docs/app/utils/docs-sidebar.ts index 964ded3..b6b4013 100644 --- a/apps/docs/app/utils/docs-sidebar.ts +++ b/apps/docs/app/utils/docs-sidebar.ts @@ -60,7 +60,8 @@ export const docsSidebar: DocsSidebarGroup[] = [ { path: '/guides/fix-failing-ci' }, { path: '/guides/release-notes' }, { path: '/guides/chat-bot' }, - { path: '/guides/multi-agent' } + { path: '/guides/multi-agent' }, + { path: '/guides/self-improving-agent' } ] }, { diff --git a/apps/docs/content/docs/5.guides/1.index.md b/apps/docs/content/docs/5.guides/1.index.md index aea0eff..a57a3cb 100644 --- a/apps/docs/content/docs/5.guides/1.index.md +++ b/apps/docs/content/docs/5.guides/1.index.md @@ -19,6 +19,7 @@ Each guide builds one working GitHub agent for one job, from install to the comm | [Release notes](/guides/release-notes) | [AI SDK](/integrations/ai-sdk) | `release-manager` | Beginner | | [Chat bot](/guides/chat-bot) | [Chat SDK](/integrations/chat-sdk), [Vercel Workflow](/integrations/workflow) | `issue-triage` | Beginner | | [Multi-agent](/guides/multi-agent) | [eve](/integrations/eve), [AI SDK](/integrations/ai-sdk) | `code-review`, `issue-triage`, `release-manager` | Advanced | +| [Self-improving agent](/guides/self-improving-agent) | [eve](/integrations/eve) | `auto` | Advanced | New to agents? Start with [Your first agent](/learn/first-agent), which builds an issue-triage agent in a terminal and explains each part. @@ -27,7 +28,7 @@ New to agents? Start with [Your first agent](/learn/first-agent), which builds a Two guides come from projects in the repository's [`examples/`](https://github.com/vercel-labs/github-tools/tree/main/examples) folder: - [`examples/pr-review-agent`](https://github.com/vercel-labs/github-tools/tree/main/examples/pr-review-agent) is the bot in [Review pull requests](/guides/review-pull-requests), and the starting point for [Chat bot](/guides/chat-bot). -- [`examples/eve`](https://github.com/vercel-labs/github-tools/tree/main/examples/eve) is an eve agent you can clone and deploy as is, with `preset: 'auto'` and `requireApproval: 'auto'`, reachable from Slack and from GitHub mentions. +- [`examples/eve`](https://github.com/vercel-labs/github-tools/tree/main/examples/eve) is an eve agent you can clone and deploy as is, with `preset: 'auto'` and `requireApproval: 'auto'`, reachable from Slack and from GitHub mentions. [Self-improving agent](/guides/self-improving-agent) builds on it. ## Production templates diff --git a/apps/docs/content/docs/5.guides/8.self-improving-agent.md b/apps/docs/content/docs/5.guides/8.self-improving-agent.md new file mode 100644 index 0000000..598e396 --- /dev/null +++ b/apps/docs/content/docs/5.guides/8.self-improving-agent.md @@ -0,0 +1,221 @@ +--- +title: Self-improving agent +description: Give an eve GitHub agent read access to its own production runs through the Vercel MCP, so it reviews its traces on a schedule and proposes fixes to its own instructions and config. +seo: + title: Build a self-improving AI agent that reviews its own traces +navigation: + icon: i-nucleo-refresh-2 +level: advanced +path: /guides/self-improving-agent +--- + +To let an agent improve itself, connect it to the [Vercel MCP](https://vercel.com/docs/agent-resources/vercel-mcp) and give it a schedule: the Vercel MCP reads the agent's own [Agent Runs](https://vercel.com/docs/agent-resources/vercel-mcp/tools/agent-runs), with each run's status, token usage and trace, and the agent reports what was slow, what failed and what to change. This guide adds that loop to the [`examples/eve`](https://github.com/vercel-labs/github-tools/tree/main/examples/eve) agent, which already answers in Slack and on GitHub. + +## What you'll build + +Every Monday, the agent posts a review of its last week in a Slack channel: the slowest and most expensive runs, the failures, and up to three changes it proposes, each with the run IDs that show the problem. Reply in the thread with "open an issue for the second one" and it files the issue in its own repository, after you approve. Every morning, a second schedule checks the last day for failed runs and new runtime errors, and posts only when it finds one. + +The agent never changes itself. It proposes, a person decides, and the change lands through a reviewed pull request like any other. + +## Before you start + +- The agent from [`examples/eve`](https://github.com/vercel-labs/github-tools/tree/main/examples/eve), deployed to Vercel with its Slack channel set up. Agent Runs are recorded for every eve agent deployed to Vercel, so a week of use gives the review something to read. +- The agent's code in a GitHub repository the agent's GitHub App is installed on, so it can file issues there. +- A Slack channel for the reports, with the Slack app invited. Keep it private: a trace contains what people asked the agent. + +## 1. Create a Vercel connector + +The Vercel MCP is an OAuth server. A schedule runs with no signed-in user, so the agent needs an app-scoped token that [Vercel Connect](https://vercel.com/docs/connect) issues on its own. From the agent's directory: + +```bash [Terminal] +vercel connect create vercel --name github-agent +``` + +The CLI opens your browser to sign in to Vercel. Grant the team that owns the agent's project. The connector acts with your access, so you need access to that project. Attach the connector to the project: + +```bash [Terminal] +vercel connect attach vercel/github-agent --yes +``` + +`vercel/github-agent` is the connector UID. `vercel connect list` shows it if you chose another name. + +## 2. Add the connection + +Each Vercel MCP tool takes a `teamId` and a `projectId`. Read both from `.vercel/project.json`, where `orgId` is the team ID, and add them to the project with the other settings the schedules use: + +| Variable | Value | +| --- | --- | +| `AGENT_TEAM_ID` | `orgId` from `.vercel/project.json` | +| `AGENT_PROJECT_ID` | `projectId` from `.vercel/project.json` | +| `AGENT_REPOSITORY` | The agent's own repository, such as `my-org/github-agent` | +| `REVIEW_SLACK_CHANNEL` | The ID of the Slack channel for reports, such as `C0123ABC` | +| `MAINTAINERS` | Comma-separated eve principal IDs of the people who may ask follow-up questions, such as `slack:T0123:U0456` | + +```bash [Terminal] +vercel env add AGENT_TEAM_ID production +``` + +Run `vercel env add` once per variable, then `vercel env pull` to copy them into `.env.local`. + +The connection is one file. Its filename, `vercel`, prefixes every tool name, as in `vercel__list_agent_runs`: + +```ts [agent/connections/vercel.ts] +import { connect } from '@vercel/connect/eve' +import { defineMcpClientConnection } from 'eve/connections' +import { isScheduleAuth } from 'eve/schedules' + +const maintainers = new Set((process.env.MAINTAINERS ?? '').split(',')) + +export default defineMcpClientConnection({ + url: 'https://mcp.vercel.com', + description: "This agent's own production activity on Vercel: Agent Runs with their traces, runtime errors and runtime logs. Read-only.", + tools: { + allow: ['list_agent_runs', 'get_agent_run', 'get_agent_run_trace', 'get_runtime_errors', 'get_runtime_logs'], + }, + toolCall: { + providedArguments: { + teamId: () => process.env.AGENT_TEAM_ID!, + projectId: () => process.env.AGENT_PROJECT_ID!, + }, + }, + auth: ({ session }) => { + const caller = session.auth.current + if (isScheduleAuth(caller) || (caller !== null && maintainers.has(caller.principalId))) { + return connect({ connector: 'vercel/github-agent', principalType: 'app' }) + } + return { + principalType: 'app', + getToken: () => Promise.reject(new Error('Only scheduled runs and maintainers can read this agent\'s runs.')), + } + }, +}) +``` + +Three settings keep the connection narrow: + +- **`tools.allow`** lists five read-only tools. The Vercel MCP also deploys, edits environment variables and manages domains, and none of that is reachable here. +- **`providedArguments`** pins `teamId` and `projectId`. The model never sees either field, so it can only read this agent's project. +- **`auth`** issues a token only to a scheduled run or a maintainer. Anyone else who mentions the agent in Slack gets an error instead of the agent's runtime logs. + +## 3. Write the review procedure + +The schedule's message stays short and points at a skill. The skill holds the procedure, and the model loads it only when a review runs: + +```md [agent/skills/self-review/SKILL.md] +--- +description: Review your own production runs for slow, expensive and failed work, and propose changes to your instructions and config. Load this when a scheduled review fires or a maintainer asks for one. +--- + +# Self review + +1. List the window's runs with `vercel__list_agent_runs` (`period: '7d'`, `pageSize: 100`), and the window before it with `from` and `to` for comparison. +2. Rank them three ways: failed or unanswered runs, the slowest, and the most tokens. Take the top three of each. +3. Read each of those traces with `vercel__get_agent_run_trace`. Look for: + - a tool call that failed and was retried with the same input + - the same tool called many times in one turn, such as paging through a list + - a tool output much larger than the answer needed + - a question to the person that your instructions already answer + - a GitHub tool listed for the session and never called +4. Read `vercel__get_runtime_errors` for the window. Drill into a cluster with `vercel__get_runtime_logs`. +5. Turn what repeats into findings. A finding names the run IDs that show it, the cause, and one change in a named place: `agent/instructions.md`, an option in `agent/extensions/github.ts`, or a new skill. A pattern seen in one run is not a finding. + +Reply with the week's numbers against the previous week, then at most three findings, the strongest first. Quote run IDs and tool names, never what a person wrote. End by asking which findings to file. + +Open nothing on your own. When a maintainer asks you to file a finding, create one issue per finding in your own repository, with the evidence and the proposed change. + +When nothing repeats, reply in one line that the week was clean. +``` + +The findings point at files the agent's own config already has, so each proposal is a change a person can review in a pull request. + +## 4. Schedule the weekly review + +A schedule with a `run` handler starts a session on a channel. This one opens a new Slack thread each Monday: + +```ts [agent/schedules/weekly-review.ts] +import { defineSchedule } from 'eve/schedules' +import slack from '../channels/slack' + +export default defineSchedule({ + cron: '0 8 * * 1', + run({ to, waitUntil, appAuth }) { + waitUntil( + to(slack, { channelId: process.env.REVIEW_SLACK_CHANNEL! }).send( + `Load the self-review skill and review your production runs from the last 7 days. Your source is in ${process.env.AGENT_REPOSITORY}.`, + { auth: appAuth }, + ), + ) + }, +}) +``` + +The session runs as the app, so `isScheduleAuth` lets the connection issue its token. The report lands in the thread, and the thread stays a conversation: a maintainer's reply continues the same session, with the traces it read still in context. Asking it to file a finding calls `createIssue`, which asks for approval in the thread before it runs. + +On Vercel, schedules run in UTC, so `'0 8 * * 1'` fires at 08:00 UTC on Mondays. + +## 5. Watch for failures every day + +A weekly report is too slow for a failure. A second schedule checks the last day and stays quiet when there is nothing to say. It needs eve's `no_reply` tool, which ends a turn without posting: + +```bash [Terminal] +npx eve add tool/no_reply +``` + +```ts [agent/schedules/failure-watch.ts] +import { defineSchedule } from 'eve/schedules' +import slack from '../channels/slack' + +export default defineSchedule({ + cron: '0 7 * * *', + run({ to, waitUntil, appAuth }) { + waitUntil( + to(slack, { channelId: process.env.REVIEW_SLACK_CHANNEL! }).send( + 'Check your production runs and runtime errors from the last 24 hours. If no run failed and no error cluster is new, call no_reply. Otherwise post one line per failure with the run ID and the likely cause.', + { auth: appAuth }, + ), + ) + }, +}) +``` + +This one needs no skill: it reads two lists and posts a few lines. + +## Run it + +`npx eve dev` never fires schedules on their own, so it serves a route that fires one by name: + +```bash [Terminal] +npx eve dev +``` + +```bash [Terminal] +curl -X POST http://localhost:2000/eve/v1/dev/schedules/weekly-review +``` + +The review reads the deployed agent's production runs, and the report appears in the Slack channel. Reply "file the first finding" in the thread and approve the issue. When the report reads well, deploy with `npx eve deploy`, then check **Settings → Cron Jobs** in the Vercel project for both schedules. + +## FAQ + +::accordion + +:::accordion-item{label="Can the agent change its own instructions?"} +Yes, through a pull request. Ask in the thread, for example "open a pull request with that change to `agent/instructions.md`". The GitHub tools create the branch, the commit and the pull request, and each write asks for approval. The agent can't merge it unless you approve that too, and it takes effect on the next deploy. Keep the merge with a person: an agent that rewrites its own prompt without review drifts in ways no single change shows. +::: + +:::accordion-item{label="What if I don't want the agent to read conversations?"} +Remove `get_agent_run_trace` from `tools.allow`. The review then works from run metadata alone: status, duration, model, trigger and token usage, which still finds slow and failing runs but not why they happened. A trace holds what people asked the agent, including Slack messages and GitHub content. +::: + +:::accordion-item{label="Does the review cover cost?"} +Agent Runs report tokens, not dollars. For spend per model, read the [AI Gateway](https://vercel.com/docs/ai-gateway) usage for the project, or price the token counts from the gateway's model list. +::: + +:::accordion-item{label="Why not a markdown schedule?"} +A markdown schedule has no channel. It discards the reply, and a tool that needs approval fails the session instead of waiting. The handler form posts to Slack, so the report is readable, and filing an issue can wait for your answer. +::: + +:::accordion-item{label="Is there a larger example?"} +[Evi](https://github.com/HugoRCD/evlog/tree/main/apps/evi), the maintainer agent of evlog, runs this loop with more lenses: a weekly self review over its repository and its own runs, and a weekly cost and model review. Its [`agent/connections/vercel.ts`](https://github.com/HugoRCD/evlog/blob/main/apps/evi/agent/connections/vercel.ts) is the connection this guide simplifies. +::: + +:: From c1f987974d037f3ca33e77d97092a66006db230d Mon Sep 17 00:00:00 2001 From: Hugo Richard Date: Thu, 12 Nov 2026 16:57:19 +0000 Subject: [PATCH 2/3] docs: let the self-improving agent open its own pull requests Rework the guide so the weekly review opens draft pull requests on the agent's own repository through an editFiles approval override limited to scheduled turns, the agent's repository and agent/ branches. Add a figure that shows the weekly runs getting faster with each merged pull request. Correct facts against the sources: the connector needs --connection-method mcp, Agent Runs needs a trace sampling rule, Slack thread replies need a mention, and Evi lives in evloghq/evlog. --- .../components/content/SelfImprovingLoop.vue | 140 ++++++++++++ .../docs/5.guides/8.self-improving-agent.md | 215 +++++++++++++----- 2 files changed, 301 insertions(+), 54 deletions(-) create mode 100644 apps/docs/app/components/content/SelfImprovingLoop.vue diff --git a/apps/docs/app/components/content/SelfImprovingLoop.vue b/apps/docs/app/components/content/SelfImprovingLoop.vue new file mode 100644 index 0000000..30b11e0 --- /dev/null +++ b/apps/docs/app/components/content/SelfImprovingLoop.vue @@ -0,0 +1,140 @@ + + + diff --git a/apps/docs/content/docs/5.guides/8.self-improving-agent.md b/apps/docs/content/docs/5.guides/8.self-improving-agent.md index 598e396..d3072e6 100644 --- a/apps/docs/content/docs/5.guides/8.self-improving-agent.md +++ b/apps/docs/content/docs/5.guides/8.self-improving-agent.md @@ -1,6 +1,6 @@ --- title: Self-improving agent -description: Give an eve GitHub agent read access to its own production runs through the Vercel MCP, so it reviews its traces on a schedule and proposes fixes to its own instructions and config. +description: Give an eve GitHub agent read access to its own production runs through the Vercel MCP, so every week it finds what slowed it down and opens a pull request on its own repository to fix it. seo: title: Build a self-improving AI agent that reviews its own traces navigation: @@ -9,55 +9,96 @@ level: advanced path: /guides/self-improving-agent --- -To let an agent improve itself, connect it to the [Vercel MCP](https://vercel.com/docs/agent-resources/vercel-mcp) and give it a schedule: the Vercel MCP reads the agent's own [Agent Runs](https://vercel.com/docs/agent-resources/vercel-mcp/tools/agent-runs), with each run's status, token usage and trace, and the agent reports what was slow, what failed and what to change. This guide adds that loop to the [`examples/eve`](https://github.com/vercel-labs/github-tools/tree/main/examples/eve) agent, which already answers in Slack and on GitHub. +A self-improving agent reads the record of its own past work, finds what failed or took too long, and changes its own setup to do better. Here, that change is a pull request on the agent's own repository, and it ships only when a person merges it. This guide adds that loop to the [`examples/eve`](https://github.com/vercel-labs/github-tools/tree/main/examples/eve) agent, which already answers people in Slack and on GitHub. + +::self-improving-loop +:: + +## How the loop works + +The loop has four steps, and it runs once a week: + +| Step | Who does it | What happens | +| --- | --- | --- | +| 1. Answer | The agent | It answers people in Slack and on GitHub, as it already does. | +| 2. Trace | Vercel | [Agent Runs](https://vercel.com/docs/agent-runs) records each run: its turns, tool calls, timings and token usage. | +| 3. Review | The agent, on a schedule | Every Monday it reads last week's runs through the [Vercel MCP](https://vercel.com/docs/agent-resources/vercel-mcp) and looks for what repeats: a failing tool, a slow pattern, a wasted call. | +| 4. Pull request | The agent, then you | For each finding, it opens a draft pull request on its own repository that changes its instructions or config. You review it like any other pull request, and merging it ships the change. | + +The agent can open those pull requests without asking, and nothing else: only during the scheduled review, only on its own repository, and only on `agent/` branches. It can't merge. Your review is the step that decides what the agent becomes. ## What you'll build -Every Monday, the agent posts a review of its last week in a Slack channel: the slowest and most expensive runs, the failures, and up to three changes it proposes, each with the run IDs that show the problem. Reply in the thread with "open an issue for the second one" and it files the issue in its own repository, after you approve. Every morning, a second schedule checks the last day for failed runs and new runtime errors, and posts only when it finds one. +You'll add four files to the agent and change one: -The agent never changes itself. It proposes, a person decides, and the change lands through a reviewed pull request like any other. +```text +agent/ +├── connections/vercel.ts # new: reads the agent's own runs through the Vercel MCP +├── skills/self-review/SKILL.md # new: how to review the runs and what to open +├── schedules/ +│ ├── weekly-review.ts # new: every Monday, the review +│ └── failure-watch.ts # new: every day, a message only when a run failed +└── extensions/github.ts # changed: lets the review open its pull requests +``` + +Every Monday, a thread in a Slack channel links the pull requests the review opened, one per finding, at most three. A pull request from the review looks like this: + +> **Call getCiFailureContext first for CI questions** +> +> In 7 of last week's 9 CI questions, `getWorkflowJobLogs` ran three times per run and took 21 of 48 seconds. `getCiFailureContext` returns the failed steps and the end of each failed job's log in one call. Runs: `wrun_8f2…`, `wrun_c41…`, `wrun_e07…`. +> +> `agent/instructions.md`: + For a failed CI run, call `getCiFailureContext` first. ## Before you start -- The agent from [`examples/eve`](https://github.com/vercel-labs/github-tools/tree/main/examples/eve), deployed to Vercel with its Slack channel set up. Agent Runs are recorded for every eve agent deployed to Vercel, so a week of use gives the review something to read. -- The agent's code in a GitHub repository the agent's GitHub App is installed on, so it can file issues there. -- A Slack channel for the reports, with the Slack app invited. Keep it private: a trace contains what people asked the agent. +- **The `examples/eve` agent, deployed.** Follow its [README](https://github.com/vercel-labs/github-tools/tree/main/examples/eve#set-up) through the Slack channel and the deploy. +- **The agent's code in its own GitHub repository**, with the agent's GitHub App installed on it. The App needs Contents (write) and Pull requests (write) there, the [`pr-author` permissions](/auth#permissions-per-preset). With the Deploy button, Vercel creates that repository and connects it to the project, so merging a pull request also deploys it. +- **Agent Runs that record your runs.** Agent Runs is in [beta](https://vercel.com/docs/release-phases#beta) on all plans, billed at [Tracing rates](https://vercel.com/docs/tracing/configure-tracing#usage-and-pricing), and keeps runs for 30 days. It only records a run when the project samples traces. `npx eve deploy` sets that up for a project it creates. For any other project, such as one created with the Deploy button, add a 100% rule under **Settings → Tracing**, as [Agent Runs](https://vercel.com/docs/agent-runs#configure-tracing-for-existing-projects) describes. Then use the agent for a few days, so the review has runs to read. The project's **Observability → Agent Runs** page lists them. +- **A private Slack channel for the reports**, with the Slack app invited. A trace holds what people asked the agent, so keep the reports where only maintainers read them. ## 1. Create a Vercel connector -The Vercel MCP is an OAuth server. A schedule runs with no signed-in user, so the agent needs an app-scoped token that [Vercel Connect](https://vercel.com/docs/connect) issues on its own. From the agent's directory: +The weekly review runs on a schedule, with nobody signed in, so the agent can't use a person's Vercel login. A [Vercel Connect](https://vercel.com/docs/connect) connector gives it a token of its own. From the agent's directory, create one for the Vercel MCP: ```bash [Terminal] -vercel connect create vercel --name github-agent +vercel connect create vercel --connection-method mcp --name github-agent ``` -The CLI opens your browser to sign in to Vercel. Grant the team that owns the agent's project. The connector acts with your access, so you need access to that project. Attach the connector to the project: +`--connection-method mcp` picks the Vercel MCP. Without it, the CLI asks whether to connect the Vercel REST API or the MCP. If the CLI opens your browser, sign in with a Vercel account that has access to the agent's project. + +Then let the agent's project use the connector: ```bash [Terminal] vercel connect attach vercel/github-agent --yes ``` -`vercel/github-agent` is the connector UID. `vercel connect list` shows it if you chose another name. +`vercel/github-agent` is the connector's UID: the service, then the name. If you chose another name, `vercel connect list` shows the UID. -## 2. Add the connection +## 2. Set the environment variables -Each Vercel MCP tool takes a `teamId` and a `projectId`. Read both from `.vercel/project.json`, where `orgId` is the team ID, and add them to the project with the other settings the schedules use: +The connection, the extension and the schedules read five values from the environment: | Variable | Value | | --- | --- | -| `AGENT_TEAM_ID` | `orgId` from `.vercel/project.json` | -| `AGENT_PROJECT_ID` | `projectId` from `.vercel/project.json` | +| `AGENT_TEAM_ID` | `orgId` in `.vercel/project.json` | +| `AGENT_PROJECT_ID` | `projectId` in `.vercel/project.json` | | `AGENT_REPOSITORY` | The agent's own repository, such as `my-org/github-agent` | -| `REVIEW_SLACK_CHANNEL` | The ID of the Slack channel for reports, such as `C0123ABC` | -| `MAINTAINERS` | Comma-separated eve principal IDs of the people who may ask follow-up questions, such as `slack:T0123:U0456` | +| `REVIEW_SLACK_CHANNEL` | The ID of the reports channel, such as `C0123ABC`. It's at the bottom of the channel's details in Slack. | +| `MAINTAINERS` | The people who may ask the agent about its runs, comma-separated, as `slack::`. For example, `slack:T0123ABC:U0456DEF`. | + +`.vercel/project.json` is written when you link the project. eve names a Slack user `slack::`: `` is the workspace ID, the `T…` part of the address when you open Slack in a browser (`app.slack.com/client/T0123ABC/…`), and `` is the member ID, which **Copy member ID** in a Slack profile copies. + +Add each variable to the project: ```bash [Terminal] vercel env add AGENT_TEAM_ID production ``` -Run `vercel env add` once per variable, then `vercel env pull` to copy them into `.env.local`. +Repeat for the other four, then run `vercel env pull` so `eve dev` reads them from `.env.local` too. + +## 3. Add the connection -The connection is one file. Its filename, `vercel`, prefixes every tool name, as in `vercel__list_agent_runs`: +A connection gives the agent the tools of an MCP server. Its filename, `vercel`, becomes the prefix of every tool name, as in `vercel__list_agent_runs`: ```ts [agent/connections/vercel.ts] import { connect } from '@vercel/connect/eve' @@ -91,46 +132,96 @@ export default defineMcpClientConnection({ }) ``` -Three settings keep the connection narrow: +Three options keep this connection safe: + +- **`tools.allow`** exposes five read-only tools. The Vercel MCP can also deploy, change environment variables and manage domains. None of that is reachable here. +- **`providedArguments`** fills in `teamId` and `projectId` on every call. The model never sees these two inputs, so it can only read this agent's project. +- **`auth`** hands out a token only to a scheduled run or to someone in `MAINTAINERS`. Anyone else who asks the agent about its runs in Slack gets an error, not your runtime logs. + +`principalType: 'app'` means the token belongs to the agent, not to a person, which is what a scheduled run needs. + +## 4. Let the review open its pull requests -- **`tools.allow`** lists five read-only tools. The Vercel MCP also deploys, edits environment variables and manages domains, and none of that is reachable here. -- **`providedArguments`** pins `teamId` and `projectId`. The model never sees either field, so it can only read this agent's project. -- **`auth`** issues a token only to a scheduled run or a maintainer. Anyone else who mentions the agent in Slack gets an error instead of the agent's runtime logs. +With `requireApproval: 'auto'`, opening a pull request always asks for approval. A scheduled review has nobody to ask, so the agent needs one exception: `editFiles`, the tool that creates a branch, commits the edits and opens a pull request in one call, may run without asking when all three of these hold: -## 3. Write the review procedure +```ts [agent/extensions/github.ts] +import githubExtension from '@github-tools/eve-extension' +import { isScheduleAuth } from 'eve/schedules' -The schedule's message stays short and points at a skill. The skill holds the procedure, and the model loads it only when a review runs: +const [owner, repo] = (process.env.AGENT_REPOSITORY ?? '').split('/') + +export default githubExtension({ + connector: 'github/github-agent', + actAs: 'caller', + preset: 'auto', + requireApproval: 'auto', + overrides: { + editFiles: { + approval: ({ session, toolInput }) => { + const scheduled = isScheduleAuth(session.auth.current) + const ownRepository = toolInput?.owner === owner && toolInput?.repo === repo + const agentBranch = typeof toolInput?.branch === 'string' && toolInput.branch.startsWith('agent/') + return scheduled && ownRepository && agentBranch ? 'not-applicable' : 'user-approval' + }, + }, + }, +}) +``` + +- **`scheduled`**: the turn runs as the agent itself, which only a schedule does. When a person asks for the same edit in Slack, it asks them first, as before. +- **`ownRepository`**: the edit targets `AGENT_REPOSITORY`. An edit to any other repository asks. +- **`agentBranch`**: the commit lands on an `agent/` branch, never on `main`. + +`'not-applicable'` lets the call run, and `'user-approval'` asks for approval. Every other write, including `mergePullRequest`, keeps the `'auto'` behavior. In a scheduled run there is nobody to approve them, so they don't happen. + +## 5. Write the review procedure + +A [skill](https://eve.dev/docs/skills) holds the procedure. The model loads it only when a review runs, so it costs nothing on other turns: ```md [agent/skills/self-review/SKILL.md] --- -description: Review your own production runs for slow, expensive and failed work, and propose changes to your instructions and config. Load this when a scheduled review fires or a maintainer asks for one. +description: Review your own production runs for failed, slow and expensive work, and open pull requests on your own repository that fix what repeats. Load this when a scheduled review fires or a maintainer asks for one. --- # Self review -1. List the window's runs with `vercel__list_agent_runs` (`period: '7d'`, `pageSize: 100`), and the window before it with `from` and `to` for comparison. -2. Rank them three ways: failed or unanswered runs, the slowest, and the most tokens. Take the top three of each. -3. Read each of those traces with `vercel__get_agent_run_trace`. Look for: +## Read + +1. List the last 7 days of runs with `vercel__list_agent_runs` (`period: '7d'`, `pageSize: 100`). List the 7 days before them with `from` and `to`, to compare. +2. Pick three groups of up to three runs: runs that failed or never answered, the slowest runs, and the runs that used the most tokens. To compare how long runs took, read their lifecycle events with `vercel__get_agent_run`. +3. Read each picked run with `vercel__get_agent_run_trace`. A trace can come in pages: while the response has a `later` cursor, fetch the next page. An empty trace doesn't mean the run did nothing. Look for: - a tool call that failed and was retried with the same input - - the same tool called many times in one turn, such as paging through a list + - the same tool called several times in one turn, such as paging through a list or a log - a tool output much larger than the answer needed - a question to the person that your instructions already answer - - a GitHub tool listed for the session and never called -4. Read `vercel__get_runtime_errors` for the window. Drill into a cluster with `vercel__get_runtime_logs`. -5. Turn what repeats into findings. A finding names the run IDs that show it, the cause, and one change in a named place: `agent/instructions.md`, an option in `agent/extensions/github.ts`, or a new skill. A pattern seen in one run is not a finding. +4. Read `vercel__get_runtime_errors` for the same 7 days, and look inside a growing error with `vercel__get_runtime_logs`. + +## Decide + +A finding is a pattern seen in at least two runs, with a cause you can name and one change that addresses it. The change goes in a file you already have: `agent/instructions.md`, an option in `agent/extensions/github.ts`, or a new skill under `agent/skills/`. A pattern seen in one run is not a finding. Keep at most three findings, the strongest first. + +## Open + +Before opening anything, list your open pull requests on `agent/` branches. Skip a finding an open pull request already covers. + +For each finding, call `editFiles` once, on your own repository: -Reply with the week's numbers against the previous week, then at most three findings, the strongest first. Quote run IDs and tool names, never what a person wrote. End by asking which findings to file. +- `branch`: `agent/` followed by a short name for the change, such as `agent/ci-failure-context`, with `baseBranch` set to the default branch +- `edits`: the smallest change that addresses the finding +- `pullRequest`: `draft: true`, a title that says what changes, and a body with the numbers, the run IDs, the cause, and what a reviewer should check -Open nothing on your own. When a maintainer asks you to file a finding, create one issue per finding in your own repository, with the evidence and the proposed change. +Quote run IDs and tool names, never what a person wrote. Never merge, and never open a pull request on another repository. -When nothing repeats, reply in one line that the week was clean. +## Report + +Reply with this week's run count, failures and token usage next to last week's, then one line per pull request with its link. When nothing repeats, reply in one line that the week was clean, and open nothing. ``` -The findings point at files the agent's own config already has, so each proposal is a change a person can review in a pull request. +The skill names the exact limits the extension enforces, so the model doesn't waste a call on a pull request the approval policy would stop. -## 4. Schedule the weekly review +## 6. Schedule the weekly review -A schedule with a `run` handler starts a session on a channel. This one opens a new Slack thread each Monday: +A [schedule](https://eve.dev/docs/schedules) starts the agent at a set time instead of waiting for a message. This one opens a new thread in the reports channel every Monday at 08:00 UTC, the time zone schedules use on Vercel: ```ts [agent/schedules/weekly-review.ts] import { defineSchedule } from 'eve/schedules' @@ -149,13 +240,13 @@ export default defineSchedule({ }) ``` -The session runs as the app, so `isScheduleAuth` lets the connection issue its token. The report lands in the thread, and the thread stays a conversation: a maintainer's reply continues the same session, with the traces it read still in context. Asking it to file a finding calls `createIssue`, which asks for approval in the thread before it runs. +`auth: appAuth` runs the session as the agent itself: the identity `isScheduleAuth` checks in the connection and in the extension. `waitUntil` keeps the schedule running until Slack has the message. -On Vercel, schedules run in UTC, so `'0 8 * * 1'` fires at 08:00 UTC on Mondays. +The report thread stays a conversation. Mention the agent in it to continue, since by default the agent only answers thread replies that mention it. A maintainer can ask why a pull request makes a change, or ask for a different one, and the traces the agent read are still in its context. An edit asked for in the thread is a person's request, so it asks that person for approval first. -## 5. Watch for failures every day +## 7. Watch for failures every day -A weekly report is too slow for a failure. A second schedule checks the last day and stays quiet when there is nothing to say. It needs eve's `no_reply` tool, which ends a turn without posting: +A weekly review is too late for a failure. A second schedule checks the last day every morning and posts only when it finds something. It needs eve's `no_reply` tool, which ends a turn without posting: ```bash [Terminal] npx eve add tool/no_reply @@ -170,7 +261,7 @@ export default defineSchedule({ run({ to, waitUntil, appAuth }) { waitUntil( to(slack, { channelId: process.env.REVIEW_SLACK_CHANNEL! }).send( - 'Check your production runs and runtime errors from the last 24 hours. If no run failed and no error cluster is new, call no_reply. Otherwise post one line per failure with the run ID and the likely cause.', + 'Check your production runs and runtime errors from the last 24 hours. If no run failed and no runtime error is new, call no_reply. Otherwise post one line per failure, with the run ID and the likely cause. Open nothing.', { auth: appAuth }, ), ) @@ -178,44 +269,60 @@ export default defineSchedule({ }) ``` -This one needs no skill: it reads two lists and posts a few lines. +This one needs no skill: it reads two lists and posts a few lines. Its message says to open nothing, so a failure gets a person's attention instead of a hasty pull request. ## Run it -`npx eve dev` never fires schedules on their own, so it serves a route that fires one by name: +`eve dev` never fires a schedule on its own. It serves a route that fires one by name instead. Start the dev server: ```bash [Terminal] npx eve dev ``` +Then, in a second terminal, fire the weekly review: + ```bash [Terminal] curl -X POST http://localhost:2000/eve/v1/dev/schedules/weekly-review ``` -The review reads the deployed agent's production runs, and the report appears in the Slack channel. Reply "file the first finding" in the thread and approve the issue. When the report reads well, deploy with `npx eve deploy`, then check **Settings → Cron Jobs** in the Vercel project for both schedules. +The review reads the production runs of your deployed agent, opens its pull requests on `AGENT_REPOSITORY`, and posts the report in the reports channel. Slack sends replies in that thread to the deployed agent, not to `eve dev`, so deploy before you answer it: + +```bash [Terminal] +npx eve deploy +``` + +Review the pull requests on GitHub. When the project is connected to the repository, merging one deploys the agent with the change. Otherwise, run `npx eve deploy` again. In the Vercel dashboard, **Settings → Cron Jobs** lists both schedules. ## FAQ ::accordion -:::accordion-item{label="Can the agent change its own instructions?"} -Yes, through a pull request. Ask in the thread, for example "open a pull request with that change to `agent/instructions.md`". The GitHub tools create the branch, the commit and the pull request, and each write asks for approval. The agent can't merge it unless you approve that too, and it takes effect on the next deploy. Keep the merge with a person: an agent that rewrites its own prompt without review drifts in ways no single change shows. +:::accordion-item{label="Can the agent merge its own pull requests?"} +No. The override covers `editFiles` only. `mergePullRequest` keeps asking for approval, and a scheduled run has nobody to approve it. Keep the merge with a person: a prompt that rewrites itself without review drifts in ways no single change shows. +::: + +:::accordion-item{label="Why draft pull requests?"} +A draft can't be merged until someone marks it ready, so a proposal never lands by accident, and the pull request list shows at a glance which changes came from the review. +::: + +:::accordion-item{label="Can I see the findings before anything is opened?"} +Yes. Remove the `overrides` block from `agent/extensions/github.ts`, and replace the skill's **Open** section with "End by asking which findings to open." The report then lists the findings, and opening one asks the person who asked for it. ::: -:::accordion-item{label="What if I don't want the agent to read conversations?"} -Remove `get_agent_run_trace` from `tools.allow`. The review then works from run metadata alone: status, duration, model, trigger and token usage, which still finds slow and failing runs but not why they happened. A trace holds what people asked the agent, including Slack messages and GitHub content. +:::accordion-item{label="Can I keep the review away from what people wrote?"} +Remove `get_agent_run_trace` from `tools.allow`. The review then reads only run metadata, such as status, trigger, model, lifecycle events and token usage. That still finds failed, slow and expensive runs, but not why they happened. To redact content from Agent Runs itself, see [Configure Agent Runs trace content](https://vercel.com/docs/agent-runs#configure-agent-runs-trace-content). ::: :::accordion-item{label="Does the review cover cost?"} -Agent Runs report tokens, not dollars. For spend per model, read the [AI Gateway](https://vercel.com/docs/ai-gateway) usage for the project, or price the token counts from the gateway's model list. +Agent Runs reports tokens, not dollars. The project's spend per model is in the dashboard's [AI Gateway](https://vercel.com/docs/ai-gateway/observability-and-spend/observability) section, under **Requests → Projects**. ::: :::accordion-item{label="Why not a markdown schedule?"} -A markdown schedule has no channel. It discards the reply, and a tool that needs approval fails the session instead of waiting. The handler form posts to Slack, so the report is readable, and filing an issue can wait for your answer. +A [markdown schedule](https://eve.dev/docs/schedules) has no channel, so it discards the reply. The `run` form used here posts to Slack, so you can read the report and continue the conversation in its thread. ::: :::accordion-item{label="Is there a larger example?"} -[Evi](https://github.com/HugoRCD/evlog/tree/main/apps/evi), the maintainer agent of evlog, runs this loop with more lenses: a weekly self review over its repository and its own runs, and a weekly cost and model review. Its [`agent/connections/vercel.ts`](https://github.com/HugoRCD/evlog/blob/main/apps/evi/agent/connections/vercel.ts) is the connection this guide simplifies. +[Evi](https://github.com/evloghq/evlog/tree/main/apps/evi), the maintainer agent of evlog, runs this loop with more checks: a weekly [self review](https://github.com/evloghq/evlog/blob/main/apps/evi/agent/skills/self-review/SKILL.md) of its repository and its own runs that opens ready pull requests for mechanical fixes, and a weekly cost and model review. Its [`agent/connections/vercel.ts`](https://github.com/evloghq/evlog/blob/main/apps/evi/agent/connections/vercel.ts) is the connection this guide simplifies. ::: :: From 0c6e182e97a7250eaaf54642c18fe2e78a357609 Mon Sep 17 00:00:00 2001 From: Hugo Richard Date: Mon, 16 Nov 2026 08:57:35 +0000 Subject: [PATCH 3/3] docs: show how to give the self-improving agent more freedom Present draft pull requests as the default and add four levels, from a report to an agent that merges its own changes, with the auto-merge and merge approval overrides and what each level trades. --- .../docs/5.guides/8.self-improving-agent.md | 63 ++++++++++++++++--- 1 file changed, 55 insertions(+), 8 deletions(-) diff --git a/apps/docs/content/docs/5.guides/8.self-improving-agent.md b/apps/docs/content/docs/5.guides/8.self-improving-agent.md index d3072e6..1357663 100644 --- a/apps/docs/content/docs/5.guides/8.self-improving-agent.md +++ b/apps/docs/content/docs/5.guides/8.self-improving-agent.md @@ -9,7 +9,7 @@ level: advanced path: /guides/self-improving-agent --- -A self-improving agent reads the record of its own past work, finds what failed or took too long, and changes its own setup to do better. Here, that change is a pull request on the agent's own repository, and it ships only when a person merges it. This guide adds that loop to the [`examples/eve`](https://github.com/vercel-labs/github-tools/tree/main/examples/eve) agent, which already answers people in Slack and on GitHub. +A self-improving agent reads the record of its own past work, finds what failed or took too long, and changes its own setup to do better. Here, that change is a pull request on the agent's own repository. By default it opens as a draft and ships only when a person merges it, and you can [give the agent more freedom](#choose-how-much-the-agent-does-on-its-own) once you trust it. This guide adds that loop to the [`examples/eve`](https://github.com/vercel-labs/github-tools/tree/main/examples/eve) agent, which already answers people in Slack and on GitHub. ::self-improving-loop :: @@ -25,7 +25,7 @@ The loop has four steps, and it runs once a week: | 3. Review | The agent, on a schedule | Every Monday it reads last week's runs through the [Vercel MCP](https://vercel.com/docs/agent-resources/vercel-mcp) and looks for what repeats: a failing tool, a slow pattern, a wasted call. | | 4. Pull request | The agent, then you | For each finding, it opens a draft pull request on its own repository that changes its instructions or config. You review it like any other pull request, and merging it ships the change. | -The agent can open those pull requests without asking, and nothing else: only during the scheduled review, only on its own repository, and only on `agent/` branches. It can't merge. Your review is the step that decides what the agent becomes. +This guide starts with the safe setup: the agent can open those pull requests without asking, and nothing else. It does so only during the scheduled review, only on its own repository, and only on `agent/` branches, and it can't merge. Your review is the step that decides what the agent becomes. How much of that review you keep is your choice: [Choose how much the agent does on its own](#choose-how-much-the-agent-does-on-its-own) goes from a report you read to an agent that merges its own changes. ## What you'll build @@ -293,20 +293,67 @@ npx eve deploy Review the pull requests on GitHub. When the project is connected to the repository, merging one deploys the agent with the change. Otherwise, run `npx eve deploy` again. In the Vercel dashboard, **Settings → Cron Jobs** lists both schedules. +## Choose how much the agent does on its own + +Draft pull requests are a starting point, not a limit. The same loop runs at four levels of freedom, and you move between them by changing the extension's `overrides` and one line of the skill: + +| Level | What the agent does alone | What you do | Change from this guide | +| --- | --- | --- | --- | +| 1. Report | Reads its runs and posts its findings | Ask it to open the ones you want | Remove `overrides`, and replace the skill's **Open** section with "End by asking which findings to open." | +| 2. Draft pull requests (this guide) | Opens a draft per finding | Mark it ready, review and merge | None | +| 3. Auto-merge | Opens a ready pull request and turns on auto-merge | Nothing, unless a check fails or a review is required | Set `draft: false` in the skill, and allow `enablePullRequestAutoMerge` | +| 4. Merge | Opens and merges its own pull requests | Read the report | Allow `mergePullRequest` too | + +Level 3 lets GitHub decide: [auto-merge](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/configuring-pull-request-merges/managing-auto-merge-for-pull-requests-in-your-repository) merges the pull request once the branch's required checks and reviews pass. Turn on **Allow auto-merge** in the repository settings, and add the agent's tests as required checks, such as a CI job that runs its [evals](https://eve.dev/docs/evals). Keep a required review, and level 3 merges the moment you approve. Drop it, and the checks alone decide. + +Both merge tools take the pull request, not its branch, so their approval policy checks the schedule and the repository: + +```ts [agent/extensions/github.ts] +import githubExtension from '@github-tools/eve-extension' +import { isScheduleAuth } from 'eve/schedules' +import type { Approval } from 'eve/tools/approval' + +const [owner, repo] = (process.env.AGENT_REPOSITORY ?? '').split('/') + +const ownRepositoryOnSchedule: Approval = ({ session, toolInput }) => + isScheduleAuth(session.auth.current) && toolInput?.owner === owner && toolInput?.repo === repo + ? 'not-applicable' + : 'user-approval' + +export default githubExtension({ + connector: 'github/github-agent', + actAs: 'caller', + preset: 'auto', + requireApproval: 'auto', + overrides: { + editFiles: { + approval: ({ session, toolInput }) => { + const scheduled = isScheduleAuth(session.auth.current) + const ownRepository = toolInput?.owner === owner && toolInput?.repo === repo + const agentBranch = typeof toolInput?.branch === 'string' && toolInput.branch.startsWith('agent/') + return scheduled && ownRepository && agentBranch ? 'not-applicable' : 'user-approval' + }, + }, + enablePullRequestAutoMerge: { approval: ownRepositoryOnSchedule }, + // Level 4: mergePullRequest: { approval: ownRepositoryOnSchedule }, + }, +}) +``` + +Update the skill to match: at level 3, "After opening a pull request, call `enablePullRequestAutoMerge` on it". At level 4, "Merge a pull request with `mergePullRequest` once its checks pass". Branch protection still applies at every level: a merge the repository's rules block fails, whatever the approval policy says. + +Each level up trades your review for your checks. Move up once the reports and pull requests at the level below have been right for a few weeks, and only as far as your tests can catch a bad change. A prompt that rewrites itself without anyone looking can drift in ways no single change shows, and at level 4 the weekly report is the only place you'd notice. + ## FAQ ::accordion :::accordion-item{label="Can the agent merge its own pull requests?"} -No. The override covers `editFiles` only. `mergePullRequest` keeps asking for approval, and a scheduled run has nobody to approve it. Keep the merge with a person: a prompt that rewrites itself without review drifts in ways no single change shows. +Not with this guide's setup. The override covers `editFiles` only, so `mergePullRequest` keeps asking for approval, and a scheduled run has nobody to approve it. To let it merge, allow auto-merge or merging, as [Choose how much the agent does on its own](#choose-how-much-the-agent-does-on-its-own) describes. ::: :::accordion-item{label="Why draft pull requests?"} -A draft can't be merged until someone marks it ready, so a proposal never lands by accident, and the pull request list shows at a glance which changes came from the review. -::: - -:::accordion-item{label="Can I see the findings before anything is opened?"} -Yes. Remove the `overrides` block from `agent/extensions/github.ts`, and replace the skill's **Open** section with "End by asking which findings to open." The report then lists the findings, and opening one asks the person who asked for it. +A draft can't be merged until someone marks it ready, so a proposal never lands by accident, and the pull request list shows at a glance which changes came from the review. That makes it the safe default while you learn what the review finds. ::: :::accordion-item{label="Can I keep the review away from what people wrote?"}