From 7a6fa0e66e01c1d4478a5a5ba5d86ebbf23fbfaa Mon Sep 17 00:00:00 2001 From: Hugo Richard Date: Tue, 17 Nov 2026 11:18:08 +0000 Subject: [PATCH] feat(eve): credit the GitHub App on pull requests and commits made with a user's token With actAs 'user', or 'caller' and a signed-in user, GitHub records the person as the author of what the agent writes. The extension now credits the App by default: createPullRequest ends the body with a "Generated by" line linking the App, and the commit tools add the App's bot account to coAuthors with the noreply address GitHub links to it. The App is read from the user's token through GET /user/installations, once per process and connector. Calls that run as the App add nothing. `attribution: false` turns both credits off, `{ footer, coAuthor }` picks. The SDK exports githubAppBot, githubAppBotIdentity, withGithubAppFooter and GITHUB_COMMIT_TOOLS from eve-runtime, and adds APP_BOT_UNKNOWN. --- .changeset/eve-attribution.md | 23 ++++++++ apps/docs/content/docs/3.core/7.errors.md | 1 + .../docs/content/docs/4.integrations/2.eve.md | 20 +++++++ apps/docs/content/docs/7.reference/1.api.md | 2 +- .../references/eve-extension.md | 3 +- packages/github-tools-eve-extension/README.md | 1 + .../extension/extension.ts | 24 ++++++++ .../extension/lib/attribution.ts | 55 ++++++++++++++++++ .../extension/tools/github.ts | 11 +++- .../github-tools/src/core/attribution.test.ts | 56 +++++++++++++++++++ packages/github-tools/src/core/attribution.ts | 46 +++++++++++++++ packages/github-tools/src/core/errors.ts | 6 ++ packages/github-tools/src/eve-runtime.ts | 2 + tests/eve-act-as/README.md | 3 +- tests/eve-act-as/agent/agent.ts | 10 +++- tests/eve-act-as/agent/extensions/github.ts | 4 +- tests/eve-act-as/agent/extensions/strict.ts | 7 ++- tests/eve-act-as/evals/act-as.eval.ts | 26 +++++++++ tests/eve-act-as/fixtures/github-calls.ts | 12 ++++ tests/eve-act-as/fixtures/stubs.ts | 24 +++++++- 20 files changed, 323 insertions(+), 13 deletions(-) create mode 100644 .changeset/eve-attribution.md create mode 100644 packages/github-tools-eve-extension/extension/lib/attribution.ts create mode 100644 packages/github-tools/src/core/attribution.test.ts create mode 100644 packages/github-tools/src/core/attribution.ts diff --git a/.changeset/eve-attribution.md b/.changeset/eve-attribution.md new file mode 100644 index 00000000..4c427196 --- /dev/null +++ b/.changeset/eve-attribution.md @@ -0,0 +1,23 @@ +--- +'@github-tools/eve-extension': minor +'@github-tools/sdk': minor +--- + +Credit the GitHub App on pull requests and commits that run with a person's token. + +With `actAs: 'user'`, or `'caller'` and a signed-in user, GitHub records the person as the author of what the agent writes. The extension now credits the App by default: + +- `createPullRequest` ends the body with `Generated by [](https://github.com/apps/).` +- `createOrUpdateFile`, `editFiles`, `mergePullRequest` and `enablePullRequestAutoMerge` add the App's bot account to `coAuthors`, as `Co-authored-by: [bot] [bot]@users.noreply.github.com>`. + +The App is read from the person's token, so the connector must be backed by a GitHub App. Calls that run as the App add nothing. Turn it off or pick one credit with `attribution`: + +```ts +export default githubExtension({ + connector: 'github/my-connector', + actAs: 'caller', + attribution: false, // or { footer: true, coAuthor: false } +}) +``` + +`@github-tools/sdk/eve-runtime` exports the pieces: `githubAppBot(token)` reads the App behind a user token, `githubAppBotIdentity(bot)` returns its commit identity, `withGithubAppFooter(body, bot)` adds the footer, and `GITHUB_COMMIT_TOOLS` lists the tools that take `coAuthors`. A user token that GitHub lists no installation to fails with `github_tools.APP_BOT_UNKNOWN`. diff --git a/apps/docs/content/docs/3.core/7.errors.md b/apps/docs/content/docs/3.core/7.errors.md index 04926d23..889a7be5 100644 --- a/apps/docs/content/docs/3.core/7.errors.md +++ b/apps/docs/content/docs/3.core/7.errors.md @@ -75,6 +75,7 @@ Every code starts with `github_tools.`, as in `github_tools.NOT_FOUND`. | --- | --- | --- | | `GUARDRAIL_BLOCKED` | 403 | The call targets a repository or branch outside [`guardrails`](/approval#guardrails), or its input contains what looks like a credential. Checked before any request reaches GitHub, whoever approved the call. The message gives the reason | | `CALLER_FORBIDDEN` | 403 | On the eve extension with [`actAs: 'caller'`](/integrations/eve#per-user-tokens), someone who commented on GitHub asked for a call their role on the target repository doesn't allow. Checked before the call reaches GitHub. The message names the role they have and the one the call needs | +| `APP_BOT_UNKNOWN` | 403 | On the eve extension with [`attribution`](/integrations/eve#credit-the-app), GitHub lists no installation of the App to the person's token, so the App's bot account can't be credited. The connector isn't backed by a GitHub App, or the person reaches no installation of it | ### GitHub API diff --git a/apps/docs/content/docs/4.integrations/2.eve.md b/apps/docs/content/docs/4.integrations/2.eve.md index 4cb23001..35d945a6 100644 --- a/apps/docs/content/docs/4.integrations/2.eve.md +++ b/apps/docs/content/docs/4.integrations/2.eve.md @@ -191,6 +191,25 @@ Only the person who asked for a call can approve it, so a colleague in a shared For a custom rule, pass `{ request, response }` for that tool in `requireApproval`, with an eve [`response` policy](https://eve.dev/docs/tools/human-in-the-loop#authorizing-approval-responses). It replaces both defaults, and the sign-in checks still apply to the people it allows. +### Credit the App + +When a call runs with a person's token, GitHub records that person as its author. So the extension credits the App on what it wrote for them: + +- `createPullRequest` ends the pull request body with `Generated by [](https://github.com/apps/).` +- `createOrUpdateFile`, `editFiles`, `mergePullRequest` and `enablePullRequestAutoMerge` add the App's bot account to `coAuthors`, so the commit message ends with `Co-authored-by: [bot] [bot]@users.noreply.github.com>`. GitHub links that address to the bot account. + +When you squash-merge a person's pull request, GitHub adds each commit author other than the pull request's author as `Co-authored-by`. Commits the App wrote, for example through eve's git extension, therefore credit it on the squash commit without this option. + +The App is read from the person's token, once per process, so the connector must be backed by a GitHub App. Calls that run as the App add nothing, since GitHub already shows the App as their author. Turn both credits off, or pick one: + +```ts [agent/extensions/github.ts] +export default githubExtension({ + connector: 'github/my-connector', + actAs: 'caller', + attribution: { footer: true, coAuthor: false }, +}) +``` + ### Work across several installations An App installed on several accounts needs no config. Each App token is minted for the installation that owns the call's `owner/repo`, after `context` defaults. Tools without a repository, such as `searchCode` and the gist tools, use the connector's default installation. @@ -269,6 +288,7 @@ Pair it with `guardrails`, and try the schedule with `dryRun: true` first. | `connector` | `string \| () => string \| Promise` | Vercel Connect connector name, or a resolver that picks one per call. Wins over `token` | | `actAs` | `'app' \| 'user' \| 'caller' \| { read, write }` | Whose GitHub access a call uses with a connector. Default `'app'`. See [Per-user tokens](#per-user-tokens) | | `approvers` | `'requester' \| 'anyone'` | Who may answer an approval. Default `'requester'`. See [Who can approve](#who-can-approve) | +| `attribution` | `boolean \| { footer?, coAuthor? }` | Credit the App on pull requests and commits that run with a person's token. Default `true`. See [Credit the App](#credit-the-app) | | `connect` | `object \| (ctx, call) => object` | Connect token params for App tokens, such as `installationId`, `repositories` or `scopes`. Can't be combined with `actAs: 'user'` | | `preset` | preset name, array, or `'auto'` | Which tools the model sees. See [Presets](/presets) | | `include` | tool names | Added to the preset, or the whole set without one | diff --git a/apps/docs/content/docs/7.reference/1.api.md b/apps/docs/content/docs/7.reference/1.api.md index 43ab7582..281e02c9 100644 --- a/apps/docs/content/docs/7.reference/1.api.md +++ b/apps/docs/content/docs/7.reference/1.api.md @@ -305,6 +305,6 @@ import githubExtension from '@github-tools/eve-extension' export default githubExtension({ connector: 'github/my-connector', preset: 'code-review' }) ``` -The default export mounts the tools in an eve agent from a file under `agent/extensions/`. The file name becomes the namespace, so `agent/extensions/github.ts` exposes `github__listPullRequests` and so on. It takes `token`, `connector`, `actAs`, `approvers`, `connect`, `preset` (including `'auto'`), `include`, `exclude`, `context`, `requireApproval` (adding `'once'` and predicates), `evaluation`, `overrides`, `author`, `committer`, `coAuthors`, `guardrails` and `dryRun`; [eve](/integrations/eve) documents each one. Needs Node 24 or later and `eve` as a peer. +The default export mounts the tools in an eve agent from a file under `agent/extensions/`. The file name becomes the namespace, so `agent/extensions/github.ts` exposes `github__listPullRequests` and so on. It takes `token`, `connector`, `actAs`, `approvers`, `attribution`, `connect`, `preset` (including `'auto'`), `include`, `exclude`, `context`, `requireApproval` (adding `'once'` and predicates), `evaluation`, `overrides`, `author`, `committer`, `coAuthors`, `guardrails` and `dryRun`; [eve](/integrations/eve) documents each one. Needs Node 24 or later and `eve` as a peer. `@github-tools/eve-extension/channels` exports `githubChannel`, which is eve's `githubChannel` plus `respondTo` (`'anyone'`, `'triagers'`, `'writers'`, `'maintainers'` or `'admins'`), and the `GithubChannelConfig` and `GithubRespondTo` types. See [Choose who the agent answers](/integrations/eve#choose-who-the-agent-answers). diff --git a/apps/docs/skills/github-tools-agents/references/eve-extension.md b/apps/docs/skills/github-tools-agents/references/eve-extension.md index 4f3f118d..a3f68b89 100644 --- a/apps/docs/skills/github-tools-agents/references/eve-extension.md +++ b/apps/docs/skills/github-tools-agents/references/eve-extension.md @@ -36,7 +36,7 @@ Tools are exposed to the model as `__`: `agent/extensions/g ## Config schema -`token`, `connector`, `actAs`, `approvers`, `connect`, `preset`, `include`, `exclude`, `context`, `requireApproval`, `evaluation`, `guardrails`, `dryRun`, `overrides`, `author`/`committer`/`coAuthors`, see `/integrations/eve#config`. `guardrails: { repositories, branches }` deny any call outside the allowed repositories or branch patterns, whoever approves it, with the reason and without asking anyone. They cover the extension's tools only: eve's git extension runs `gh` through `git__gh` without approval, so limit it with its own `github.authorize` check. `dryRun: true` sends no write to GitHub and labels each one "Would create issue on owner/repo". +`token`, `connector`, `actAs`, `approvers`, `attribution`, `connect`, `preset`, `include`, `exclude`, `context`, `requireApproval`, `evaluation`, `guardrails`, `dryRun`, `overrides`, `author`/`committer`/`coAuthors`, see `/integrations/eve#config`. `guardrails: { repositories, branches }` deny any call outside the allowed repositories or branch patterns, whoever approves it, with the reason and without asking anyone. They cover the extension's tools only: eve's git extension runs `gh` through `git__gh` without approval, so limit it with its own `github.authorize` check. `dryRun: true` sends no write to GitHub and labels each one "Would create issue on owner/repo". `token` is `string | (() => Promise)` (`GithubTokenInput`). Pass an async provider for rotating GitHub App installation tokens. Falls back to `GITHUB_TOKEN` when omitted; `connector` takes priority. @@ -95,6 +95,7 @@ export default githubExtension({ - GitHub allows a user-token call only when both the user and the App have access, so a maintainer can merge and a reader gets `403`. - A user who has not authorized the App gets an eve `sign-in` interaction, and the call resumes after it; a `401` asks them to sign in again. A signed-in user never falls back to the App. - `approvers: 'requester'` (default): only the requester can approve or deny, so a colleague in a shared thread cannot approve someone else's request. `'anyone'` (opt-in, for simple shared agents): any signed-in user can approve and anyone can deny; for `'user'`/`'caller'` tools the approved call runs with the approver's token, so GitHub checks and records the approver, and an approver who has not authorized the App signs in before the approval counts. For `'app'` tools the approval is a gate only. +- `attribution` (default `true`): a call that runs with a person's token is authored by them on GitHub, so `createPullRequest` ends the body with `Generated by [](https://github.com/apps/).` and `createOrUpdateFile`/`editFiles`/`mergePullRequest`/`enablePullRequestAutoMerge` add the App's bot as `Co-authored-by`. App-token calls add nothing. `false` turns both off; `{ footer, coAuthor }` picks. Don't also write a "generated by" line into the body yourself. - `'user'`/`'caller'` need `connector`; `connect` configures App tokens and cannot be combined with `actAs: 'user'`. One GitHub App installed on several accounts needs no configuration: each app token targets the installation owning the call's `owner/repo`, after `context` defaults. Tools without a repository target (search, gists, notifications) use the connector's default installation. Set `installationId`, `authorizationDetails` or `repositories` in `connect` to pin one installation; user subjects are left untouched. `connect` also accepts a custom `(ctx, call) => params` resolver, where `call` is `{ toolName, input, owner?, repo? }`. A missing installation surfaces as `CONNECT_INSTALLATION_REQUIRED` naming the account. diff --git a/packages/github-tools-eve-extension/README.md b/packages/github-tools-eve-extension/README.md index f03a638d..515e3c85 100644 --- a/packages/github-tools-eve-extension/README.md +++ b/packages/github-tools-eve-extension/README.md @@ -118,6 +118,7 @@ channels/ | `token` | `string \| (() => Promise)` (optional) | PAT string, or an async provider for rotating tokens (e.g. a GitHub App installation token) — the same `GithubTokenInput` the SDK accepts; falls back to `GITHUB_TOKEN` when omitted and `connector` is not set | | `connector` | `string \| (() => string \| Promise)` (optional) | Vercel Connect connector name, or a resolver to pick one dynamically (e.g. per environment/tenant); takes priority over `token` | | `actAs` | `'app' \| 'user' \| 'caller' \| { read, write }` (optional) | Whose GitHub access the tools use when `connector` is set. `'app'` (default) uses the GitHub App installation. `'user'` runs each call with the signed-in eve user's own GitHub token, so the agent can do what that user can do on GitHub and nothing more; sessions without a signed-in user fail. `'caller'` uses the user when one drives the turn and the App otherwise (schedules, bots). Users who have not authorized the App get a sign-in prompt and never fall back to the App. Someone who comments on eve's GitHub channel can't sign in, so their call runs as the App once their own role on the target repository allows it (Read for a read, Write for a write), and fails with `CALLER_FORBIDDEN` otherwise. `{ read, write }` picks per tool kind, `overrides..actAs` per tool. The default may change to `'caller'` in a future major version | +| `attribution` | `boolean \| { footer?, coAuthor? }` (optional) | Credit the GitHub App when a call runs with a person's token, since GitHub then records the person as the author. `createPullRequest` ends the body with `Generated by [](https://github.com/apps/).`, and the commit tools add the App's bot account to `coAuthors`. The App is read from the person's token, once per process. Calls that run as the App add nothing. Default `true`; `false` turns both off | | `approvers` | `'requester' \| 'anyone'` (optional) | Who may answer an approval. `'requester'` (default) is only the person who asked, so a colleague cannot approve your request. `'anyone'` is an opt-in that lets any signed-in user approve and anyone deny; for `'user'` and `'caller'` tools the approved call runs with the approver's GitHub token, after they sign in | | `connect` | `record \| ((ctx, call) => record)` (optional) | Passed through to `getToken` when `connector` is set. `connect.subject` defaults to `{ type: 'app' }` (the project's GitHub App installation); for per-user tokens, use `actAs`. App tokens target the installation owning each call's repository unless `installationId`, `authorizationDetails` or `repositories` pins one; pass a `(ctx, call) => record` resolver for other per-call rules | | `preset` | preset name, array, or `'auto'` | `code-review`, `issue-triage`, `ci-ops`, `repo-explorer`, `security-audit`, `release-manager`, `discussion-moderator`, `notification-inbox`, `pr-author`, `maintainer`; `'auto'` lists the tools the session's first request needs and defers the rest | diff --git a/packages/github-tools-eve-extension/extension/extension.ts b/packages/github-tools-eve-extension/extension/extension.ts index 5d012fa2..aa23fabf 100644 --- a/packages/github-tools-eve-extension/extension/extension.ts +++ b/packages/github-tools-eve-extension/extension/extension.ts @@ -92,6 +92,14 @@ export type GithubExtensionActAs = GithubActAs | { read?: GithubActAs, write?: G /** Who may answer an approval: only the requester, or any signed-in user. */ export type GithubExtensionApprovers = 'requester' | 'anyone' +/** Which credits `attribution` adds. Each defaults to `true`. */ +export interface GithubExtensionAttribution { + /** End the body of a pull request with a line saying the App generated it. */ + footer?: boolean + /** Add the App's bot account as `Co-authored-by` on commits. */ + coAuthor?: boolean +} + /** Per-tool overrides, including the tool's own `actAs`. */ export type GithubExtensionToolOverrides = { [K in GithubToolName]?: NonNullable & { actAs?: GithubActAs } @@ -142,6 +150,21 @@ export interface GithubExtensionConfig { * `'caller'` in a future major version. */ actAs?: GithubExtensionActAs + /** + * Credit the GitHub App on what a person writes through it. When a call runs with a person's + * GitHub token (`actAs: 'user'`, or `'caller'` with a signed-in user), GitHub records that person + * as the author, so by default: + * + * - `createPullRequest` ends the body with `Generated by [](https://github.com/apps/).` + * - `createOrUpdateFile`, `editFiles`, `mergePullRequest` and `enablePullRequestAutoMerge` add the + * App's bot account to `coAuthors`, so the commit message carries + * `Co-authored-by: [bot] [bot]@users.noreply.github.com>`. + * + * The App is read from the person's token, so the connector must be backed by a GitHub App. + * Calls that run as the App add nothing: the App is already their author. Pass `false` to turn + * both off, or `{ footer, coAuthor }` to pick. + */ + attribution?: boolean | GithubExtensionAttribution /** * Who may answer an approval. * @@ -244,6 +267,7 @@ const configSchema = z.object({ ).optional(), actAs: z.union([actAsSchema, z.object({ read: actAsSchema.optional(), write: actAsSchema.optional() })]).optional(), approvers: z.enum(['requester', 'anyone']).optional(), + attribution: z.union([z.boolean(), z.object({ footer: z.boolean().optional(), coAuthor: z.boolean().optional() })]).optional(), connect: z.union([ z.record(z.string(), z.unknown()), z.custom(value => typeof value === 'function'), diff --git a/packages/github-tools-eve-extension/extension/lib/attribution.ts b/packages/github-tools-eve-extension/extension/lib/attribution.ts new file mode 100644 index 00000000..9c0495da --- /dev/null +++ b/packages/github-tools-eve-extension/extension/lib/attribution.ts @@ -0,0 +1,55 @@ +import { resolveGithubConnector } from '@github-tools/sdk/connect' +import { + GITHUB_COMMIT_TOOLS, + githubAppBot, + githubAppBotIdentity, + withGithubAppFooter, + type EveGithubToolsOptions, + type GithubAppBot, + type GithubToolName, +} from '@github-tools/sdk/eve-runtime' +import extension from '../extension' + +// The App behind a connector never changes, so each process reads its bot once. +const bots = new Map>() + +async function appBot(token: string): Promise { + const connector = await resolveGithubConnector(extension.config.connector!) + const cached = bots.get(connector) + if (cached) return cached + const bot = githubAppBot(token) + bots.set(connector, bot) + bot.catch(() => bots.delete(connector)) + return bot +} + +function credits() { + const { attribution = true } = extension.config + if (typeof attribution === 'boolean') return { footer: attribution, coAuthor: attribution } + return { footer: attribution.footer ?? true, coAuthor: attribution.coAuthor ?? true } +} + +/** + * The input and options of a call that runs with a person's `token`, with the App credited as + * `attribution` asks: a footer on a new pull request, a co-author on a commit. + */ +export async function withAttribution( + name: GithubToolName, + args: Record, + options: EveGithubToolsOptions, + token: string, +): Promise<{ args: Record, options: EveGithubToolsOptions }> { + const { footer, coAuthor } = credits() + const addFooter = footer && name === 'createPullRequest' + const addCoAuthor = coAuthor && GITHUB_COMMIT_TOOLS.has(name) + if (!addFooter && !addCoAuthor) return { args, options: { ...options, token } } + const bot = await appBot(token) + return { + args: addFooter ? { ...args, body: withGithubAppFooter(args.body as string | undefined, bot) } : args, + options: { + ...options, + token, + ...(addCoAuthor && { coAuthors: [...options.coAuthors ?? [], githubAppBotIdentity(bot)] }), + }, + } +} diff --git a/packages/github-tools-eve-extension/extension/tools/github.ts b/packages/github-tools-eve-extension/extension/tools/github.ts index 02e4fbed..e8f829ac 100644 --- a/packages/github-tools-eve-extension/extension/tools/github.ts +++ b/packages/github-tools-eve-extension/extension/tools/github.ts @@ -29,6 +29,7 @@ import { import type { ApprovalContext, ApprovalResponseContext, ApprovalResponseDecision, ApprovalResponsePolicy, ApprovalStatus } from 'eve/tools/approval' import { defineDynamic, defineTool, type ToolContext, type ToolDefinition } from 'eve/tools' import { z } from 'zod' +import { withAttribution } from '../lib/attribution' import { githubCommenter } from '../lib/commenter' import { sessionContext } from '../lib/context' import extension, { @@ -174,6 +175,12 @@ async function githubUserAuth() { return connect(await resolveGithubConnector(extension.config.connector!)) } +// GitHub records the person whose token runs the call, so the App is credited on what it wrote for them. +async function runAsUser(name: GithubToolName, input: Record, ctx: ToolContext, token: string) { + const { args, options } = await withAttribution(name, input, buildSessionOptions(ctx), token) + return executeGithubEveTool(name, args, options) +} + async function runGithubEveTool(name: GithubToolName, input: unknown, ctx: ToolContext) { const args = input as Record if (extension.config.dryRun && writeToolName(name)) { @@ -198,13 +205,13 @@ async function runGithubEveTool(name: GithubToolName, input: unknown, ctx: ToolC const auth = await githubUserAuth() if (approvedByOther) { const { token } = await approver.getToken(auth) - return executeGithubEveTool(name, args, { ...buildSessionOptions(ctx), token }) + return runAsUser(name, args, ctx, token) } if (actAs === 'caller' && !isUser(requester)) return executeGithubEveTool(name, args, buildSessionOptions(ctx)) const { token } = await ctx.getToken(auth) try { - return await executeGithubEveTool(name, args, { ...buildSessionOptions(ctx), token }) + return await runAsUser(name, args, ctx, token) } catch (error) { // A 401 means the user revoked the authorization: drop the token and ask them to sign in again. if (isUnauthorized(error)) ctx.requireAuth(auth) diff --git a/packages/github-tools/src/core/attribution.test.ts b/packages/github-tools/src/core/attribution.test.ts new file mode 100644 index 00000000..b1d6c9ec --- /dev/null +++ b/packages/github-tools/src/core/attribution.test.ts @@ -0,0 +1,56 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { githubAppBot, githubAppBotIdentity, withGithubAppFooter } from './attribution' + +function json(body: unknown, status = 200) { + return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }) +} + +function stubGithub(routes: Record) { + const requests: string[] = [] + vi.stubGlobal('fetch', vi.fn(async (input, init) => { + const url = new URL(String(input)) + const route = `${init?.method ?? 'GET'} ${decodeURIComponent(url.pathname)}` + requests.push(route) + return route in routes ? json(routes[route]) : json({ message: 'Not Found' }, 404) + })) + return requests +} + +const bot = { slug: 'evlogai', login: 'evlogai[bot]', id: 313167257 } + +afterEach(() => { + vi.unstubAllGlobals() +}) + +describe('githubAppBot', () => { + it('reads the App from the token\'s installations, then its bot account', async () => { + const requests = stubGithub({ + 'GET /user/installations': { total_count: 1, installations: [{ id: 1, app_id: 2, app_slug: 'evlogai' }] }, + 'GET /users/evlogai[bot]': { login: 'evlogai[bot]', id: 313167257, type: 'Bot' }, + }) + await expect(githubAppBot('ghu_test')).resolves.toEqual(bot) + expect(requests).toEqual(['GET /user/installations', 'GET /users/evlogai[bot]']) + }) + + it('fails when GitHub lists no installation to the token', async () => { + stubGithub({ 'GET /user/installations': { total_count: 0, installations: [] } }) + await expect(githubAppBot('ghu_test')).rejects.toMatchObject({ code: 'github_tools.APP_BOT_UNKNOWN' }) + }) +}) + +describe('githubAppBotIdentity', () => { + it('uses the noreply address GitHub links to the bot account', () => { + expect(githubAppBotIdentity(bot)).toEqual({ name: 'evlogai[bot]', email: '313167257+evlogai[bot]@users.noreply.github.com' }) + }) +}) + +describe('withGithubAppFooter', () => { + it('closes the body with a line naming the App', () => { + expect(withGithubAppFooter('Fixes the drain.\n', bot)).toBe('Fixes the drain.\n\n---\n\nGenerated by [evlogai](https://github.com/apps/evlogai).') + }) + + it('is the whole body when there is none', () => { + expect(withGithubAppFooter(undefined, bot)).toBe('Generated by [evlogai](https://github.com/apps/evlogai).') + expect(withGithubAppFooter(' ', bot)).toBe('Generated by [evlogai](https://github.com/apps/evlogai).') + }) +}) diff --git a/packages/github-tools/src/core/attribution.ts b/packages/github-tools/src/core/attribution.ts new file mode 100644 index 00000000..1a466654 --- /dev/null +++ b/packages/github-tools/src/core/attribution.ts @@ -0,0 +1,46 @@ +import { createOctokit } from '../client' +import type { CommitIdentity } from '../types' +import { githubToolsErrors } from './errors' +import type { GithubToolName } from './tool-names' + +/** A GitHub App's bot account, the identity GitHub shows for what the App writes. */ +export type GithubAppBot = { + /** The App's slug, as in `https://github.com/apps/`. */ + slug: string + /** The bot's login, `[bot]`. */ + login: string + /** The bot's numeric user id. */ + id: number +} + +/** The tools that create a commit and add `coAuthors` to its message. */ +export const GITHUB_COMMIT_TOOLS: ReadonlySet = new Set([ + 'createOrUpdateFile', + 'editFiles', + 'mergePullRequest', + 'enablePullRequestAutoMerge', +]) + +/** + * Read the bot of the GitHub App that issued `token`, a user access token. GitHub lists only that + * App's installations to such a token, so the first one names the App. + */ +export async function githubAppBot(token: string): Promise { + const octokit = createOctokit(token) + const { data } = await octokit.rest.apps.listInstallationsForAuthenticatedUser({ per_page: 1 }) + const slug = data.installations[0]?.app_slug + if (!slug) throw githubToolsErrors.APP_BOT_UNKNOWN() + const { data: bot } = await octokit.rest.users.getByUsername({ username: `${slug}[bot]` }) + return { slug, login: bot.login, id: bot.id } +} + +/** The bot as a commit identity, with the noreply address GitHub links to its account. */ +export function githubAppBotIdentity(bot: GithubAppBot): CommitIdentity { + return { name: bot.login, email: `${bot.id}+${bot.login}@users.noreply.github.com` } +} + +/** `body` with a closing line saying the App generated the pull request. */ +export function withGithubAppFooter(body: string | undefined, bot: GithubAppBot): string { + const footer = `Generated by [${bot.slug}](https://github.com/apps/${bot.slug}).` + return body?.trim() ? `${body.trimEnd()}\n\n---\n\n${footer}` : footer +} diff --git a/packages/github-tools/src/core/errors.ts b/packages/github-tools/src/core/errors.ts index e1af84c2..9fe59e42 100644 --- a/packages/github-tools/src/core/errors.ts +++ b/packages/github-tools/src/core/errors.ts @@ -78,6 +78,12 @@ export const githubToolsErrors = defineErrorCatalog('github_tools', { fix: 'Act on a repository and branch the guardrails allow, such as a branch matching the allowed patterns, or ask the user to change `guardrails`.', link: 'https://github-tools.com/approval#guardrails', }, + APP_BOT_UNKNOWN: { + status: 403, + message: 'GitHub lists no installation of the App to this user token, so the App\'s bot account can\'t be credited.', + why: 'Attribution reads the App that issued a user token from the installations GitHub lists to it. An empty list means the token is not a GitHub App user token, or the user can reach no installation of the App.', + fix: 'Use a Vercel Connect connector backed by a GitHub App installed where the user works, or turn attribution off.', + }, CALLER_FORBIDDEN: { status: 403, message: ({ reason }: { reason: string }) => `Not allowed for the person who asked: ${reason}`, diff --git a/packages/github-tools/src/eve-runtime.ts b/packages/github-tools/src/eve-runtime.ts index 3a6cabb8..7ad8f2d7 100644 --- a/packages/github-tools/src/eve-runtime.ts +++ b/packages/github-tools/src/eve-runtime.ts @@ -24,6 +24,8 @@ export { githubGuardrailViolation } from './eve/steps' export type { GithubGuardrails } from './core/guardrails' export { GITHUB_ROLES, githubRoleRank, withGithubCallerAccess } from './core/caller-access' export type { GithubCaller, GithubRole } from './core/caller-access' +export { GITHUB_COMMIT_TOOLS, githubAppBot, githubAppBotIdentity, withGithubAppFooter } from './core/attribution' +export type { GithubAppBot } from './core/attribution' export type { GithubDryRunApproval, GithubDryRunResult } from './core/dry-run' export type { GithubTokenCall } from './core/token' export { githubToolsErrors } from './core/errors' diff --git a/tests/eve-act-as/README.md b/tests/eve-act-as/README.md index 331f44c7..6fe3358b 100644 --- a/tests/eve-act-as/README.md +++ b/tests/eve-act-as/README.md @@ -3,7 +3,7 @@ Mounts the built `@github-tools/eve-extension` twice and drives it with `eve eval`: - `agent/extensions/github.ts`: `actAs: 'caller'` with `approvers: 'anyone'` -- `agent/extensions/strict.ts`: `actAs: 'user'` with the default approvers +- `agent/extensions/strict.ts`: `actAs: 'user'` with the default approvers and `attribution: false` - `agent/extensions/gated.ts`: `actAs: 'app'` with a configured `response` policy and a `pullNumber` context `fixtures/stubs.ts` answers Vercel Connect and `api.github.com` in-process, including the Connect sign-in. `agent/channels/eve.ts` signs in the user named by the `x-eval-user` header, or stands in for a GitHub commenter named by `x-eval-commenter`. `agent/channels/github.ts` mounts `githubChannel` from `@github-tools/eve-extension/channels` with `respondTo: 'writers'`, and the eval posts `issue_comment` webhooks to it. The run needs no token, network, or AI Gateway credentials. @@ -23,6 +23,7 @@ The eval checks that: - the approval prompt names the issue a call updates, not the pull request in the context - with `'caller'`, a GitHub commenter's call runs as the App with no sign-in, a reader's approved write is refused with `CALLER_FORBIDDEN`, a writer who approves it lends their role, and a call to another repository is checked against the role there - with `'caller'`, a commenter needs Write on a review thread's repository to resolve it, and a search is refused while the App's token reaches another repository +- a signed-in user's pull request ends with the App's footer and their commit names the App's bot as co-author, the App is read once from their token, and an App call or a mount with `attribution: false` adds neither - with `respondTo: 'writers'`, a reader's mention starts no turn, and a writer's mention starts one that reads the thread's repository and replies ```bash diff --git a/tests/eve-act-as/agent/agent.ts b/tests/eve-act-as/agent/agent.ts index 0c09013e..4cb337c7 100644 --- a/tests/eve-act-as/agent/agent.ts +++ b/tests/eve-act-as/agent/agent.ts @@ -1,6 +1,6 @@ import { defineAgent } from 'eve' import { mockModel } from 'eve/evals' -import { githubCalls } from '../fixtures/github-calls' +import { githubCalls, githubWrites } from '../fixtures/github-calls' const target = { owner: 'vercel-labs', repo: 'github-tools' } @@ -34,8 +34,16 @@ export default defineAgent({ return { toolCalls: [{ name: 'gated__createIssue', input: { ...target, title: 'eval' } }] } case 'gated update': return { toolCalls: [{ name: 'gated__updateIssue', input: { ...target, issueNumber: 999, state: 'closed' } }] } + case 'pr': + return { toolCalls: [{ name: 'github__createPullRequest', input: { ...target, title: 'eval', body: 'Fixes the drain.', head: 'eval', base: 'main' } }] } + case 'commit': + return { toolCalls: [{ name: 'github__createOrUpdateFile', input: { ...target, path: 'README.md', message: 'docs: update readme', content: 'eval', branch: 'eval' } }] } + case 'strict pr': + return { toolCalls: [{ name: 'strict__createPullRequest', input: { ...target, title: 'eval', body: 'Fixes the drain.', head: 'eval', base: 'main' } }] } case 'github calls': return JSON.stringify(githubCalls()) + case 'github writes': + return JSON.stringify(githubWrites()) default: return `unexpected message: ${lastUserMessage}` } diff --git a/tests/eve-act-as/agent/extensions/github.ts b/tests/eve-act-as/agent/extensions/github.ts index cde9cfe2..8c7e481e 100644 --- a/tests/eve-act-as/agent/extensions/github.ts +++ b/tests/eve-act-as/agent/extensions/github.ts @@ -8,7 +8,7 @@ export default githubExtension({ connector: 'github/eval', actAs: 'caller', approvers: 'anyone', - include: ['getRepository', 'createIssue', 'addIssueComment', 'resolveReviewThread', 'searchCode'], - requireApproval: { createIssue: 'always', addIssueComment: 'always' }, + include: ['getRepository', 'createIssue', 'addIssueComment', 'resolveReviewThread', 'searchCode', 'createPullRequest', 'createOrUpdateFile'], + requireApproval: { createIssue: 'always', addIssueComment: 'always', createPullRequest: 'never', createOrUpdateFile: 'never' }, overrides: { addIssueComment: { actAs: 'app' } }, }) diff --git a/tests/eve-act-as/agent/extensions/strict.ts b/tests/eve-act-as/agent/extensions/strict.ts index 9325b6e4..f1960bc3 100644 --- a/tests/eve-act-as/agent/extensions/strict.ts +++ b/tests/eve-act-as/agent/extensions/strict.ts @@ -1,10 +1,11 @@ import githubExtension from '@github-tools/eve-extension' import '../../fixtures/stubs' -// Every call runs as the signed-in user, and only the requester can approve. +// Every call runs as the signed-in user, only the requester can approve, and the App is not credited. export default githubExtension({ connector: 'github/eval', actAs: 'user', - include: ['getRepository', 'createIssue'], - requireApproval: { createIssue: 'always' }, + attribution: false, + include: ['getRepository', 'createIssue', 'createPullRequest'], + requireApproval: { createIssue: 'always', createPullRequest: 'never' }, }) diff --git a/tests/eve-act-as/evals/act-as.eval.ts b/tests/eve-act-as/evals/act-as.eval.ts index 26c6aa67..d73f9eb9 100644 --- a/tests/eve-act-as/evals/act-as.eval.ts +++ b/tests/eve-act-as/evals/act-as.eval.ts @@ -213,5 +213,31 @@ export default defineEval({ 'GET /repos/vercel-labs/github-tools ghs_app', 'POST /repos/vercel-labs/github-tools/issues/7/comments ghs_app', ])) + + // Attribution, with `actAs: 'caller'` (`github__*`) and `attribution: false` (`strict__*`) + + // A person's pull request credits the App in its body, and their commit names its bot as co-author. + const beforeAttribution = (await githubCalls(t)).length + t.check((await t.send('pr', as('alice'))).reply, includes('pull/31')) + t.check((await t.send('commit', as('alice'))).reply, includes('c0ffee')) + // The App's own pull request credits nobody, and neither does a mount that turns attribution off. + t.check((await t.send('pr')).reply, includes('pull/31')) + t.check((await t.send('strict pr', as('alice'))).reply, includes('pull/31')) + t.check(JSON.parse((await t.send('github writes', as('alice'))).reply ?? '[]'), equals([ + 'Fixes the drain.\n\n---\n\nGenerated by [eval](https://github.com/apps/eval).', + 'docs: update readme\n\nCo-authored-by: eval[bot] <4242+eval[bot]@users.noreply.github.com>', + 'Fixes the drain.', + 'Fixes the drain.', + ])) + // The App is read once, from the token of the first person it is credited for. + t.check((await githubCalls(t)).slice(beforeAttribution), equals([ + 'GET /user/installations ghu_alice', + 'GET /users/eval%5Bbot%5D ghu_alice', + 'POST /repos/vercel-labs/github-tools/pulls ghu_alice', + 'GET /repos/vercel-labs/github-tools/git/ref/heads%2Feval ghu_alice', + 'POST /graphql ghu_alice', + 'POST /repos/vercel-labs/github-tools/pulls ghs_app', + 'POST /repos/vercel-labs/github-tools/pulls ghu_alice', + ])) }, }) diff --git a/tests/eve-act-as/fixtures/github-calls.ts b/tests/eve-act-as/fixtures/github-calls.ts index 07737c07..ccc699e0 100644 --- a/tests/eve-act-as/fixtures/github-calls.ts +++ b/tests/eve-act-as/fixtures/github-calls.ts @@ -9,3 +9,15 @@ export function recordGithubCall(call: string) { export function githubCalls(): string[] { return calls } + +const writes: string[] = [] + +/** Records the text a write sent to GitHub: a pull request body or a commit message. */ +export function recordGithubWrite(text: string) { + writes.push(text) +} + +/** Texts sent to GitHub in this process, oldest first. */ +export function githubWrites(): string[] { + return writes +} diff --git a/tests/eve-act-as/fixtures/stubs.ts b/tests/eve-act-as/fixtures/stubs.ts index a9b7c6a5..da422244 100644 --- a/tests/eve-act-as/fixtures/stubs.ts +++ b/tests/eve-act-as/fixtures/stubs.ts @@ -1,4 +1,4 @@ -import { recordGithubCall } from './github-calls' +import { recordGithubCall, recordGithubWrite } from './github-calls' // The GitHub token Vercel Connect holds for each user. `carol` and `erin` have not authorized // the App yet, and `dave` revoked the authorization on GitHub after Connect stored their token. @@ -69,7 +69,12 @@ globalThis.fetch = async (input, init) => { return json({ total_count: 2, repositories: [{ full_name: 'vercel-labs/github-tools' }, { full_name: 'vercel-labs/private' }] }) } if (request.method === 'POST' && url.pathname === '/graphql') { - const { query } = await request.json() as { query: string } + const { query, variables } = await request.json() as { query: string, variables: { input?: { message?: { headline: string, body?: string } } } } + if (query.includes('createCommitOnBranch')) { + const message = variables.input!.message! + recordGithubWrite([message.headline, message.body].filter(Boolean).join('\n\n')) + return json({ data: { createCommitOnBranch: { commit: { oid: 'c0ffee', url: 'https://github.com/vercel-labs/github-tools/commit/c0ffee' } } } }) + } return query.includes('mutation') ? json({ data: { resolveReviewThread: { thread: { id: 'PRRT_1', isResolved: true } } } }) : json({ data: { node: { repository: { name: 'github-tools', owner: { login: 'vercel-labs' } } } } }) @@ -82,6 +87,21 @@ globalThis.fetch = async (input, init) => { const { body } = await request.json() as { body: string } return json({ id: 78, html_url: 'https://github.com/vercel-labs/github-tools/issues/7#issuecomment-78', body, user: { login: 'eval[bot]' }, created_at: '2026-11-06T00:00:00Z' }, 201) } + // A user token lists the installations of the App that issued it: the eval connector's App is `eval`. + if (request.method === 'GET' && url.pathname === '/user/installations' && token.startsWith('ghu_')) { + return json({ total_count: 1, installations: [{ id: 3, app_id: 9, app_slug: 'eval' }] }) + } + if (request.method === 'GET' && decodeURIComponent(url.pathname) === '/users/eval[bot]') { + return json({ login: 'eval[bot]', id: 4242, type: 'Bot' }) + } + if (request.method === 'POST' && url.pathname === '/repos/vercel-labs/github-tools/pulls') { + const { title, body, head, base } = await request.json() as { title: string, body?: string, head: string, base: string } + recordGithubWrite(body ?? '') + return json({ number: 31, title, html_url: 'https://github.com/vercel-labs/github-tools/pull/31', state: 'open', draft: false, head: { ref: head }, base: { ref: base } }, 201) + } + if (request.method === 'GET' && decodeURIComponent(url.pathname) === '/repos/vercel-labs/github-tools/git/ref/heads/eval') { + return json({ ref: 'refs/heads/eval', object: { sha: 'abc123' } }) + } if (request.method === 'GET' && url.pathname === '/repos/vercel-labs/github-tools') { return json({ name: 'github-tools',