pr_01m47d15m3e54sn21z27rpy5n9/crates/runner/src/main.rs

251 lines9,881 bytesCodeBlame

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

Issues and pull requests replace intents and attempts1//! Runs a coding agent on one pull request and reports back to g1t.
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)2//!
Issues and pull requests replace intents and attempts3//! This is the program a hosted sandbox starts. It clones the pull
4//! request's fork, runs the agent harness headless, streams what the agent
5//! does into the pull request's session as it happens, pushes the result
6//! and marks the pull request ready for review. It talks to g1t only through the public API and git, exactly
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)7//! as an agent on someone's own machine would.
8//!
Agents as a team: lifecycle, merge queue, billing and a new shell9//! `MODE` selects another job instead: `checks` runs acceptance checks,
10//! `update` brings a pull request up to date with its target branch,
11//! `review` has an agent review one, and `revise` sends the author back to
12//! address what the checks or a review found, `plan` turns an outcome
Agents and memory, checks and conflicts, profiles, slug renames, custom domains13//! into issues, `queue` builds and checks a state of the merge queue,
14//! `mergecheck` finds out whether a pull request merges cleanly, and
GitHub Actions on g1t, part two: running workflows15//! `actions` runs one job of a GitHub Actions workflow.
Agents as a team: lifecycle, merge queue, billing and a new shell16//! See the modules of those names.
Acceptance checks in sandboxes, line comments and review verdicts17//!
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)18//! Configuration comes from the environment:
19//!
20//! - `G1T_API`, `G1T_TOKEN`, `G1T_USER`: where and who to report as.
Issues and pull requests replace intents and attempts21//! - `G1T_REPO`, `PULL_NUMBER`, `GIT_REMOTE`: the pull request and its fork.
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)22//! - `PROMPT`: what the agent is asked to do.
23//! - `COMMIT_MESSAGE`: used if the agent leaves changes uncommitted.
24//! - `ANTHROPIC_API_KEY`: read by the harness itself.
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look25//!
26//! Every mode runs with the mining watch in `abuse`: a sandbox that looks
27//! like it is mining stops itself and exits with `abuse::EXIT_CODE`.
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)28
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look29mod abuse;
GitHub Actions on g1t, part two: running workflows30mod actions;
Acceptance checks in sandboxes, line comments and review verdicts31mod checks;
Deployments: a preview for every pull request, production on g1t.page32mod deploy;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API33mod guard;
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)34mod harness;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API35mod learned;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains36mod mergecheck;
Agents as a team: lifecycle, merge queue, billing and a new shell37mod plan;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains38mod progress;
Agents as a team: lifecycle, merge queue, billing and a new shell39mod queue;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API40mod reply;
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)41mod report;
Agents as a team: lifecycle, merge queue, billing and a new shell42mod review;
43mod revise;
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request44mod steer;
Agents as a team: lifecycle, merge queue, billing and a new shell45mod update;
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)46
47use std::path::Path;
48use std::process::Command;
49
50use anyhow::{Context, Result, bail};
51use base64::Engine;
52use base64::engine::general_purpose::STANDARD;
53
54use report::{Entry, Reporter};
55
Acceptance checks in sandboxes, line comments and review verdicts56pub(crate) const WORKDIR: &str = "/work/repo";
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)57
Acceptance checks in sandboxes, line comments and review verdicts58pub(crate) fn env(name: &str) -> Result<String> {
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)59 std::env::var(name).with_context(|| format!("{name} is not set"))
60}
61
62/// Runs git and returns its trimmed output, failing on a non-zero exit.
Acceptance checks in sandboxes, line comments and review verdicts63pub(crate) fn git(dir: &Path, args: &[&str]) -> Result<String> {
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)64 let output = Command::new("git")
65 .current_dir(dir)
66 .args(args)
67 .output()
68 .context("could not run git")?;
69 if !output.status.success() {
70 bail!(
71 "git {} failed: {}",
72 args.first().unwrap_or(&""),
73 String::from_utf8_lossy(&output.stderr).trim()
74 );
75 }
76 Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
77}
78
79/// A git option that authenticates one command. The credential is passed
80/// per command and never written to the clone's config or its remote URL,
81/// where the agent would find it.
Acceptance checks in sandboxes, line comments and review verdicts82pub(crate) fn auth_option(user: &str, token: &str) -> String {
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)83 let credentials = STANDARD.encode(format!("{user}:{token}"));
84 format!("http.extraHeader=Authorization: Basic {credentials}")
85}
86
Agents as a team: lifecycle, merge queue, billing and a new shell87/// Clones the fork, runs the agent on `PROMPT`, commits and pushes what it
88/// did, and returns its closing summary.
89pub(crate) fn run(reporter: &mut Reporter) -> Result<String> {
90 let mut prompt = env("PROMPT")?;
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)91 let remote = env("GIT_REMOTE")?;
92 let auth = auth_option(&env("G1T_USER")?, &env("G1T_TOKEN")?);
93 let workdir = Path::new(WORKDIR);
94
Show the model behind each choice; toolchains in the sandbox95 if let Ok(model) = std::env::var("AGENT_MODEL_NAME") {
96 reporter.record(Entry::new("note", &format!("Running on {model}.")));
97 }
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)98 reporter.record(Entry::new("prompt", &prompt));
99 reporter.flush();
100
101 std::fs::create_dir_all("/work")?;
102 git(
103 Path::new("/work"),
104 &["-c", &auth, "clone", "--quiet", &remote, WORKDIR],
105 )
Issues and pull requests replace intents and attempts106 .context("could not clone the pull request's fork")?;
Diffs on attempts; hosted agent presented as the g1t agent107 git(workdir, &["config", "user.name", "g1t agent"])?;
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)108 git(workdir, &["config", "user.email", "agent@g1t.sh"])?;
109 let branch = git(workdir, &["rev-parse", "--abbrev-ref", "HEAD"])?;
110 let start = git(workdir, &["rev-parse", "HEAD"]).unwrap_or_default();
111
Agents as a team: lifecycle, merge queue, billing and a new shell112 // Sent back to work that is already open: start from where the branch it
113 // will land on is now, so what passes here passes there too.
114 if let (Ok(upstream), Ok(upstream_branch)) = (env("UPSTREAM_REMOTE"), env("UPSTREAM_BRANCH")) {
115 git(
116 workdir,
117 &["-c", &auth, "fetch", "--quiet", &upstream, &upstream_branch],
118 )
119 .context("could not fetch the branch this will land on")?;
120 let behind = Command::new("git")
121 .current_dir(workdir)
122 .args(["merge-base", "--is-ancestor", "FETCH_HEAD", "HEAD"])
123 .status()
124 .is_ok_and(|status| !status.success());
125 if behind {
126 let message = format!("Catch up with {upstream_branch}");
127 let merged = Command::new("git")
128 .current_dir(workdir)
129 .args(["merge", "--quiet", "--no-edit", "-m", &message, "FETCH_HEAD"])
130 .status()
131 .is_ok_and(|status| status.success());
132 if merged {
133 reporter.record(Entry::new(
134 "note",
135 &format!("Merged in the latest {upstream_branch} before starting."),
136 ));
137 } else {
138 let files = git(workdir, &["diff", "--name-only", "--diff-filter=U"])?;
139 let files: Vec<&str> = files.lines().collect();
140 reporter.record(Entry::new(
141 "note",
142 &format!(
143 "Merged in the latest {upstream_branch} before starting; {} conflict.",
144 files.join(", ")
145 ),
146 ));
147 prompt.push_str(&format!(
148 "\n\nBefore you started, the latest {upstream_branch} was merged into this branch, and these files conflict: {}. Resolve the conflicts first, keeping what both sides meant, then address the points above. Leave no conflict markers.",
149 files.join(", ")
150 ));
151 }
152 reporter.flush();
153 }
154 }
155
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API156 // The agent is asked what it learned; that goes to memory, not the summary.
157 let summary = learned::finish(harness::run_claude(workdir, &learned::ask(&prompt), reporter)?);
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)158
159 // Commit whatever the agent left in the working tree.
160 if !git(workdir, &["status", "--porcelain"])?.is_empty() {
161 let message = std::env::var("COMMIT_MESSAGE").unwrap_or_else(|_| "Agent changes".into());
162 git(workdir, &["add", "--all"])?;
163 git(workdir, &["commit", "--quiet", "--message", &message])?;
164 }
165 let head = git(workdir, &["rev-parse", "HEAD"])?;
166 if head == start {
Agents asked while not at work are woken to answer167 // An agent woken to answer usually only answers.
168 if std::env::var("MODE").as_deref() == Ok("answer") {
169 return Ok(summary);
170 }
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)171 bail!("the agent finished without changing anything");
172 }
173 git(
174 workdir,
175 &[
176 "-c",
177 &auth,
178 "push",
179 "--quiet",
180 "origin",
181 &format!("HEAD:{branch}"),
182 ],
183 )
Issues and pull requests replace intents and attempts184 .context("could not push the pull request's commits")?;
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)185 reporter.record(Entry::new(
186 "note",
Issues and pull requests replace intents and attempts187 &format!("Pushed {}.", &head[..head.len().min(12)]),
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)188 ));
189 Ok(summary)
190}
191
192fn main() {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API193 // A guarded sandbox's HTTPS is re-signed on its way out: trust that
194 // before anything is fetched. The guard hook runs before every tool
195 // call, so it skips this.
196 if std::env::var("MODE").as_deref() == Ok("guard") {
197 std::process::exit(guard::hook_main());
198 }
199 guard::trust_egress_ca();
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look200 // Watches for mining for as long as the sandbox runs (abuse.rs). Not in
201 // the hooks the harness runs after every tool call.
202 if std::env::var("MODE").as_deref() != Ok("steer") {
203 abuse::watch();
204 }
Agents as a team: lifecycle, merge queue, billing and a new shell205 // The same image does the other jobs a sandbox is started for.
206 match std::env::var("MODE").as_deref() {
GitHub Actions on g1t, part two: running workflows207 Ok("actions") => std::process::exit(actions::main()),
Agents as a team: lifecycle, merge queue, billing and a new shell208 Ok("checks") => std::process::exit(checks::main()),
Deployments: a preview for every pull request, production on g1t.page209 Ok("deploy") => std::process::exit(deploy::main()),
Agents as a team: lifecycle, merge queue, billing and a new shell210 Ok("update") => std::process::exit(update::main()),
211 Ok("review") => std::process::exit(review::main()),
212 Ok("revise") => std::process::exit(revise::main()),
Agents asked while not at work are woken to answer213 Ok("answer") => std::process::exit(revise::answer()),
Agents as a team: lifecycle, merge queue, billing and a new shell214 Ok("plan") => std::process::exit(plan::main()),
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API215 Ok("reply") => std::process::exit(reply::main()),
Agents as a team: lifecycle, merge queue, billing and a new shell216 Ok("queue") => std::process::exit(queue::main()),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains217 Ok("mergecheck") => std::process::exit(mergecheck::main()),
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request218 Ok("steer") => std::process::exit(steer::main()),
Agents as a team: lifecycle, merge queue, billing and a new shell219 _ => {}
Acceptance checks in sandboxes, line comments and review verdicts220 }
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)221 let mut reporter = match Reporter::from_env() {
222 Ok(reporter) => reporter,
223 Err(error) => {
224 eprintln!("g1t-runner: {error:#}");
225 std::process::exit(2);
226 }
227 };
228 match run(&mut reporter) {
229 Ok(summary) => {
230 reporter.flush();
Issues and pull requests replace intents and attempts231 if let Err(error) = reporter.ready(&summary) {
232 eprintln!("g1t-runner: could not mark the pull request ready: {error:#}");
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)233 std::process::exit(1);
234 }
235 }
236 Err(error) => {
237 eprintln!("g1t-runner: {error:#}");
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API238 // Stopped at a cap: like a person's stop, the pull request is
239 // left open for a person, not closed.
240 if guard::is_halt(&error) {
241 reporter.record(Entry::new("note", &format!("g1t stopped the agent: {error:#}.")));
242 reporter.flush();
243 std::process::exit(1);
244 }
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)245 reporter.record(Entry::new("note", &format!("The run failed: {error:#}")));
246 reporter.flush();
Issues and pull requests replace intents and attempts247 let _ = reporter.close();
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)248 std::process::exit(1);
249 }
250 }
251}