The Open Framework for Building Agents
feat(git): add Co-authored-by attribution to the gh tool (#4908)
roboeve[bot]e3d14970c29b
diff --git a/.changeset/github-co-author-attribution.md b/.changeset/github-co-author-attribution.mdnew file mode 100644index 000000000..da4dbb8b3--- /dev/null+++ b/.changeset/github-co-author-attribution.md@@ -0,0 +1,5 @@+---+"eve": minor+---++Add `github.attribution(ctx)` to `eve/extensions/git` and the deprecated `code({ github })` config. When it returns a `{ name, email }` co-author, the `gh` tool ends every `gh-signed-commit` message and `gh pr create` body with that person's `Co-authored-by` trailer.diff --git a/docs/code-extension.mdx b/docs/code-extension.mdxindex e8508a108..c31befdf0 100644--- a/docs/code-extension.mdx+++ b/docs/code-extension.mdx@@ -92,12 +92,13 @@ export default git({});Configure `github` to broker GitHub access through Connect instead. The extension then adds the authenticated `git__gh` tool, tells the agent to use it for every authenticated GitHub operation, and switches `git__pr` to `gh-signed-commit` for repositories that require verified signatures.-| Option | Required | Effect |-| ------------------ | ------------- | ------------------------------------------------------------------------------------------ |-| `github.connector` | With `github` | Connector that mints a GitHub token |-| `github.org` | With `github` | Organization whose repositories the `gh` tool can access |-| `github.broker` | With `github` | `broker(sandbox, rules)` callback that installs, then removes, the GitHub credential rules |-| `github.authorize` | No | `authorize({ auth, repository, token })` callback that allows or denies each `gh` tool invocation |+| Option | Required | Effect |+| -------------------- | ------------- | ------------------------------------------------------------------------------------------------- |+| `github.connector` | With `github` | Connector that mints a GitHub token |+| `github.org` | With `github` | Organization whose repositories the `gh` tool can access |+| `github.broker` | With `github` | `broker(sandbox, rules)` callback that installs, then removes, the GitHub credential rules |+| `github.authorize` | No | `authorize({ auth, repository, token })` callback that allows or denies each `gh` tool invocation |+| `github.attribution` | No | `attribution(ctx)` callback that returns the `{ name, email }` co-author for this turn |The `gh` tool requests a token scoped to exactly one repository in `github.org` for each invocation. The sandbox process receives a placeholder `GH_TOKEN`, and the firewall exchanges it on matching GitHub requests. Your `github.broker` callback receives the header-transform rules for the command, then `null` to remove the lease. The callback must preserve your other network rules. GitHub authentication has no command-delivery option.@@ -128,6 +129,19 @@ export default git({});```+Commits made by the `gh` tool are authored by the GitHub App. To credit the person a turn works for, return them from `github.attribution`. The callback receives the tool's context, so it can read the verified caller from `ctx.session.auth.current` or resolve their linked accounts with `ctx.getToken`. The `gh` tool then ends every `gh-signed-commit` message, and every `gh pr create` body passed with `--body` or `--body-file`, with `Co-authored-by: <name> <email>`. Return `null` to publish without a co-author. `Co-authored-by` lines the agent writes itself are kept, and the trailer joins their block so they still count. Pull requests created without a body flag, such as with `--fill` or `--template`, and other paths, such as `gh api`, are not attributed.++```ts+git({+ github: {+ connector: "github",+ org: "acme",+ broker,+ attribution: (ctx) => coAuthorFor(ctx.session.auth.current),+ },+});+```+### Migrate from `code({ github })``code({ github })` is deprecated. While it is set, the code extension still contributes `code__gh`, its GitHub instructions, and the signed-commit `code__pr` skill. Without it, the code extension contributes no GitHub tool, instructions, or pull request skill. Move the `github` option to `git({ github })`, and import `gh` and the GitHub sandbox helpers from `eve/extensions/git/tools` and `eve/extensions/git/sandbox`.diff --git a/packages/eve-code/extension/extension.ts b/packages/eve-code/extension/extension.tsindex a813a9824..1b791b3c7 100644--- a/packages/eve-code/extension/extension.ts+++ b/packages/eve-code/extension/extension.ts@@ -12,6 +12,7 @@ export type CredentialPolicyBroker = (export type { GitHubLeaseRule } from "eve/extensions/git/sandbox";export type GitHubLeaseBroker = GitHubConfig["broker"];+export type GitHubAttribution = NonNullable<GitHubConfig["attribution"]>;const fn = <T>() => z.custom<T>((value) => typeof value === "function");const delivery = z.enum(["firewall", "command"]).default("firewall");@@ -30,6 +31,7 @@ export default defineExtension({connector: z.string().min(1),org: z.string().min(1),broker: fn<GitHubLeaseBroker>(),+ attribution: fn<GitHubAttribution>().optional(),}).optional(),vercel: zdiff --git a/packages/eve-git/README.md b/packages/eve-git/README.mdindex ad9735962..584c35150 100644--- a/packages/eve-git/README.md+++ b/packages/eve-git/README.md@@ -21,6 +21,8 @@ export default git({});To broker GitHub access through Connect instead, configure `github` with `connector`, `org`, and a required `broker(sandbox, rules)` callback. The extension then contributes `git__gh`, which requests a token for exactly one repository in that organization per command. The callback installs the supplied GitHub header-transform rules for the command, then receives `null` to remove the lease. It must preserve the consumer's other network rules. Sandbox processes receive a placeholder token, not the real credential. `git__pr` switches to `gh-signed-commit` for repositories that require verified signatures. Install the executables with `installCodeTooling` from `eve/extensions/code/sandbox`.+An optional `attribution(ctx)` callback returns the `{ name, email }` co-author for the current turn, or `null`. `git__gh` appends its `Co-authored-by` trailer to `gh-signed-commit` messages and to `gh pr create` bodies passed with `--body` or `--body-file`.+## Validate```shdiff --git a/packages/eve-git/extension/extension.ts b/packages/eve-git/extension/extension.tsindex f34d19082..f22be5021 100644--- a/packages/eve-git/extension/extension.ts+++ b/packages/eve-git/extension/extension.ts@@ -4,8 +4,10 @@ import { z } from "zod";import type { GitHubAuthorize, GitHubConfig } from "./lib/github-shell.ts";export type { GitHubLeaseRule } from "./lib/github-shell.ts";+export type { GitHubCoAuthor } from "./lib/github-shell.ts";export type { GitHubAuthorize, GitHubAuthorizeRequest } from "./lib/github-shell.ts";export type GitHubLeaseBroker = GitHubConfig["broker"];+export type GitHubAttribution = NonNullable<GitHubConfig["attribution"]>;const fn = <T>() => z.custom<T>((value) => typeof value === "function");@@ -21,6 +23,11 @@ export default defineExtension({connector: z.string().min(1),org: z.string().min(1),broker: fn<GitHubLeaseBroker>(),+ /**+ * Resolves the person each turn publishes for. Their+ * `Co-authored-by` trailer ends signed commits and new pull requests.+ */+ attribution: fn<GitHubAttribution>().optional(),/*** Called before each `gh` command with the session's caller, the* declared repository, and its scoped token. Return `false` to deny.diff --git a/packages/eve-git/extension/lib/attribution.ts b/packages/eve-git/extension/lib/attribution.tsnew file mode 100644index 000000000..678c87ebc--- /dev/null+++ b/packages/eve-git/extension/lib/attribution.ts@@ -0,0 +1,109 @@+import { posix } from "node:path";+import type { SandboxSession } from "eve/sandbox";++/** The person a commit or pull request is created for. */+export interface GitHubCoAuthor {+ readonly email: string;+ readonly name: string;+}++/** Pull request body flags accepted by `gh pr create`. */+const BODY_FLAGS = new Set(["-b", "--body"]);+const BODY_FILE_FLAGS = new Set(["-F", "--body-file"]);+/** A `Key: value` line, the shape of every line in a git trailer block. */+const TRAILER_LINE = /^[A-Za-z0-9][A-Za-z0-9-]*: \S/u;++/** Format a validated `Co-authored-by` trailer. */+export function coAuthorTrailer(coAuthor: GitHubCoAuthor): string {+ const name = coAuthor.name.trim();+ const email = coAuthor.email.trim();+ if (!name || /[\r\n<>]/u.test(name)) {+ throw new Error(`Invalid co-author name ${JSON.stringify(coAuthor.name)}.`);+ }+ if (!/^[^\s<>@]+@[^\s<>@]+$/u.test(email)) {+ throw new Error(`Invalid co-author email ${JSON.stringify(coAuthor.email)}.`);+ }+ return `Co-authored-by: ${name} <${email}>`;+}++/**+ * Append a trailer unless the body already carries it. Git and GitHub read+ * only the last paragraph as trailers, so an existing trailer block is+ * extended rather than followed by a new paragraph.+ */+export function withTrailer(body: string, trailer: string): string {+ const lines = body.split(/\r?\n/u).map((line) => line.trim().toLowerCase());+ if (lines.includes(trailer.toLowerCase())) return body;+ const trimmed = body.trimEnd();+ if (!trimmed) return trailer;+ const paragraphs = trimmed.split(/\r?\n[ \t]*\r?\n/u);+ const last = paragraphs.at(-1)!.split(/\r?\n/u);+ const extendsTrailers = paragraphs.length > 1 && last.every((line) => TRAILER_LINE.test(line));+ return `${trimmed}${extendsTrailers ? "\n" : "\n\n"}${trailer}`;+}++/** True for the commands whose bodies carry attribution. */+export function isAttributable(argv: readonly string[]): boolean {+ return (+ argv[0] === "gh-signed-commit" || (argv[0] === "gh" && argv[1] === "pr" && argv[2] === "create")+ );+}++/**+ * Add the trailer to the bodies eve publishes: `gh-signed-commit` commit+ * messages and `gh pr create` descriptions. Other commands are unchanged.+ * A `--body-file` is copied to `bodyFile`, so the model's file stays intact.+ */+export async function attributeCommand(+ argv: readonly string[],+ trailer: string,+ sandbox: Pick<SandboxSession, "readTextFile" | "writeTextFile">,+ workingDirectory: string,+ bodyFile: string,+): Promise<string[]> {+ const result = [...argv];+ if (argv[0] === "gh-signed-commit") {+ // gh-signed-commit keeps the last `-b`.+ const index = result.lastIndexOf("-b");+ if (index === -1) result.push("-b", trailer);+ else result[index + 1] = withTrailer(result[index + 1] ?? "", trailer);+ return result;+ }+ if (argv[0] !== "gh" || argv[1] !== "pr" || argv[2] !== "create") return result;+ // gh keeps the last body flag, so attribute that one.+ for (let index = result.length - 1; index >= 3; index -= 1) {+ const value = result[index]!;+ const [flag, inline] = splitInline(value);+ if (BODY_FLAGS.has(flag)) {+ const body = withTrailer(inline ?? result[index + 1] ?? "", trailer);+ if (inline === undefined) result[index + 1] = body;+ else result[index] = `${flag}=${body}`;+ return result;+ }+ if (BODY_FILE_FLAGS.has(flag)) {+ const path = inline ?? result[index + 1];+ if (!path || path === "-") return result;+ const content = await sandbox.readTextFile({ path: posix.resolve(workingDirectory, path) });+ if (content === null)+ throw new Error(`Pull request body file ${JSON.stringify(path)} not found.`);+ await sandbox.writeTextFile({ content: withTrailer(content, trailer), path: bodyFile });+ if (inline === undefined) result[index + 1] = bodyFile;+ else result[index] = `${flag}=${bodyFile}`;+ return result;+ }+ }+ return result;+}++/** Split `--flag=value`, `-fvalue`, and `-f=value` the way gh's flag parser does. */+function splitInline(value: string): [string, string | undefined] {+ if (!value.startsWith("--")) {+ if (!value.startsWith("-") || value.length <= 2) return [value, undefined];+ const rest = value.slice(2);+ return [value.slice(0, 2), rest.startsWith("=") ? rest.slice(1) : rest];+ }+ const separator = value.indexOf("=");+ return separator === -1+ ? [value, undefined]+ : [value.slice(0, separator), value.slice(separator + 1)];+}diff --git a/packages/eve-git/extension/lib/gh-tool.ts b/packages/eve-git/extension/lib/gh-tool.tsindex cfbe97bf1..1a4fc3c26 100644--- a/packages/eve-git/extension/lib/gh-tool.ts+++ b/packages/eve-git/extension/lib/gh-tool.ts@@ -29,6 +29,7 @@ export function defineGhTool(}),execute(input, ctx) {return executeGitHubShell(input, github(), {+ context: ctx,auth: ctx.session.auth.current,getSandbox: () => ctx.getSandbox(),sessionId: ctx.session.id,diff --git a/packages/eve-git/extension/lib/github-shell.ts b/packages/eve-git/extension/lib/github-shell.tsindex 8a344aa8e..c6387c967 100644--- a/packages/eve-git/extension/lib/github-shell.ts+++ b/packages/eve-git/extension/lib/github-shell.ts@@ -2,11 +2,20 @@ import { posix } from "node:path";import { getToken, type ConnectTokenParams } from "@vercel/connect";import type { SessionAuthContext } from "eve/context";import type { SandboxSession } from "eve/sandbox";+import type { ToolContext } from "eve/tools";+import {+ attributeCommand,+ coAuthorTrailer,+ isAttributable,+ type GitHubCoAuthor,+} from "./attribution.ts";import { validateRepositoryRoot } from "./repository-root.ts";import { shellQuote } from "./shell.ts";import { GITHUB_TOOLING_PATHS } from "./tooling.ts";+export type { GitHubCoAuthor } from "./attribution.ts";+export interface GitHubPermission {readonly access: "write";readonly provider: "github";@@ -28,6 +37,16 @@ export interface GitHubShellOutput {}export interface GitHubConfig {+ /**+ * Resolves who the current turn publishes for. When it returns a person,+ * `gh-signed-commit` messages and `gh pr create` bodies end with their+ * `Co-authored-by` trailer. Return `null` to publish without one. It+ * receives the `gh` tool's context, so `ctx.getToken` can resolve the+ * requester's linked accounts.+ */+ readonly attribution?: (+ ctx: ToolContext,+ ) => GitHubCoAuthor | null | PromiseLike<GitHubCoAuthor | null>;readonly authorize?: GitHubAuthorize;readonly broker: (sandbox: SandboxSession,@@ -61,6 +80,8 @@ export interface GitHubLeaseRule {}interface GitHubShellDependencies {+ /** The calling tool's context, passed to `attribution`. */+ readonly context?: ToolContext;readonly auth?: SessionAuthContext | null;readonly getConnectToken?: typeof getToken;readonly getSandbox: () => Promise<SandboxSession>;@@ -104,6 +125,8 @@ export async function executeGitHubShell(workingDirectory,sandbox,);+ const invocationId = crypto.randomUUID();+ const bodyFile = `/tmp/eve-git-body-${invocationId}.md`;const repositories = repositoryNames(declaredRepositories, config.org);const tokenParams: ConnectTokenParams = {authorizationDetails: [{ type: "github_app_installation", org: config.org, repositories }],@@ -119,24 +142,30 @@ export async function executeGitHubShell() {throw new Error(`The current caller is not authorized to access ${repository}.`);}+ const coAuthor =+ config.attribution && dependencies.context && isAttributable(argv)+ ? await config.attribution(dependencies.context)+ : null;+ const commandArgv = coAuthor+ ? await attributeCommand(argv, coAuthorTrailer(coAuthor), sandbox, workingDirectory, bodyFile)+ : argv;- const executable = executablePath(argv[0]!);+ const executable = executablePath(commandArgv[0]!);const executionArguments = remoteRepository? ["-c","protocol.allow=never","-c","protocol.https.allow=always",- argv[1]!,+ commandArgv[1]!,`https://github.com/${remoteRepository}.git`,- ...argv.slice(3),+ ...commandArgv.slice(3),]- : argv.slice(1);+ : commandArgv.slice(1);const command = `cd ${shellQuote(workingDirectory)} && exec ${shellQuote(executable)} ${executionArguments.map(shellQuote).join(" ")}`;const authorization = `Basic ${Buffer.from(`x-access-token:${token}`).toString("base64")}`;- const invocationId = crypto.randomUUID();const placeholder = `eve-github-${invocationId}`;const githubConfig = `/tmp/eve-code-gh-${invocationId}`;const placeholderAuthorization = `Basic ${Buffer.from(`x-access-token:${placeholder}`).toString("base64")}`;@@ -165,6 +194,7 @@ export async function executeGitHubShell();} finally {await sandbox.removePath({ path: githubConfig, recursive: true, force: true });+ await sandbox.removePath({ path: bodyFile, force: true });}const stdout = sanitizeOutput(result.stdout, token, authorization);const stderr = sanitizeOutput(result.stderr, token, authorization);diff --git a/packages/eve-git/extension/lib/sandbox.ts b/packages/eve-git/extension/lib/sandbox.tsindex f35705adf..27a0da5b1 100644--- a/packages/eve-git/extension/lib/sandbox.ts+++ b/packages/eve-git/extension/lib/sandbox.ts@@ -2,6 +2,7 @@export {executeGitHubShell,githubShellApproval,+ type GitHubCoAuthor,type GitHubConfig,type GitHubLeaseRule,type GitHubShellInput,diff --git a/packages/eve-git/test/integration/github-shell.test.ts b/packages/eve-git/test/integration/github-shell.test.tsindex 1376f350f..2c8dcb292 100644--- a/packages/eve-git/test/integration/github-shell.test.ts+++ b/packages/eve-git/test/integration/github-shell.test.ts@@ -2,6 +2,7 @@ import assert from "node:assert/strict";import test from "node:test";import type { ConnectTokenParams } from "@vercel/connect";import type { SandboxNetworkPolicy, SandboxSession } from "eve/sandbox";+import type { ToolContext } from "eve/tools";type NetworkPolicySandboxSession = SandboxSession & {setNetworkPolicy(policy: SandboxNetworkPolicy): Promise<void>;@@ -399,6 +400,43 @@ test("rejects repositories outside the configured organization before minting",assert.equal(tokenRequested, false);});+test("attributes pull requests to the person the tool context resolves", async () => {+ const runs: Parameters<SandboxSession["run"]>[0][] = [];+ const contexts: unknown[] = [];+ const context = { session: { id: "session-1" } } as ToolContext;+ const config = {+ ...CONFIG,+ attribution(ctx: ToolContext) {+ contexts.push(ctx);+ return { name: "octocat", email: "[email protected]" };+ },+ };+ const dependencies = {+ context,+ sessionId: "session-1",+ async getConnectToken() {+ return "secret-token";+ },+ async getSandbox() {+ return fakeSandbox(runs, { exitCode: 0, stdout: "", stderr: "" });+ },+ };+ await executeGitHubShell(READ, config, dependencies);+ assert.deepEqual(contexts, [], "read commands never resolve attribution");++ await executeGitHubShell(+ { ...READ, command: 'gh pr create --repo vercel/internal-agents --title T --body "Why."' },+ config,+ dependencies,+ );++ assert.deepEqual(contexts, [context]);+ assert.match(+ runs.at(-1)?.command ?? "",+ /'--body' 'Why\.\n\nCo-authored-by: octocat <1\+octocat@users\.noreply\.github\.com>'$/u,+ );+});+function fakeSandbox(runs: Parameters<SandboxSession["run"]>[0][],result:diff --git a/packages/eve-git/test/unit/attribution.test.ts b/packages/eve-git/test/unit/attribution.test.tsnew file mode 100644index 000000000..b686a0c49--- /dev/null+++ b/packages/eve-git/test/unit/attribution.test.ts@@ -0,0 +1,118 @@+import assert from "node:assert/strict";+import test from "node:test";++import { attributeCommand, coAuthorTrailer, withTrailer } from "../../extension/lib/attribution.ts";++const TRAILER = "Co-authored-by: octocat <[email protected]>";++function files(initial: Record<string, string> = {}) {+ const store = new Map(Object.entries(initial));+ return {+ store,+ async readTextFile({ path }: { path: string }) {+ return store.get(path) ?? null;+ },+ async writeTextFile({ content, path }: { content: string; path: string }) {+ store.set(path, content);+ },+ };+}++function attribute(argv: string[], sandbox = files()) {+ return attributeCommand(argv, TRAILER, sandbox, "/workspace/repo", "/tmp/body.md");+}++test("formats a trailer and rejects values that could inject lines", () => {+ assert.equal(+ coAuthorTrailer({ name: "octocat", email: "[email protected]" }),+ TRAILER,+ );+ assert.throws(() => coAuthorTrailer({ name: "a\nCo-authored-by: b", email: "[email protected]" }), /name/u);+ assert.throws(() => coAuthorTrailer({ name: "a", email: "[email protected]>\nx" }), /email/u);+});++test("appends the trailer once", () => {+ assert.equal(withTrailer("", TRAILER), TRAILER);+ assert.equal(withTrailer("Fix it.\n", TRAILER), `Fix it.\n\n${TRAILER}`);+ assert.equal(withTrailer(`Fix it.\n\n${TRAILER}`, TRAILER), `Fix it.\n\n${TRAILER}`);+});++test("extends an existing trailer block so earlier co-authors still count", () => {+ const existing = "Fix it.\n\nCo-authored-by: A <[email protected]>\n";+ assert.equal(withTrailer(existing, TRAILER), `Fix it.\n\nCo-authored-by: A <[email protected]>\n${TRAILER}`);+ // A lone `Key: value` paragraph is the subject or prose, not a trailer block.+ assert.equal(withTrailer("Note: details", TRAILER), `Note: details\n\n${TRAILER}`);+ assert.equal(+ withTrailer("Fix it.\n\nSee: this is prose\nacross lines", TRAILER),+ `Fix it.\n\nSee: this is prose\nacross lines\n\n${TRAILER}`,+ );+});++test("adds the trailer to signed commit bodies", async () => {+ assert.deepEqual(await attribute(["gh-signed-commit", "--repo", "o/r", "-m", "Fix"]), [+ "gh-signed-commit",+ "--repo",+ "o/r",+ "-m",+ "Fix",+ "-b",+ TRAILER,+ ]);+ assert.deepEqual(await attribute(["gh-signed-commit", "-m", "Fix", "-b", "A", "-b", "Why."]), [+ "gh-signed-commit",+ "-m",+ "Fix",+ "-b",+ "A",+ "-b",+ `Why.\n\n${TRAILER}`,+ ]);+});++test("adds the trailer to pull request bodies without touching the model's file", async () => {+ assert.deepEqual(await attribute(["gh", "pr", "create", "--body=Why."]), [+ "gh",+ "pr",+ "create",+ `--body=Why.\n\n${TRAILER}`,+ ]);+ assert.deepEqual(await attribute(["gh", "pr", "create", "-bWhy."]), [+ "gh",+ "pr",+ "create",+ `-b=Why.\n\n${TRAILER}`,+ ]);+ assert.deepEqual(await attribute(["gh", "pr", "create", "-b=Why."]), [+ "gh",+ "pr",+ "create",+ `-b=Why.\n\n${TRAILER}`,+ ]);+ const sandbox = files({ "/workspace/repo/pr.md": "Why.\n" });+ assert.deepEqual(await attribute(["gh", "pr", "create", "--body-file", "pr.md"], sandbox), [+ "gh",+ "pr",+ "create",+ "--body-file",+ "/tmp/body.md",+ ]);+ assert.equal(sandbox.store.get("/tmp/body.md"), `Why.\n\n${TRAILER}`);+ assert.equal(sandbox.store.get("/workspace/repo/pr.md"), "Why.\n");+ assert.deepEqual(await attribute(["gh", "pr", "create", "-Fpr.md"], sandbox), [+ "gh",+ "pr",+ "create",+ "-F=/tmp/body.md",+ ]);+});++test("leaves other commands unchanged", async () => {+ for (const argv of [+ ["gh", "pr", "comment", "1", "--body", "hi"],+ ["gh", "pr", "create", "--fill"],+ ["gh", "pr", "create", "--template", "bug.md"],+ ["git", "push", "origin", "HEAD"],+ ]) {+ assert.deepEqual(await attribute(argv), argv);+ }+});