Skip to content
294 linesCodeBlameRaw
1//! Runs a coding agent on one pull request and reports back to g1t.
2//!
3//! 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
7//! as an agent on someone's own machine would.
8//!
9//! `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
13//! into issues, `queue` builds and checks a state of the merge queue,
14//! `mergecheck` finds out whether a pull request merges cleanly,
15//! `actions` runs one job of a GitHub Actions workflow, `backup` cuts a
16//! repository's nightly backup bundle, `bump` makes a
17//! security update: one package raised in its lockfiles, pushed as g1t,
18//! and `computer` is a workspace agent's own computer, served for as long
19//! as it is awake. See the modules of those names.
20//!
21//! Configuration comes from the environment:
22//!
23//! - `G1T_API`, `G1T_TOKEN`, `G1T_USER`: where and who to report as.
24//! - `G1T_REPO`, `PULL_NUMBER`, `GIT_REMOTE`: the pull request and its fork.
25//! - `PROMPT`: what the agent is asked to do.
26//! - `COMMIT_MESSAGE`: used if the agent leaves changes uncommitted.
27//! - `ANTHROPIC_API_KEY`: read by the harness itself.
28//!
29//! Every mode runs with the mining watch in `abuse`: a sandbox that looks
30//! like it is mining stops itself and exits with `abuse::EXIT_CODE`.
31//!
32//! Given a command instead (`register`, `run`, `service`, `remove`,
33//! `update`, `version`), it is a self-hosted runner on someone's own
34//! machine, which runs work in these modes: see `selfhosted`.
35//!
36//! `deploy` and `detect` are for a workflow step: a g1t.page build of the
37//! job's own checkout, and what that build would find (see `deploy`).
38
39mod abuse;
40mod actions;
41mod backup;
42mod bump;
43mod checks;
44mod clone;
45mod computer;
46mod confidence;
47mod deploy;
48mod docker;
49mod guard;
50mod harness;
51mod learned;
52mod mergecheck;
53mod plan;
54mod progress;
55mod queue;
56mod reply;
57mod report;
58mod review;
59mod revise;
60mod selfhosted;
61mod steer;
62mod update;
63
64use std::path::Path;
65use std::process::Command;
66
67use anyhow::{Context, Result, bail};
68use base64::Engine;
69use base64::engine::general_purpose::STANDARD;
70
71use report::{Entry, Reporter};
72
73pub(crate) const WORKDIR: &str = "/work/repo";
74/// The name and address on every commit g1t makes here, whether its agent
75/// or g1t itself: `g1t_contracts::system::{USERNAME, EMAIL}`.
76pub(crate) const AUTHOR_NAME: &str = "g1t";
77pub(crate) const AUTHOR_EMAIL: &str = "g1t@users.noreply.g1t.sh";
78
79pub(crate) fn env(name: &str) -> Result<String> {
80 std::env::var(name).with_context(|| format!("{name} is not set"))
81}
82
83/// Runs git and returns its trimmed output, failing on a non-zero exit.
84pub(crate) fn git(dir: &Path, args: &[&str]) -> Result<String> {
85 let output = Command::new("git")
86 .current_dir(dir)
87 .args(args)
88 .output()
89 .context("could not run git")?;
90 if !output.status.success() {
91 bail!(
92 "git {} failed: {}",
93 args.first().unwrap_or(&""),
94 String::from_utf8_lossy(&output.stderr).trim()
95 );
96 }
97 Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
98}
99
100/// A git option that authenticates one command. The credential is passed
101/// per command and never written to the clone's config or its remote URL,
102/// where the agent would find it.
103pub(crate) fn auth_option(user: &str, token: &str) -> String {
104 let credentials = STANDARD.encode(format!("{user}:{token}"));
105 format!("http.extraHeader=Authorization: Basic {credentials}")
106}
107
108/// Clones the fork, runs the agent on `PROMPT`, commits and pushes what it
109/// did, and returns its closing summary.
110pub(crate) fn run(reporter: &mut Reporter) -> Result<String> {
111 let mut prompt = env("PROMPT")?;
112 let remote = env("GIT_REMOTE")?;
113 let auth = auth_option(&env("G1T_USER")?, &env("G1T_TOKEN")?);
114 let workdir = Path::new(WORKDIR);
115
116 // Which model, and why: the router's one line names both.
117 let reason = std::env::var("AGENT_MODEL_REASON").unwrap_or_default();
118 if !reason.trim().is_empty() {
119 reporter.record(Entry::new("note", reason.trim()));
120 } else if let Ok(model) = std::env::var("AGENT_MODEL_NAME") {
121 reporter.record(Entry::new("note", &format!("Running on {model}.")));
122 }
123 reporter.record(Entry::new("prompt", &prompt));
124 reporter.flush();
125
126 std::fs::create_dir_all("/work")?;
127 clone::clone(Path::new("/work"), &auth, &[], &remote, WORKDIR).context("could not clone the pull request's fork")?;
128 git(workdir, &["config", "user.name", crate::AUTHOR_NAME])?;
129 git(workdir, &["config", "user.email", crate::AUTHOR_EMAIL])?;
130 let branch = git(workdir, &["rev-parse", "--abbrev-ref", "HEAD"])?;
131 let start = git(workdir, &["rev-parse", "HEAD"]).unwrap_or_default();
132
133 // Sent back to work that is already open: start from where the branch it
134 // will land on is now, so what passes here passes there too.
135 if let (Ok(upstream), Ok(upstream_branch)) = (env("UPSTREAM_REMOTE"), env("UPSTREAM_BRANCH")) {
136 clone::fetch(workdir, &auth, &upstream, &upstream_branch).context("could not fetch the branch this will land on")?;
137 // Shallow: deep enough to tell whether it is behind, and to merge.
138 clone::share_history(workdir, &auth, &[("origin", branch.as_str()), (upstream.as_str(), upstream_branch.as_str())], "HEAD", "FETCH_HEAD")?;
139 let behind = Command::new("git")
140 .current_dir(workdir)
141 .args(["merge-base", "--is-ancestor", "FETCH_HEAD", "HEAD"])
142 .status()
143 .is_ok_and(|status| !status.success());
144 if behind {
145 let message = format!("Catch up with {upstream_branch}");
146 let merged = Command::new("git")
147 .current_dir(workdir)
148 .args(["merge", "--quiet", "--no-edit", "-m", &message, "FETCH_HEAD"])
149 .status()
150 .is_ok_and(|status| status.success());
151 if merged {
152 reporter.record(Entry::new(
153 "note",
154 &format!("Merged in the latest {upstream_branch} before starting."),
155 ));
156 } else {
157 let files = git(workdir, &["diff", "--name-only", "--diff-filter=U"])?;
158 let files: Vec<&str> = files.lines().collect();
159 reporter.record(Entry::new(
160 "note",
161 &format!(
162 "Merged in the latest {upstream_branch} before starting; {} conflict.",
163 files.join(", ")
164 ),
165 ));
166 prompt.push_str(&format!(
167 "\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.",
168 files.join(", ")
169 ));
170 }
171 reporter.flush();
172 }
173 }
174
175 // The agent is asked what it learned, which goes to memory, and how sure
176 // it is of its change, which g1t weighs with what it observes. Neither
177 // stays in the summary.
178 let asked = confidence::ask(&learned::ask(&prompt));
179 let summary = confidence::finish(learned::finish(harness::run_claude(workdir, &asked, reporter)?));
180
181 // Commit whatever the agent left in the working tree.
182 if !git(workdir, &["status", "--porcelain"])?.is_empty() {
183 let message = std::env::var("COMMIT_MESSAGE").unwrap_or_else(|_| "Agent changes".into());
184 git(workdir, &["add", "--all"])?;
185 git(workdir, &["commit", "--quiet", "--message", &message])?;
186 }
187 let head = git(workdir, &["rev-parse", "HEAD"])?;
188 if head == start {
189 // An agent woken to answer usually only answers.
190 if std::env::var("MODE").as_deref() == Ok("answer") {
191 return Ok(summary);
192 }
193 bail!("the agent finished without changing anything");
194 }
195 git(
196 workdir,
197 &[
198 "-c",
199 &auth,
200 "push",
201 "--quiet",
202 "origin",
203 &format!("HEAD:{branch}"),
204 ],
205 )
206 .context("could not push the pull request's commits")?;
207 reporter.record(Entry::new(
208 "note",
209 &format!("Pushed {}.", &head[..head.len().min(12)]),
210 ));
211 Ok(summary)
212}
213
214fn main() {
215 // The runc the job's Docker Engine starts containers with (docker/oci.rs).
216 if docker::oci::invoked_as_runc() {
217 docker::oci::main();
218 }
219 // A self-hosted runner's commands; the modes below are what it, and
220 // g1t's sandboxes, run work with.
221 let args: Vec<String> = std::env::args().skip(1).collect();
222 // From a workflow step: a g1t.page build of the job's own checkout,
223 // and what it would find (deploy.rs).
224 match args.first().map(String::as_str) {
225 Some("deploy") => std::process::exit(deploy::cli(&args[1..])),
226 Some("detect") => std::process::exit(deploy::detect_cli(&args[1..])),
227 _ => {}
228 }
229 if selfhosted::is_command(&args) {
230 std::process::exit(selfhosted::main(args));
231 }
232 // A guarded sandbox's HTTPS is re-signed on its way out: trust that
233 // before anything is fetched. The guard hook runs before every tool
234 // call, so it skips this.
235 if std::env::var("MODE").as_deref() == Ok("guard") {
236 std::process::exit(guard::hook_main());
237 }
238 guard::trust_egress_ca();
239 // Watches for mining for as long as the sandbox runs (abuse.rs). Not in
240 // the hooks the harness runs after every tool call.
241 if std::env::var("MODE").as_deref() != Ok("steer") {
242 abuse::watch();
243 }
244 // The same image does the other jobs a sandbox is started for.
245 match std::env::var("MODE").as_deref() {
246 Ok("actions") => std::process::exit(actions::main()),
247 Ok("backup") => std::process::exit(backup::main()),
248 Ok("bump") => std::process::exit(bump::main()),
249 Ok("checks") => std::process::exit(checks::main()),
250 // An agent's own computer: serves until it is put to sleep.
251 Ok("computer") => std::process::exit(computer::main()),
252 Ok("deploy") => std::process::exit(deploy::main()),
253 Ok("update") => std::process::exit(update::main()),
254 Ok("review") => std::process::exit(review::main()),
255 Ok("revise") => std::process::exit(revise::main()),
256 Ok("answer") => std::process::exit(revise::answer()),
257 Ok("plan") => std::process::exit(plan::main()),
258 Ok("reply") => std::process::exit(reply::main()),
259 Ok("queue") => std::process::exit(queue::main()),
260 Ok("mergecheck") => std::process::exit(mergecheck::main()),
261 Ok("steer") => std::process::exit(steer::main()),
262 _ => {}
263 }
264 let mut reporter = match Reporter::from_env() {
265 Ok(reporter) => reporter,
266 Err(error) => {
267 eprintln!("g1t-runner: {error:#}");
268 std::process::exit(2);
269 }
270 };
271 match run(&mut reporter) {
272 Ok(summary) => {
273 reporter.flush();
274 if let Err(error) = reporter.ready(&summary) {
275 eprintln!("g1t-runner: could not mark the pull request ready: {error:#}");
276 std::process::exit(1);
277 }
278 }
279 Err(error) => {
280 eprintln!("g1t-runner: {error:#}");
281 // Stopped at a cap: like a person's stop, the pull request is
282 // left open for a person, not closed.
283 if guard::is_halt(&error) {
284 reporter.record(Entry::new("note", &format!("g1t stopped the agent: {error:#}.")));
285 reporter.flush();
286 std::process::exit(1);
287 }
288 reporter.record(Entry::new("note", &format!("The run failed: {error:#}")));
289 reporter.flush();
290 let _ = reporter.close();
291 std::process::exit(1);
292 }
293 }
294}