aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/agent.rs16
-rw-r--r--src/main.rs221
-rw-r--r--src/session.rs22
-rw-r--r--src/ui.rs26
4 files changed, 280 insertions, 5 deletions
diff --git a/src/agent.rs b/src/agent.rs
index d574934..4bf19ed 100644
--- a/src/agent.rs
+++ b/src/agent.rs
@@ -9,7 +9,7 @@ use crate::config::Config;
9use crate::provider::{self, Error, Outcome}; 9use crate::provider::{self, Error, Outcome};
10use crate::session::Session; 10use crate::session::Session;
11use crate::tools::{self, Approval}; 11use crate::tools::{self, Approval};
12use crate::ui::{self, Approver, Renderer}; 12use crate::ui::{self, Approver, Renderer, Summary};
13 13
14/// Frozen for the life of the session. Anything session-varying added here 14/// Frozen for the life of the session. Anything session-varying added here
15/// invalidates the provider's prompt cache, so keep it boring. 15/// invalidates the provider's prompt cache, so keep it boring.
@@ -128,6 +128,8 @@ pub struct TurnReport {
128 pub steps: usize, 128 pub steps: usize,
129 pub aborted: bool, 129 pub aborted: bool,
130 pub denied: usize, 130 pub denied: usize,
131 pub writes: usize,
132 pub commands: usize,
131} 133}
132 134
133pub enum ToolOutcome { 135pub enum ToolOutcome {
@@ -188,6 +190,7 @@ pub fn run_turn(
188 let mut last: Option<Outcome> = None; 190 let mut last: Option<Outcome> = None;
189 let mut aborted = false; 191 let mut aborted = false;
190 let mut denied = 0usize; 192 let mut denied = 0usize;
193 let mut summary = Summary::default();
191 let mut truncated: Option<String> = None; 194 let mut truncated: Option<String> = None;
192 195
193 loop { 196 loop {
@@ -248,6 +251,13 @@ pub fn run_turn(
248 }; 251 };
249 if result.denied() { 252 if result.denied() {
250 denied += 1; 253 denied += 1;
254 summary.denied += 1;
255 } else if !aborted {
256 match call.name.as_str() {
257 "write" | "edit" => summary.writes += 1,
258 "bash" => summary.commands += 1,
259 _ => {}
260 }
251 } 261 }
252 ui::tool_result(&result.summary(), aborted); 262 ui::tool_result(&result.summary(), aborted);
253 let message = json!({ 263 let message = json!({
@@ -270,12 +280,14 @@ pub fn run_turn(
270 eprintln!("agent686: {note}"); 280 eprintln!("agent686: {note}");
271 } 281 }
272 if let Some(outcome) = last { 282 if let Some(outcome) = last {
273 ui::status(steps, started.elapsed(), &outcome); 283 ui::status(steps, started.elapsed(), &outcome, &summary);
274 } 284 }
275 Ok(TurnReport { 285 Ok(TurnReport {
276 steps, 286 steps,
277 aborted, 287 aborted,
278 denied, 288 denied,
289 writes: summary.writes,
290 commands: summary.commands,
279 }) 291 })
280} 292}
281 293
diff --git a/src/main.rs b/src/main.rs
index 117973b..91d54da 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,4 +1,4 @@
1use std::io::{BufRead, Write}; 1use std::io::{BufRead, IsTerminal, Write};
2use std::path::PathBuf; 2use std::path::PathBuf;
3use std::time::SystemTime; 3use std::time::SystemTime;
4 4
@@ -31,6 +31,7 @@ OPTIONS:
31 --session <ID> resume a session, creating it if the id is new 31 --session <ID> resume a session, creating it if the id is new
32 -c, --continue resume the most recent session 32 -c, --continue resume the most recent session
33 --list list sessions and exit 33 --list list sessions and exit
34 --show [ID] print a transcript (most recent if no ID) and exit
34 --doctor check key, directories, provider and model, then exit 35 --doctor check key, directories, provider and model, then exit
35 --yolo approve every tool call without asking 36 --yolo approve every tool call without asking
36 -V, --version print the version and exit 37 -V, --version print the version and exit
@@ -44,6 +45,7 @@ ENVIRONMENT:
44 AGENT686_MODEL default model id 45 AGENT686_MODEL default model id
45 AGENT686_BASE_URL default provider base URL 46 AGENT686_BASE_URL default provider base URL
46 AGENT686_DATA where sessions live (default ~/.local/share/agent686) 47 AGENT686_DATA where sessions live (default ~/.local/share/agent686)
48 AGENT686_ALLOW_HOME permit --yolo in $HOME or /
47 NO_COLOR disable colour 49 NO_COLOR disable colour
48"; 50";
49 51
@@ -54,6 +56,7 @@ struct Args {
54 session: Option<String>, 56 session: Option<String>,
55 continue_last: bool, 57 continue_last: bool,
56 list: bool, 58 list: bool,
59 show: Option<Option<String>>,
57 doctor: bool, 60 doctor: bool,
58 yolo: bool, 61 yolo: bool,
59} 62}
@@ -77,11 +80,12 @@ fn parse_args() -> Result<Args, String> {
77 session: None, 80 session: None,
78 continue_last: false, 81 continue_last: false,
79 list: false, 82 list: false,
83 show: None,
80 doctor: false, 84 doctor: false,
81 yolo: false, 85 yolo: false,
82 }; 86 };
83 let mut words: Vec<String> = Vec::new(); 87 let mut words: Vec<String> = Vec::new();
84 let mut iter = std::env::args().skip(1); 88 let mut iter = std::env::args().skip(1).peekable();
85 let mut literal = false; 89 let mut literal = false;
86 90
87 while let Some(arg) = iter.next() { 91 while let Some(arg) = iter.next() {
@@ -98,6 +102,14 @@ fn parse_args() -> Result<Args, String> {
98 } 102 }
99 "-c" | "--continue" => args.continue_last = true, 103 "-c" | "--continue" => args.continue_last = true,
100 "--list" => args.list = true, 104 "--list" => args.list = true,
105 "--show" => {
106 // Optional value: an id, or nothing for the most recent session.
107 let id = match iter.peek() {
108 Some(next) if !next.starts_with('-') => iter.next(),
109 _ => None,
110 };
111 args.show = Some(id);
112 }
101 "--doctor" => args.doctor = true, 113 "--doctor" => args.doctor = true,
102 "--yolo" => args.yolo = true, 114 "--yolo" => args.yolo = true,
103 "-V" | "--version" => { 115 "-V" | "--version" => {
@@ -124,6 +136,9 @@ fn parse_args() -> Result<Args, String> {
124 if args.list && args.doctor { 136 if args.list && args.doctor {
125 return Err("--list and --doctor cannot be combined".into()); 137 return Err("--list and --doctor cannot be combined".into());
126 } 138 }
139 if args.show.is_some() && (args.list || args.doctor) {
140 return Err("--show cannot be combined with --list or --doctor".into());
141 }
127 if let Some(id) = &args.session { 142 if let Some(id) = &args.session {
128 validate_session_id(id)?; 143 validate_session_id(id)?;
129 } 144 }
@@ -155,6 +170,11 @@ fn validate_session_id(id: &str) -> Result<(), String> {
155fn run(args: Args) { 170fn run(args: Args) {
156 signal::install(); 171 signal::install();
157 172
173 if let Some(id) = args.show {
174 show_session(id);
175 return;
176 }
177
158 if args.list { 178 if args.list {
159 print_sessions(); 179 print_sessions();
160 return; 180 return;
@@ -185,6 +205,17 @@ fn run(args: Args) {
185 cfg.session = session.id.clone(); 205 cfg.session = session.id.clone();
186 206
187 warn_if_moved(&session); 207 warn_if_moved(&session);
208 if !session.version.is_empty() && session.version != env!("CARGO_PKG_VERSION") {
209 eprintln!(
210 "agent686: this session was written by {}; the prompt and tool schemas may \
211 differ, so the provider's cache will be repopulated",
212 session.version
213 );
214 }
215 if !session.model.is_empty() && session.model != cfg.model {
216 let _ = session.record_model(&cfg.model);
217 }
218 refuse_yolo_at_home(&cfg);
188 219
189 let mut approver = Approver::new(cfg.yolo); 220 let mut approver = Approver::new(cfg.yolo);
190 let watched = agent::agents_md(); 221 let watched = agent::agents_md();
@@ -430,3 +461,189 @@ fn ago(modified: SystemTime) -> String {
430 _ => format!("{}d", seconds / 86_400), 461 _ => format!("{}d", seconds / 86_400),
431 } 462 }
432} 463}
464
465/// `--yolo` with no approval at all in `$HOME` or `/` is how a transcript ends up
466/// overwriting `.bashrc` or deleting a checkout. Refuse it unless asked twice.
467fn refuse_yolo_at_home(cfg: &Config) {
468 if !cfg.yolo {
469 return;
470 }
471 if std::env::var_os("AGENT686_ALLOW_HOME").is_some() {
472 return;
473 }
474 let Ok(cwd) = std::env::current_dir() else {
475 return;
476 };
477 let home = std::env::var_os("HOME").map(PathBuf::from);
478 let at_home = home.as_deref() == Some(cwd.as_path());
479 let at_root = cwd.parent().is_none();
480 if at_home || at_root {
481 eprintln!(
482 "agent686: refusing --yolo in {} — the model can overwrite anything here. \
483 Run inside a project directory, or set AGENT686_ALLOW_HOME=1.",
484 cwd.display()
485 );
486 std::process::exit(2);
487 }
488}
489
490fn style(code: &str, text: &str, color: bool) -> String {
491 if color {
492 format!("\x1b[{code}m{text}\x1b[0m")
493 } else {
494 text.to_string()
495 }
496}
497
498fn first_lines(text: &str, max: usize) -> String {
499 let mut lines: Vec<String> = text
500 .lines()
501 .take(max)
502 .map(|line| crate::truncate_line(line, 160))
503 .collect();
504 let total = text.lines().count();
505 if total > max {
506 lines.push(format!("… {} more line(s)", total - max));
507 }
508 lines.join("\n ")
509}
510
511fn truncate_line(line: &str, max: usize) -> String {
512 agent686::provider::truncate(line, max)
513}
514
515/// Renders a transcript: what was said, what was asked, what came back. Reads
516/// the file without locking so it works while a session is open elsewhere.
517fn show_session(id: Option<String>) {
518 let id = match id.or_else(|| session::latest().ok().flatten()) {
519 Some(id) => id,
520 None => {
521 println!("no sessions");
522 return;
523 }
524 };
525 let path = session::sessions_dir().join(format!("{id}.jsonl"));
526 let text = match std::fs::read_to_string(&path) {
527 Ok(text) => text,
528 Err(error) => {
529 eprintln!("agent686: {}: {error}", path.display());
530 std::process::exit(1);
531 }
532 };
533
534 let color = std::io::stdout().is_terminal()
535 && std::env::var_os("NO_COLOR").is_none()
536 && std::env::var("TERM").map(|t| t != "dumb").unwrap_or(true);
537
538 let mut model = String::from("?");
539 let mut cwd = String::new();
540 let mut messages = 0usize;
541 let mut rendered = Vec::new();
542
543 for line in text.lines() {
544 let value: Value = match serde_json::from_str(line) {
545 Ok(value) => value,
546 Err(_) => continue,
547 };
548 match value.get("t").and_then(|t| t.as_str()) {
549 Some("header") => {
550 model = value
551 .get("model")
552 .and_then(|m| m.as_str())
553 .unwrap_or("?")
554 .to_string();
555 cwd = value
556 .get("cwd")
557 .and_then(|c| c.as_str())
558 .unwrap_or("")
559 .to_string();
560 }
561 Some("model") => {
562 if let Some(name) = value.get("model").and_then(|m| m.as_str()) {
563 rendered.push(style("2", &format!("— model switched to {name}"), color));
564 }
565 }
566 Some("msg") => {
567 messages += 1;
568 rendered.push(render_message(&value, color));
569 }
570 _ => {}
571 }
572 }
573
574 println!(
575 "{}",
576 style(
577 "1",
578 &format!("session {id} · {model} · {messages} messages"),
579 color
580 )
581 );
582 if !cwd.is_empty() {
583 println!("{}", style("2", &format!("started in {cwd}"), color));
584 }
585 println!("{}", style("2", &path.display().to_string(), color));
586 println!();
587 for block in rendered {
588 println!("{block}");
589 }
590}
591
592fn render_message(message: &Value, color: bool) -> String {
593 match message.get("role").and_then(|r| r.as_str()).unwrap_or("?") {
594 "user" => format!(
595 "{}\n{}\n",
596 style("1;33", "user", color),
597 message
598 .get("content")
599 .and_then(|c| c.as_str())
600 .unwrap_or("")
601 ),
602 "assistant" => {
603 let mut out = String::new();
604 if let Some(reasoning) = message.get("_reasoning").and_then(|r| r.as_str()) {
605 out.push_str(&style("2", reasoning, color));
606 out.push('\n');
607 }
608 if let Some(content) = message.get("content").and_then(|c| c.as_str()) {
609 out.push_str(content);
610 out.push('\n');
611 }
612 if let Some(calls) = message.get("tool_calls").and_then(|c| c.as_array()) {
613 for call in calls {
614 let name = call
615 .get("function")
616 .and_then(|f| f.get("name"))
617 .and_then(|n| n.as_str())
618 .unwrap_or("?");
619 let args = call
620 .get("function")
621 .and_then(|f| f.get("arguments"))
622 .and_then(|a| a.as_str())
623 .unwrap_or("");
624 out.push_str(&style("1;36", &format!(" ● {name}"), color));
625 out.push('\n');
626 out.push_str(&style(
627 "2",
628 &format!(" {}", truncate_line(args, 200)),
629 color,
630 ));
631 out.push('\n');
632 }
633 }
634 out
635 }
636 "tool" => format!(
637 "{}\n",
638 style(
639 "2",
640 &format!(
641 " └ {}",
642 first_lines(message.get("content").and_then(|c| c.as_str()).unwrap_or(""), 4)
643 ),
644 color
645 )
646 ),
647 other => format!("[{other}]\n"),
648 }
649}
diff --git a/src/session.rs b/src/session.rs
index 6416b56..d017eda 100644
--- a/src/session.rs
+++ b/src/session.rs
@@ -66,6 +66,8 @@ pub struct Session {
66 pub model: String, 66 pub model: String,
67 /// Directory the session was started in; the system prompt is frozen with it. 67 /// Directory the session was started in; the system prompt is frozen with it.
68 pub cwd: String, 68 pub cwd: String,
69 /// Harness version that created the session, for prefix-change warnings.
70 pub version: String,
69 path: PathBuf, 71 path: PathBuf,
70 file: File, 72 file: File,
71} 73}
@@ -107,6 +109,7 @@ impl Session {
107 "session": id, 109 "session": id,
108 "model": model, 110 "model": model,
109 "cwd": cwd, 111 "cwd": cwd,
112 "version": env!("CARGO_PKG_VERSION"),
110 "created": now_ms(), 113 "created": now_ms(),
111 "system": system, 114 "system": system,
112 }); 115 });
@@ -117,6 +120,7 @@ impl Session {
117 id, 120 id,
118 model: model.to_string(), 121 model: model.to_string(),
119 cwd, 122 cwd,
123 version: env!("CARGO_PKG_VERSION").to_string(),
120 path, 124 path,
121 file, 125 file,
122 }) 126 })
@@ -133,6 +137,7 @@ impl Session {
133 let mut system = Value::Null; 137 let mut system = Value::Null;
134 let mut session_id = id.to_string(); 138 let mut session_id = id.to_string();
135 let mut cwd = String::new(); 139 let mut cwd = String::new();
140 let mut version = String::new();
136 let mut messages = Vec::new(); 141 let mut messages = Vec::new();
137 142
138 for line in reader.lines() { 143 for line in reader.lines() {
@@ -159,6 +164,9 @@ impl Session {
159 if let Some(c) = value.get("cwd").and_then(|c| c.as_str()) { 164 if let Some(c) = value.get("cwd").and_then(|c| c.as_str()) {
160 cwd = c.to_string(); 165 cwd = c.to_string();
161 } 166 }
167 if let Some(v) = value.get("version").and_then(|v| v.as_str()) {
168 version = v.to_string();
169 }
162 } 170 }
163 Some("msg") => { 171 Some("msg") => {
164 let mut message = value.clone(); 172 let mut message = value.clone();
@@ -185,6 +193,7 @@ impl Session {
185 id: session_id, 193 id: session_id,
186 model, 194 model,
187 cwd, 195 cwd,
196 version,
188 path, 197 path,
189 file, 198 file,
190 }, 199 },
@@ -213,6 +222,14 @@ impl Session {
213 pub fn path(&self) -> &PathBuf { 222 pub fn path(&self) -> &PathBuf {
214 &self.path 223 &self.path
215 } 224 }
225
226 /// Records a model switch so `--list` shows what the last turn used. Appending
227 /// is legal; the header itself is never rewritten.
228 pub fn record_model(&mut self, model: &str) -> Result<(), String> {
229 let line = json!({ "t": "model", "model": model, "at": now_ms() });
230 writeln!(self.file, "{line}").map_err(|e| e.to_string())?;
231 self.file.flush().map_err(|e| e.to_string())
232 }
216} 233}
217 234
218pub fn exists(id: &str) -> bool { 235pub fn exists(id: &str) -> bool {
@@ -271,6 +288,11 @@ fn scan(path: &PathBuf) -> (String, usize) {
271 } 288 }
272 } 289 }
273 Some("msg") => messages += 1, 290 Some("msg") => messages += 1,
291 Some("model") => {
292 if let Some(name) = value.get("model").and_then(|m| m.as_str()) {
293 model = name.to_string();
294 }
295 }
274 _ => {} 296 _ => {}
275 } 297 }
276 } 298 }
diff --git a/src/ui.rs b/src/ui.rs
index 3148df9..2fdda1a 100644
--- a/src/ui.rs
+++ b/src/ui.rs
@@ -150,7 +150,14 @@ pub fn tool_result(summary: &str, aborted: bool) {
150 let _ = std::io::stdout().flush(); 150 let _ = std::io::stdout().flush();
151} 151}
152 152
153pub fn status(steps: usize, elapsed: Duration, outcome: &Outcome) { 153#[derive(Debug, Default, Clone, Copy)]
154pub struct Summary {
155 pub writes: usize,
156 pub commands: usize,
157 pub denied: usize,
158}
159
160pub fn status(steps: usize, elapsed: Duration, outcome: &Outcome, summary: &Summary) {
154 let mut parts = vec![ 161 let mut parts = vec![
155 if steps == 1 { 162 if steps == 1 {
156 "1 step".to_string() 163 "1 step".to_string()
@@ -159,6 +166,23 @@ pub fn status(steps: usize, elapsed: Duration, outcome: &Outcome) {
159 }, 166 },
160 format!("{:.1}s", elapsed.as_secs_f64()), 167 format!("{:.1}s", elapsed.as_secs_f64()),
161 ]; 168 ];
169 if summary.writes > 0 {
170 parts.push(format!(
171 "{} write{}",
172 summary.writes,
173 if summary.writes == 1 { "" } else { "s" }
174 ));
175 }
176 if summary.commands > 0 {
177 parts.push(format!(
178 "{} command{}",
179 summary.commands,
180 if summary.commands == 1 { "" } else { "s" }
181 ));
182 }
183 if summary.denied > 0 {
184 parts.push(format!("{} denied", summary.denied));
185 }
162 let (input, output) = outcome.tokens(); 186 let (input, output) = outcome.tokens();
163 if let (Some(i), Some(o)) = (input, output) { 187 if let (Some(i), Some(o)) = (input, output) {
164 parts.push(format!("{i} in · {o} out")); 188 parts.push(format!("{i} in · {o} out"));