Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,14 @@ INTERNAL_API_SECRET=
# admin — if your env points at production APIs, that is production admin.
# NUXI_CLI_ADMIN=1

# Optional: a GitHub personal access token. Nuxi's coder subagent uploads its
# screenshots and recordings with it as GitHub attachments, to show them in
# pull requests. GitHub refuses that upload from the token of a GitHub App, so
# the `nuxi-code` connector can't do it. The token's account needs write access
# to the repositories Nuxi works on, and a classic token needs the `repo`
# scope. Use a token of a bot account: every attachment belongs to its account.
# NUXI_GITHUB_ATTACHMENTS_PAT=

# Canonical site URL for MCP + internal API callbacks (also used for OG images
# when pre-rendering the docs)
NUXT_PUBLIC_SITE_URL=
Expand Down
37 changes: 34 additions & 3 deletions layers/nuxi/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,14 +87,45 @@ Dispatch is restricted to channels listed under `discord.channels.admin`, `.publ
When someone on Slack or in an admin Discord channel gives Nuxi a coding task on nuxt.com, such as a fix, a feature, a content change or a question about the code, Nuxi hands it to the `coder` subagent (`agent/subagents/coder/`). `coder` is a coding agent on Claude Opus 5.5 that delivers its changes as pull requests. It mounts [`@github-tools/eve-extension`](https://github-tools.com/integrations/eve) with the `pr-author` preset, trimmed to what opening a pull request needs. It makes the change on a new `nuxi/*` branch of `nuxt/nuxt.com` with `editFiles`, opens a pull request when it's done, and replies with the link. It never merges.

- **Who:** `coder`'s `agent.ts` returns `null` outside Slack, `discord.channels.admin` channels, and `pnpm nuxi` with `NUXI_CLI_ADMIN=1`, so the web chat, public Discord channels and schedules never see it or its tools. `githubToolsApproval` in `agent/lib/github.ts`, the root agent's `approval` policy, also covers subagents and denies every `github__*` call anywhere else.
- **Where:** `guardrails` refuse any call outside `nuxt/nuxt.com` and any write outside `nuxi/*` branches.
- **Approval:** creating the branch, committing and opening the pull request run without asking; a person reviews and merges on GitHub. `updatePullRequest` still asks the person who requested it, with **Approve** and **Deny** buttons in the thread. On Discord, the buttons need the Interactions Endpoint URL from the [Discord setup](#discord-channel).
- **Tools:** `coder/tools/` disables eve's sandbox tools (`bash` and the file tools), so it changes code through the GitHub API only and never needs a sandbox. It keeps `web_search` and `web_fetch` to read docs, issues and pages linked in the request. `web_fetch` stays off on the root agent, which serves public chats.
- **Where:** `GITHUB_REPOSITORIES` in `agent/lib/github.ts` lists the repositories `coder` works on, which is `nuxt/nuxt.com` for now. `guardrails` refuse any call outside that list and any write outside `nuxi/*` branches. See [Work on another repository](#work-on-another-repository).
- **Approval:** creating the branch, committing and opening the pull request run without asking; a person reviews and merges on GitHub. `updatePullRequest` still asks the person who requested it, with **Approve** and **Deny** buttons in the thread. So does a commit to a branch that already has an open pull request (`githubToolsApproval` in `agent/lib/github.ts`): `coder` can't add to a pull request from another task, or to its own on a follow-up, without a click. The same policy denies a commit that names no branch, or a repository outside the list. It compares repository names without their case, as GitHub does. On Discord, the buttons need the Interactions Endpoint URL from the [Discord setup](#discord-channel).
- **Tools:** `coder` changes code through the GitHub API only. Its sandbox holds a browser and no checkout, see [Browser and captures](#browser-and-captures). `coder/tools/` disables `edit_file` and `write_file`, and keeps `bash` and `read_file` to work on files in the sandbox, such as a capture or a logo. It keeps `web_search` and `web_fetch` to read docs, issues and pages linked in the request. `web_fetch` stays off on the root agent, which serves public chats.

On Slack, Nuxi first moves the request into a [code channel](https://docs.slack.dev/ai/slack-code) with `tools/open_code_channel.ts`, offered to the same people as `coder`. The channel starts with the thread so far and invites the person who asked. Every message in it reaches Nuxi without a mention, the whole channel is one session, and anyone in it can stop the agent from Slack. This needs **Code Channels** turned on in the `slack/nuxi` and `slack/nuxi-preview` connector settings, which adds the `code_channels:manage` scope and the `message.session` and `agent_session_stopped` events, plus the `groups:read` and `mpim:read` bot scopes. Discord has no equivalent and keeps using threads.

Auth uses the `nuxi-code` GitHub App on the `nuxt` org through the Vercel Connect connector `github/nuxi-code`, connected to every environment of the project. `coder` runs with `actAs: 'caller'`: every call uses the GitHub token of the person who asked, so the branch, commits and pull request are theirs, and GitHub enforces their own access to `nuxt/nuxt.com`. The extension's `attribution` still credits the App: the pull request body ends with "Generated by nuxi-code", and the commits list the App's bot as co-author. The first time someone asks, Nuxi replies with a sign-in button to authorize the App on their GitHub account; the task continues once they have. A person never falls back to the App's own token. Only `pnpm nuxi` with `NUXI_CLI_ADMIN=1`, which has no GitHub user, runs as the App, so local tests act with the App's permissions. `searchCode` is excluded because its free-text query can name another repository, which the `repositories` guardrail can't check. The App needs **Contents** and **Pull requests** (read and write) and **Metadata** (read).

### Browser and captures

`coder` has its own sandbox (`coder/sandbox.ts`) with Chromium, [agent-browser](https://agent-browser.dev) and ffmpeg. It uses the sandbox to look at pages, and to produce the images a task needs instead of leaving them to a person. For example, a showcase pull request arrives with its screenshot and logo. A task that only asks for a capture, such as a clip of a page for a Slack reply, opens no pull request.

- **Browser:** `coder/extensions/browser/` mounts [`@agent-browser/eve`](https://www.npmjs.com/package/@agent-browser/eve) as `browser__*`, which opens and operates any public page. The sandbox holds no credentials and no checkout, so `coder` can't run the site or capture its own branch. On Vercel, the sandbox's firewall refuses every connection to a private address (`networkPolicy` in `coder/sandbox.ts`). A local Docker sandbox has no such rule: there, the capture tools only refuse a URL that names a private address. The capture tools drive the same browser, so their calls run one at a time, even when the model asks for several together.
- **`capture_screenshot`:** saves a 2560×1440 WebP, the format of `public/assets/websites/`, and shows the frame to the model. Its `cookies`, `hideElements`, `removeElements`, `scripts` and `delay` options match `screenshotOptions` in `content/showcase.yml`.
- **`record_video`:** plays a list of steps with a visible cursor, saves an MP4 without sound, and shows six frames spread over the clip to the model. GitHub plays a video inline only from its own attachments, which is where `publish_media` uploads it.
- **`publish_media`:** uploads a capture to GitHub as an attachment of the repository, the upload behind [`gh --attach`](https://docs.github.com/en/github-cli/github-cli/attaching-files-with-github-cli), and returns its link and its Markdown once GitHub serves it. This is how a capture reaches a pull request body, and nothing is written to the repository. An image embeds as `![alt](url)`, and the URL of a clip alone on a line renders as a video player. GitHub serves the link to everyone only once a pull request, an issue or a comment of a public repository embeds it, so the link of a capture that no pull request embeds, such as one made for a Slack reply, can answer 404. GitHub has no way to delete an attachment.
- **`commit_assets`:** commits images to a `nuxi/*` branch, because `editFiles` writes text only. It accepts images of 1 MB at most whose bytes match their extension, so `capture_screenshot` takes a lower `quality` for a page that passes the limit. It uses the same GitHub token as the GitHub tools. Unlike `editFiles`, its commits don't list the App's bot as co-author.

Every one of these tools calls `assertCanUseGithubTools`, so they are available to the same people as the GitHub tools. Two skills in `coder/skills/` hold the procedures: `showcase-entry` for a complete showcase entry, and `visual-evidence` for the captures of a pull request.

Setup:

- **Deploys:** `eve build` installs the browser into a sandbox snapshot once per build, which takes about a minute. Sessions start from that snapshot.
- **Local:** the browser needs Docker running before `pnpm nuxi`. The first browser call builds the sandbox image, which takes about two minutes. Without Docker, eve falls back to just-bash, which runs no native binaries, so the browser and capture tools fail. On Apple Silicon, the Docker sandbox gets no browser, because Chrome for Testing has no Linux arm64 build.
- **Attachment token:** `publish_media` needs `NUXI_GITHUB_ATTACHMENTS_PAT` on the eve service, a GitHub personal access token. GitHub accepts the attachment upload from a personal access token only: it answers 404 to the `nuxi-code` installation token and to the token of a person signed in through the App ([cli/cli#14309](https://github.com/cli/cli/issues/14309)). So this tool never uses the token of the person who asked, and every attachment belongs to the token's account. That account needs write access to each repository in `GITHUB_REPOSITORIES`, and a classic token needs the `repo` scope. Use a token of a bot account instead of a person's. Without the variable, the tool reports that it has no token, and the other tools still work.
- **Local GitHub access:** the GitHub tools and `commit_assets` need a linked Vercel project (`vercel link`), because Vercel Connect authenticates with the project's OIDC token. Without it, they fail with `VercelOidcTokenError`.
- **Local publishing:** set `NUXI_GITHUB_ATTACHMENTS_PAT` in `.env`. It needs no Vercel project.
- **`--no-default-extensions`:** the `dev` script passes this flag to turn off eve's bundled self-modification subagent. That subagent uses a just-bash sandbox, and eve prepares every sandbox when `coder` first opens its own. Preparing it runs `pnpm add just-bash` in `layers/nuxi`, which fails on the ignored build scripts and leaves a stray lockfile.

### Work on another repository

Nothing in `coder`'s tools is specific to `nuxt/nuxt.com`. To let it work on another repository:

1. Add the repository to `GITHUB_REPOSITORIES` in `agent/lib/github.ts`. The first entry stays the default.
2. Give the `nuxi-code` GitHub App access to the repository, and give the account of `NUXI_GITHUB_ATTACHMENTS_PAT` write access to it.
3. Add a section for it to `coder/instructions.md`, like the `nuxt/nuxt.com` one. Say where its site is deployed, where its images live, and how its pull requests preview.

`commit_assets` and `publish_media` take the repository as an input, and the `github__*` tools take `owner` and `repo`.

## Caller identity

`agent/lib/identity/context.ts` resolves `Context.person` (id, name, bot flag) for every surface, and `agent/lib/identity/caller-instructions.ts` renders it into the always-on prompt so "who am I?" has an answer. Discord's display name (`global_name`) comes for free from the inbound message payload; the `@`-mention handle (`username`) is still kept on the auth context for future use, it's just not what the model sees. Slack's `app_mention`/`message` events only carry a user id — `channels/slack.ts` resolves the real name via `users.info` (`agent/lib/slack/api.ts`, cached 1h per user), which needs the **`users:read`** bot scope on top of the ones above; without it, Slack callers fall back to their user id.
Expand Down
116 changes: 116 additions & 0 deletions layers/nuxi/agent/lib/github-files.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import { checkedMediaType } from './media/media-type.js'

const API = 'https://api.github.com'
/** Same rule as the `branches` guardrail of the GitHub tools. */
const BRANCH = /^nuxi\/[a-z0-9][a-z0-9._/-]*$/
const FILE_PATH = /^[\w.-]+(?:\/[\w.-]+)*$/

/** Showcase screenshots are 80 to 350 KB; an image near this is a mistake, not an asset. */
export const MAX_COMMIT_BYTES = 1024 * 1024

export class GithubRequestError extends Error {
constructor(message: string, readonly status: number) {
super(message)
this.name = 'GithubRequestError'
}
}

/** Where a call goes, and as whom. */
interface Github {
/** `owner/name` */
readonly repository: string
readonly token: string
readonly fetchImpl?: typeof fetch
}

/** GET `url`, or POST `body` to it: bytes as they are, anything else as JSON. */
export async function request<T>({ token, fetchImpl = fetch }: Pick<Github, 'token' | 'fetchImpl'>, url: string, body?: object): Promise<T> {
const binary = body instanceof Uint8Array
const response = await fetchImpl(url, {
method: body ? 'POST' : 'GET',
headers: {
accept: 'application/vnd.github+json',
authorization: `Bearer ${token}`,
...(body && { 'content-type': binary ? 'application/octet-stream' : 'application/json' })
},
body: binary ? Buffer.from(body) : body && JSON.stringify(body),
signal: AbortSignal.timeout(60_000)
})
const data = await response.json().catch(() => ({})) as T & { message?: string }
if (!response.ok) {
throw new GithubRequestError(`GitHub answered HTTP ${response.status} on ${new URL(url).pathname}: ${data.message ?? 'no message'}`, response.status)
}
return data
}

/** The number of the open pull request whose head is `branch`, if it has one. */
export async function openPullRequestOf({ branch, ...github }: Github & { readonly branch: string }): Promise<number | undefined> {
const head = `${github.repository.split('/')[0]}:${branch}`
const pulls = await request<Array<{ number: number }>>(github, `${API}/repos/${github.repository}/pulls?state=open&per_page=1&head=${encodeURIComponent(head)}`)
return pulls[0]?.number
}

interface CommitInput extends Github {
readonly branch: string
/** A conventional commit: the first line is the headline, the rest the body. */
readonly message: string
/** `path` is the repository path, such as `public/assets/websites/world-triathlon.webp`. */
readonly files: ReadonlyArray<{ readonly path: string, readonly bytes: Uint8Array }>
}

const COMMIT_MUTATION = 'mutation ($input: CreateCommitOnBranchInput!) { createCommitOnBranch(input: $input) { commit { oid url } } }'

/**
* Commit images to a `nuxi/*` branch in one commit, creating the branch from the default branch
* when it doesn't exist. `github__editFiles` takes text only, so an image can't go through it.
* GitHub signs a `createCommitOnBranch` commit and records the token's owner as its author.
*/
export async function commitAssets({ branch, message, files, ...github }: CommitInput) {
if (!BRANCH.test(branch) || branch.includes('..')) throw new Error(`Images are committed to a \`nuxi/*\` branch only, not "${branch}".`)
if (!files.length) throw new Error('No files to commit.')
for (const { path, bytes } of files) {
if (!FILE_PATH.test(path) || path.includes('..')) throw new Error(`"${path}" is not a path in the repository.`)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if (checkedMediaType(path, bytes, MAX_COMMIT_BYTES) === 'video/mp4') throw new Error(`"${path}" is a video: only images are committed.`)
}

const repository = `${API}/repos/${github.repository}`
async function headOf(name: string) {
try {
return (await request<{ object: { sha: string } }>(github, `${repository}/git/ref/heads/${name}`)).object.sha
} catch (error) {
if (error instanceof GithubRequestError && error.status === 404) return undefined
throw error
}
}

let head = await headOf(branch)
const createdBranch = !head
if (!head) {
const { default_branch } = await request<{ default_branch: string }>(github, repository)
head = await headOf(default_branch)
if (!head) throw new Error(`Could not read the head of ${default_branch}.`)
await request(github, `${repository}/git/refs`, { ref: `refs/heads/${branch}`, sha: head })
}

const [headline = '', ...rest] = message.trim().split('\n')
const body = rest.join('\n').trim()
const { data, errors } = await request<{
data?: { createCommitOnBranch?: { commit?: { oid: string, url: string } } }
errors?: Array<{ message?: string }>
}>(github, `${API}/graphql`, {
query: COMMIT_MUTATION,
variables: {
input: {
branch: { repositoryNameWithOwner: github.repository, branchName: branch },
expectedHeadOid: head,
message: body ? { headline, body } : { headline },
fileChanges: { additions: files.map(({ path, bytes }) => ({ path, contents: Buffer.from(bytes).toString('base64') })) }
}
}
})

const commit = data?.createCommitOnBranch?.commit
if (!commit) throw new Error(`GitHub refused the commit: ${errors?.map(error => error.message).join('; ') || 'no reason given'}`)

return { repository: github.repository, branch, createdBranch, commitSha: commit.oid, commitUrl: commit.url, paths: files.map(file => file.path) }
}
23 changes: 23 additions & 0 deletions layers/nuxi/agent/lib/github-token.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { connect } from '@vercel/connect/eve'
import type { ToolContext } from 'eve/tools'
import { appToken, GITHUB_CONNECTOR } from './github.js'
import { GithubRequestError } from './github-files.js'

const userAuth = connect(GITHUB_CONNECTOR)

/**
* Run `call` with a GitHub token for `repository`, chosen like the GitHub tools' `actAs: 'caller'`:
* the token of the person who asked, or the App's when no person drives the turn. A person whose
* token GitHub rejects is asked to sign in again.
*/
export async function withGithubToken<T>(ctx: ToolContext, repository: string, call: (token: string) => Promise<T>): Promise<T> {
if (ctx.session.auth.current?.principalType !== 'user') return call(await appToken(repository))

const { token } = await ctx.getToken(userAuth)
try {
return await call(token)
} catch (error) {
if (error instanceof GithubRequestError && error.status === 401) ctx.requireAuth(userAuth)
throw error
}
}
Loading
Loading