Skip to content

g1t/crates/runner/src/main.rs

275 lines11,464 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,
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily14//! `mergecheck` finds out whether a pull request merges cleanly,
Merge branch 'worktree-agent-ac5b181a013e54348'15//! `actions` runs one job of a GitHub Actions workflow, `backup` cuts a
16//! repository's nightly backup bundle, and `bump` makes a
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily17//! security update: one package raised in its lockfiles, pushed as g1t.
Agents as a team: lifecycle, merge queue, billing and a new shell18//! See the modules of those names.
Acceptance checks in sandboxes, line comments and review verdicts19//!
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)20//! Configuration comes from the environment:
21//!
22//! - `G1T_API`, `G1T_TOKEN`, `G1T_USER`: where and who to report as.
Issues and pull requests replace intents and attempts23//! - `G1T_REPO`, `PULL_NUMBER`, `GIT_REMOTE`: the pull request and its fork.
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)24//! - `PROMPT`: what the agent is asked to do.
25//! - `COMMIT_MESSAGE`: used if the agent leaves changes uncommitted.
26//! - `ANTHROPIC_API_KEY`: read by the harness itself.
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look27//!
28//! Every mode runs with the mining watch in `abuse`: a sandbox that looks
29//! like it is mining stops itself and exits with `abuse::EXIT_CODE`.
Fast pages, required checks on the branch, self-hosted runners, honest incidents30//!
31//! Given a command instead (`register`, `run`, `service`, `remove`,
32//! `update`, `version`), it is a self-hosted runner on someone's own
33//! machine, which runs work in these modes: see `selfhosted`.
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)34
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look35mod abuse;
GitHub Actions on g1t, part two: running workflows36mod actions;
Merge branch 'worktree-agent-ac5b181a013e54348'37mod backup;
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily38mod bump;
Acceptance checks in sandboxes, line comments and review verdicts39mod checks;
Fast pages, required checks on the branch, self-hosted runners, honest incidents40mod clone;
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step41mod confidence;
Deployments: a preview for every pull request, production on g1t.page42mod deploy;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API43mod guard;
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)44mod harness;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API45mod learned;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains46mod mergecheck;
Agents as a team: lifecycle, merge queue, billing and a new shell47mod plan;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains48mod progress;
Agents as a team: lifecycle, merge queue, billing and a new shell49mod queue;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API50mod reply;
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)51mod report;
Agents as a team: lifecycle, merge queue, billing and a new shell52mod review;
53mod revise;
Fast pages, required checks on the branch, self-hosted runners, honest incidents54mod selfhosted;
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request55mod steer;
Agents as a team: lifecycle, merge queue, billing and a new shell56mod update;
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)57
58use std::path::Path;
59use std::process::Command;
60
61use anyhow::{Context, Result, bail};
62use base64::Engine;
63use base64::engine::general_purpose::STANDARD;
64
65use report::{Entry, Reporter};
66
Acceptance checks in sandboxes, line comments and review verdicts67pub(crate) const WORKDIR: &str = "/work/repo";
g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent68/// The name and address on every commit g1t makes here, whether its agent
69/// or g1t itself: `g1t_contracts::system::{USERNAME, EMAIL}`.
70pub(crate) const AUTHOR_NAME: &str = "g1t";
71pub(crate) const AUTHOR_EMAIL: &str = "g1t@users.noreply.g1t.sh";
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)72
Acceptance checks in sandboxes, line comments and review verdicts73pub(crate) fn env(name: &str) -> Result<String> {
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)74 std::env::var(name).with_context(|| format!("{name} is not set"))
75}
76
77/// Runs git and returns its trimmed output, failing on a non-zero exit.
Acceptance checks in sandboxes, line comments and review verdicts78pub(crate) fn git(dir: &Path, args: &[&str]) -> Result<String> {
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)79 let output = Command::new("git")
80 .current_dir(dir)
81 .args(args)
82 .output()
83 .context("could not run git")?;
84 if !output.status.success() {
85 bail!(
86 "git {} failed: {}",
87 args.first().unwrap_or(&""),
88 String::from_utf8_lossy(&output.stderr).trim()
89 );
90 }
91 Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
92}
93
94/// A git option that authenticates one command. The credential is passed
95/// per command and never written to the clone's config or its remote URL,
96/// where the agent would find it.
Acceptance checks in sandboxes, line comments and review verdicts97pub(crate) fn auth_option(user: &str, token: &str) -> String {
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)98 let credentials = STANDARD.encode(format!("{user}:{token}"));
99 format!("http.extraHeader=Authorization: Basic {credentials}")
100}
101
Agents as a team: lifecycle, merge queue, billing and a new shell102/// Clones the fork, runs the agent on `PROMPT`, commits and pushes what it
103/// did, and returns its closing summary.
104pub(crate) fn run(reporter: &mut Reporter) -> Result<String> {
105 let mut prompt = env("PROMPT")?;
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)106 let remote = env("GIT_REMOTE")?;
107 let auth = auth_option(&env("G1T_USER")?, &env("G1T_TOKEN")?);
108 let workdir = Path::new(WORKDIR);
109
Merge branch 'model-routing'110 // Which model, and why: the router's one line names both.
111 let reason = std::env::var("AGENT_MODEL_REASON").unwrap_or_default();
112 if !reason.trim().is_empty() {
113 reporter.record(Entry::new("note", reason.trim()));
114 } else if let Ok(model) = std::env::var("AGENT_MODEL_NAME") {
Show the model behind each choice; toolchains in the sandbox115 reporter.record(Entry::new("note", &format!("Running on {model}.")));
116 }
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)117 reporter.record(Entry::new("prompt", &prompt));
118 reporter.flush();
119
120 std::fs::create_dir_all("/work")?;
Fast pages, required checks on the branch, self-hosted runners, honest incidents121 clone::clone(Path::new("/work"), &auth, &[], &remote, WORKDIR).context("could not clone the pull request's fork")?;
g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent122 git(workdir, &["config", "user.name", crate::AUTHOR_NAME])?;
123 git(workdir, &["config", "user.email", crate::AUTHOR_EMAIL])?;
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)124 let branch = git(workdir, &["rev-parse", "--abbrev-ref", "HEAD"])?;
125 let start = git(workdir, &["rev-parse", "HEAD"]).unwrap_or_default();
126
Agents as a team: lifecycle, merge queue, billing and a new shell127 // Sent back to work that is already open: start from where the branch it
128 // will land on is now, so what passes here passes there too.
129 if let (Ok(upstream), Ok(upstream_branch)) = (env("UPSTREAM_REMOTE"), env("UPSTREAM_BRANCH")) {
Fast pages, required checks on the branch, self-hosted runners, honest incidents130 clone::fetch(workdir, &auth, &upstream, &upstream_branch).context("could not fetch the branch this will land on")?;
131 // Shallow: deep enough to tell whether it is behind, and to merge.
132 clone::share_history(workdir, &auth, &[("origin", branch.as_str()), (upstream.as_str(), upstream_branch.as_str())], "HEAD", "FETCH_HEAD")?;
Agents as a team: lifecycle, merge queue, billing and a new shell133 let behind = Command::new("git")
134 .current_dir(workdir)
135 .args(["merge-base", "--is-ancestor", "FETCH_HEAD", "HEAD"])
136 .status()
137 .is_ok_and(|status| !status.success());
138 if behind {
139 let message = format!("Catch up with {upstream_branch}");
140 let merged = Command::new("git")
141 .current_dir(workdir)
142 .args(["merge", "--quiet", "--no-edit", "-m", &message, "FETCH_HEAD"])
143 .status()
144 .is_ok_and(|status| status.success());
145 if merged {
146 reporter.record(Entry::new(
147 "note",
148 &format!("Merged in the latest {upstream_branch} before starting."),
149 ));
150 } else {
151 let files = git(workdir, &["diff", "--name-only", "--diff-filter=U"])?;
152 let files: Vec<&str> = files.lines().collect();
153 reporter.record(Entry::new(
154 "note",
155 &format!(
156 "Merged in the latest {upstream_branch} before starting; {} conflict.",
157 files.join(", ")
158 ),
159 ));
160 prompt.push_str(&format!(
161 "\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.",
162 files.join(", ")
163 ));
164 }
165 reporter.flush();
166 }
167 }
168
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step169 // The agent is asked what it learned, which goes to memory, and how sure
170 // it is of its change, which g1t weighs with what it observes. Neither
171 // stays in the summary.
172 let asked = confidence::ask(&learned::ask(&prompt));
173 let summary = confidence::finish(learned::finish(harness::run_claude(workdir, &asked, reporter)?));
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)174
175 // Commit whatever the agent left in the working tree.
176 if !git(workdir, &["status", "--porcelain"])?.is_empty() {
177 let message = std::env::var("COMMIT_MESSAGE").unwrap_or_else(|_| "Agent changes".into());
178 git(workdir, &["add", "--all"])?;
179 git(workdir, &["commit", "--quiet", "--message", &message])?;
180 }
181 let head = git(workdir, &["rev-parse", "HEAD"])?;
182 if head == start {
Agents asked while not at work are woken to answer183 // An agent woken to answer usually only answers.
184 if std::env::var("MODE").as_deref() == Ok("answer") {
185 return Ok(summary);
186 }
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)187 bail!("the agent finished without changing anything");
188 }
189 git(
190 workdir,
191 &[
192 "-c",
193 &auth,
194 "push",
195 "--quiet",
196 "origin",
197 &format!("HEAD:{branch}"),
198 ],
199 )
Issues and pull requests replace intents and attempts200 .context("could not push the pull request's commits")?;
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)201 reporter.record(Entry::new(
202 "note",
Issues and pull requests replace intents and attempts203 &format!("Pushed {}.", &head[..head.len().min(12)]),
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)204 ));
205 Ok(summary)
206}
207
208fn main() {
Fast pages, required checks on the branch, self-hosted runners, honest incidents209 // A self-hosted runner's commands; the modes below are what it, and
210 // g1t's sandboxes, run work with.
211 let args: Vec<String> = std::env::args().skip(1).collect();
212 if selfhosted::is_command(&args) {
213 std::process::exit(selfhosted::main(args));
214 }
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API215 // A guarded sandbox's HTTPS is re-signed on its way out: trust that
216 // before anything is fetched. The guard hook runs before every tool
217 // call, so it skips this.
218 if std::env::var("MODE").as_deref() == Ok("guard") {
219 std::process::exit(guard::hook_main());
220 }
221 guard::trust_egress_ca();
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look222 // Watches for mining for as long as the sandbox runs (abuse.rs). Not in
223 // the hooks the harness runs after every tool call.
224 if std::env::var("MODE").as_deref() != Ok("steer") {
225 abuse::watch();
226 }
Agents as a team: lifecycle, merge queue, billing and a new shell227 // The same image does the other jobs a sandbox is started for.
228 match std::env::var("MODE").as_deref() {
GitHub Actions on g1t, part two: running workflows229 Ok("actions") => std::process::exit(actions::main()),
Merge branch 'worktree-agent-ac5b181a013e54348'230 Ok("backup") => std::process::exit(backup::main()),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily231 Ok("bump") => std::process::exit(bump::main()),
Agents as a team: lifecycle, merge queue, billing and a new shell232 Ok("checks") => std::process::exit(checks::main()),
Deployments: a preview for every pull request, production on g1t.page233 Ok("deploy") => std::process::exit(deploy::main()),
Agents as a team: lifecycle, merge queue, billing and a new shell234 Ok("update") => std::process::exit(update::main()),
235 Ok("review") => std::process::exit(review::main()),
236 Ok("revise") => std::process::exit(revise::main()),
Agents asked while not at work are woken to answer237 Ok("answer") => std::process::exit(revise::answer()),
Agents as a team: lifecycle, merge queue, billing and a new shell238 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 API239 Ok("reply") => std::process::exit(reply::main()),
Agents as a team: lifecycle, merge queue, billing and a new shell240 Ok("queue") => std::process::exit(queue::main()),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains241 Ok("mergecheck") => std::process::exit(mergecheck::main()),
Usage, like a hosting provider's: what agents cost, per day, task, repository and pull request242 Ok("steer") => std::process::exit(steer::main()),
Agents as a team: lifecycle, merge queue, billing and a new shell243 _ => {}
Acceptance checks in sandboxes, line comments and review verdicts244 }
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)245 let mut reporter = match Reporter::from_env() {
246 Ok(reporter) => reporter,
247 Err(error) => {
248 eprintln!("g1t-runner: {error:#}");
249 std::process::exit(2);
250 }
251 };
252 match run(&mut reporter) {
253 Ok(summary) => {
254 reporter.flush();
Issues and pull requests replace intents and attempts255 if let Err(error) = reporter.ready(&summary) {
256 eprintln!("g1t-runner: could not mark the pull request ready: {error:#}");
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)257 std::process::exit(1);
258 }
259 }
260 Err(error) => {
261 eprintln!("g1t-runner: {error:#}");
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API262 // Stopped at a cap: like a person's stop, the pull request is
263 // left open for a person, not closed.
264 if guard::is_halt(&error) {
265 reporter.record(Entry::new("note", &format!("g1t stopped the agent: {error:#}.")));
266 reporter.flush();
267 std::process::exit(1);
268 }
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)269 reporter.record(Entry::new("note", &format!("The run failed: {error:#}")));
270 reporter.flush();
Issues and pull requests replace intents and attempts271 let _ = reporter.close();
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)272 std::process::exit(1);
273 }
274 }
275}

This file's history is long; its oldest lines are credited to the oldest commit read.