Skip to content
374 linesCodeBlameRaw
1//! The agent harness. g1t does not implement its own agent loop: it runs
2//! Claude Code headless and translates its event stream into session
3//! entries.
4
5use std::io::{BufRead, BufReader};
6use std::path::Path;
7use std::process::{Command, Stdio};
8use std::sync::Arc;
9use std::sync::atomic::{AtomicBool, Ordering};
10use std::time::Duration;
11
12use anyhow::{Context, Result, bail};
13use serde_json::Value;
14
15use crate::guard::{self, Halted, Policy};
16use crate::progress::{self, Progress};
17use crate::report::{Entry, Reporter};
18
19const MAX_TURNS: &str = "80";
20
21/// A compact, readable rendering of a tool's input.
22fn describe_input(tool: &str, input: &Value) -> String {
23 let field = |name: &str| input.get(name).and_then(Value::as_str);
24 match tool {
25 "Bash" => field("command").unwrap_or_default().to_owned(),
26 "Read" | "Write" | "Edit" | "MultiEdit" | "NotebookEdit" => {
27 field("file_path").unwrap_or_default().to_owned()
28 }
29 "Glob" | "Grep" => field("pattern").unwrap_or_default().to_owned(),
30 _ => serde_json::to_string(input).unwrap_or_default(),
31 }
32}
33
34/// The text of a tool result, which is either a string or content blocks.
35fn result_text(content: &Value) -> String {
36 match content {
37 Value::String(text) => text.clone(),
38 Value::Array(blocks) => blocks
39 .iter()
40 .filter_map(|block| block.get("text").and_then(Value::as_str))
41 .collect::<Vec<_>>()
42 .join("\n"),
43 _ => String::new(),
44 }
45}
46
47/// The tokens a run used, from Claude Code's closing `usage`: input,
48/// output, and prompt-cache reads and writes. On a workspace's own model
49/// key this is what g1t charges its agent rate on (the model proxy's own
50/// count, when it has more, wins), so it is reported with the cost.
51fn run_tokens(event: &Value) -> Value {
52 let usage = &event["usage"];
53 let count = |field: &str| usage[field].as_u64().unwrap_or_default();
54 serde_json::json!({
55 "input": count("input_tokens"),
56 "output": count("output_tokens"),
57 "cache_read": count("cache_read_input_tokens"),
58 "cache_write": count("cache_creation_input_tokens"),
59 })
60}
61
62/// Tells g1t what the run cost, so that the workspace it was for can be
63/// charged. The run's own token, given to this sandbox and to nothing
64/// else, is the credential. Does nothing where runs are not billed.
65fn report_cost(cost_usd: f64, turns: u64, tokens: Value) {
66 let (Ok(api), Ok(run), Ok(token)) = (
67 std::env::var("G1T_API"),
68 std::env::var("BILLING_RUN"),
69 std::env::var("BILLING_TOKEN"),
70 ) else {
71 return;
72 };
73 let sent = ureq::post(&format!("{api}/runs/{run}/usage")).send_json(serde_json::json!({
74 "token": token,
75 "cost_usd": cost_usd,
76 "turns": turns,
77 "tokens": tokens,
78 }));
79 if let Err(error) = sent {
80 eprintln!("g1t-runner: could not report what the run cost: {error}");
81 }
82}
83
84/// Records one line of Claude Code's `stream-json` output. Returns the final
85/// result when the line is the one that ends the run.
86fn handle_event(
87 event: &Value,
88 reporter: &mut Reporter,
89 progress: &mut Option<Progress>,
90) -> Option<Result<String>> {
91 let blocks = || {
92 event["message"]["content"]
93 .as_array()
94 .map(Vec::as_slice)
95 .unwrap_or_default()
96 };
97 match event["type"].as_str()? {
98 "assistant" => {
99 for block in blocks() {
100 match block["type"].as_str() {
101 Some("text") => {
102 let text = block["text"].as_str().unwrap_or_default().trim();
103 if !text.is_empty() {
104 reporter.record(Entry::new("message", text));
105 if let Some(progress) = progress {
106 progress.step(&format!("Said: {}", text.lines().next().unwrap_or_default()));
107 }
108 }
109 }
110 Some("tool_use") => {
111 crate::abuse::touch();
112 let tool = block["name"].as_str().unwrap_or("tool");
113 if let Some(progress) = progress {
114 progress.step(&progress::describe_tool(tool, &block["input"]));
115 }
116 reporter.record(Entry::tool(
117 "tool_call",
118 tool,
119 &describe_input(tool, &block["input"]),
120 ));
121 }
122 _ => {}
123 }
124 }
125 None
126 }
127 "user" => {
128 for block in blocks() {
129 if block["type"] == "tool_result" {
130 let text = result_text(&block["content"]);
131 if !text.trim().is_empty() {
132 reporter.record(Entry::tool("tool_result", "result", text.trim()));
133 }
134 }
135 }
136 None
137 }
138 "result" => {
139 let text = event["result"].as_str().unwrap_or_default().to_owned();
140 // What the run cost, as the harness worked it out, kept with
141 // the session so that spend can be read per pull request.
142 if let Some(cost) = event["total_cost_usd"].as_f64() {
143 let turns = event["num_turns"].as_u64().unwrap_or_default();
144 report_cost(cost, turns, run_tokens(event));
145 if let Some(progress) = progress {
146 progress.cost(cost, turns);
147 }
148 reporter.record(Entry::new(
149 "note",
150 &format!("This run cost ${cost:.4} over {turns} turns."),
151 ));
152 }
153 // Claude Code stopped at the run's cost cap (`--max-budget-usd`).
154 if event["subtype"] == "error_max_budget_usd" {
155 return Some(Err(anyhow::Error::new(Halted::Budget)));
156 }
157 Some(if event["is_error"].as_bool().unwrap_or(false) {
158 Err(anyhow::anyhow!("the agent reported an error: {text}"))
159 } else {
160 Ok(text)
161 })
162 }
163 _ => None,
164 }
165}
166
167/// Runs Claude Code on `prompt` in `workdir` and returns its closing
168/// summary.
169pub fn run_claude(workdir: &Path, prompt: &str, reporter: &mut Reporter) -> Result<String> {
170 // g1t's own tools, through a token that can do a few things in this one
171 // repository: read its issues, pull requests and merge queue, open an
172 // issue, and comment.
173 let mut tools = Vec::new();
174 if let Ok(token) = std::env::var("G1T_AGENT_TOKEN") {
175 let mut config = serde_json::json!({
176 "mcpServers": {
177 "g1t": {
178 "type": "http",
179 "url": std::env::var("G1T_MCP").unwrap_or_else(|_| "https://mcp.g1t.sh".to_owned()),
180 "headers": { "Authorization": format!("Bearer {token}") },
181 }
182 }
183 });
184 // What the workspace's Customize gives the run (customize.rs): its
185 // plugins and library skills as plugin folders, and its connectors
186 // beside g1t's own server. The connectors' keys stay in the config
187 // file and out of the transcript.
188 let loaded = crate::customize::prepare(&token, &mut config);
189 for secret in &loaded.secrets {
190 reporter.hide(secret);
191 }
192 let path = "/work/g1t-mcp.json";
193 if std::fs::write(path, config.to_string()).is_ok() {
194 tools = vec!["--mcp-config".to_owned(), path.to_owned()];
195 }
196 tools.extend(loaded.flags.iter().cloned());
197 if !loaded.is_empty() {
198 reporter.record(Entry::new("note", &loaded.note()));
199 }
200 // People can message the agent while it works: after each tool call
201 // a hook asks g1t for messages and hands any to the agent.
202 if let (Ok(repo), Ok(number)) = (std::env::var("G1T_REPO"), std::env::var("PULL_NUMBER")) {
203 let steer = serde_json::json!({
204 "api": std::env::var("G1T_API").unwrap_or_else(|_| "https://api.g1t.sh".to_owned()),
205 "token": token,
206 "repo": repo,
207 "number": number.parse::<u32>().unwrap_or_default(),
208 });
209 let hooks = serde_json::json!({
210 "hooks": {
211 "PostToolUse": [{
212 "matcher": "*",
213 "hooks": [{ "type": "command", "command": "MODE=steer /usr/local/bin/g1t-runner", "timeout": 15 }],
214 }],
215 "Stop": [{
216 "hooks": [{ "type": "command", "command": "MODE=steer G1T_HOOK=stop /usr/local/bin/g1t-runner", "timeout": 15 }],
217 }],
218 }
219 });
220 let home = std::env::var("HOME").unwrap_or_else(|_| "/home/node".to_owned());
221 let settings = format!("{home}/.claude/settings.json");
222 if std::fs::write(crate::steer::CONFIG, steer.to_string()).is_ok()
223 && std::fs::create_dir_all(format!("{home}/.claude")).is_ok()
224 {
225 let _ = std::fs::write(settings, hooks.to_string());
226 }
227 }
228 }
229 // The run's guardrails (guard.rs): the hook before every tool call, the
230 // permission rules, and the cost cap, which Claude Code enforces itself.
231 let policy = guard::Policy::from_env();
232 if let Some(policy) = &policy {
233 let installed = guard::install(policy, &std::env::var("GUARDRAILS").unwrap_or_default());
234 if let Some(file) = installed.settings_file {
235 tools.extend(["--settings".to_owned(), file]);
236 }
237 if let Some(budget) = policy.budget_usd.filter(|budget| *budget > 0.0) {
238 tools.extend(["--max-budget-usd".to_owned(), format!("{budget:.2}")]);
239 }
240 }
241 // A fork's checkout is anyone's: none of its CLAUDE.md, .claude
242 // settings, hooks, MCP servers or commands are loaded (guard.rs).
243 let trusted = guard::checkout_trusted_from_env();
244 if !trusted {
245 tools.extend(guard::UNTRUSTED_FLAGS.iter().map(|flag| (*flag).to_owned()));
246 reporter.record(Entry::new(
247 "note",
248 "This checkout is not the repository's own branch, so its CLAUDE.md and .claude settings, hooks, MCP servers and commands were not loaded.",
249 ));
250 }
251 let mut denials = guard::Denials::default();
252 // How the run goes, step by step, for people watching it live.
253 let mut progress = Progress::from_env();
254 if let Some(progress) = &mut progress {
255 progress.step("Started the agent");
256 }
257 let mut command = Command::new("claude");
258 if !trusted {
259 command.env(guard::UNTRUSTED_ENV.0, guard::UNTRUSTED_ENV.1);
260 }
261 let mut child = command
262 .current_dir(workdir)
263 .args(&tools)
264 .args([
265 "--print",
266 prompt,
267 "--output-format",
268 "stream-json",
269 "--verbose",
270 "--max-turns",
271 MAX_TURNS,
272 // The sandbox is the permission boundary: it holds one fork and
273 // one short-lived token, and nothing else.
274 "--dangerously-skip-permissions",
275 ])
276 // The agent needs the model key and nothing else of ours.
277 .env_remove("G1T_TOKEN")
278 .env_remove("REVIEW_TOKEN")
279 .env_remove("CHECK_TOKEN")
280 .env_remove("BILLING_TOKEN")
281 .env_remove("PLAN_TOKEN")
282 .env_remove("G1T_AGENT_TOKEN")
283 .env_remove("AGENT_RUN_TOKEN")
284 .stdin(Stdio::null())
285 .stdout(Stdio::piped())
286 .stderr(Stdio::inherit())
287 .spawn()
288 .context("could not start Claude Code")?;
289
290 // The time cap: the agent is stopped when it passes, and the run with it.
291 let timed_out = Arc::new(AtomicBool::new(false));
292 let finished = Arc::new(AtomicBool::new(false));
293 if let Some(minutes) = policy.as_ref().and_then(|policy| policy.minutes) {
294 let (pid, timed_out, finished) = (child.id(), timed_out.clone(), finished.clone());
295 std::thread::spawn(move || {
296 std::thread::sleep(Duration::from_secs(u64::from(minutes) * 60));
297 if !finished.load(Ordering::SeqCst) {
298 timed_out.store(true, Ordering::SeqCst);
299 let _ = Command::new("kill").arg(pid.to_string()).status();
300 }
301 });
302 }
303
304 let stdout = child.stdout.take().context("no output from Claude Code")?;
305 let mut outcome = None;
306 for line in BufReader::new(stdout).lines() {
307 let line = line?;
308 let Ok(event) = serde_json::from_str::<Value>(&line) else {
309 continue;
310 };
311 if let Some(result) = handle_event(&event, reporter, &mut progress) {
312 outcome = Some(result);
313 }
314 // What the guardrails refused, as steps people can see.
315 for denied in denials.take() {
316 reporter.record(Entry::new("note", &denied));
317 if let Some(progress) = &mut progress {
318 progress.step(&denied);
319 }
320 }
321 }
322 let status = child.wait()?;
323 finished.store(true, Ordering::SeqCst);
324 if timed_out.load(Ordering::SeqCst) {
325 outcome = Some(Err(anyhow::Error::new(Halted::Time)));
326 }
327 if let Some(progress) = &mut progress {
328 progress.flush();
329 if let Some(halted) = outcome.as_ref().and_then(|o| o.as_ref().err()).and_then(|e| e.downcast_ref::<Halted>()) {
330 let message = match (halted, &policy) {
331 (Halted::Budget, Some(Policy { budget_usd: Some(budget), .. })) => {
332 format!("Stopped: it reached its cost cap of ${budget:.2}.")
333 }
334 (Halted::Time, Some(Policy { minutes: Some(minutes), .. })) => {
335 format!("Stopped: it reached its time cap of {minutes} minutes.")
336 }
337 _ => format!("Stopped: {halted}."),
338 };
339 progress.halt(halted.reason(), &message);
340 }
341 }
342 match outcome {
343 Some(result) => result,
344 None => bail!("Claude Code exited ({status}) without a result"),
345 }
346}
347
348#[cfg(test)]
349mod tests {
350 use super::*;
351
352 #[test]
353 fn a_runs_tokens_come_from_the_closing_usage_by_kind() {
354 let event = serde_json::json!({
355 "type": "result",
356 "total_cost_usd": 0.42,
357 "usage": {
358 "input_tokens": 1200,
359 "output_tokens": 340,
360 "cache_read_input_tokens": 90000,
361 "cache_creation_input_tokens": 5000,
362 },
363 });
364 assert_eq!(
365 run_tokens(&event),
366 serde_json::json!({ "input": 1200, "output": 340, "cache_read": 90000, "cache_write": 5000 })
367 );
368 // An older harness without usage reports nothing, not an error.
369 assert_eq!(
370 run_tokens(&serde_json::json!({ "type": "result" })),
371 serde_json::json!({ "input": 0, "output": 0, "cache_read": 0, "cache_write": 0 })
372 );
373 }
374}