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/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/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..1357663 --- /dev/null +++ b/apps/docs/content/docs/5.guides/8.self-improving-agent.md @@ -0,0 +1,375 @@ +--- +title: Self-improving agent +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: + icon: i-nucleo-refresh-2 +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. 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 +:: + +## 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. | + +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 + +You'll add four files to the agent and change one: + +```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 `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 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 --connection-method mcp --name github-agent +``` + +`--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's UID: the service, then the name. If you chose another name, `vercel connect list` shows the UID. + +## 2. Set the environment variables + +The connection, the extension and the schedules read five values from the environment: + +| Variable | Value | +| --- | --- | +| `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 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 +``` + +Repeat for the other four, then run `vercel env pull` so `eve dev` reads them from `.env.local` too. + +## 3. Add the connection + +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' +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 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 + +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: + +```ts [agent/extensions/github.ts] +import githubExtension from '@github-tools/eve-extension' +import { isScheduleAuth } from 'eve/schedules' + +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 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 + +## 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 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 +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: + +- `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 + +Quote run IDs and tool names, never what a person wrote. Never merge, and never open a pull request on another repository. + +## 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 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. + +## 6. Schedule the weekly review + +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' +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 }, + ), + ) + }, +}) +``` + +`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. + +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. + +## 7. Watch for failures every day + +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 +``` + +```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 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 }, + ), + ) + }, +}) +``` + +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 + +`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 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. + +## 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?"} +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. 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?"} +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 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](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/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. +::: + +::