From 14e56289391ea95b493c2a20c87f8d88047aa051 Mon Sep 17 00:00:00 2001 From: salmonik Date: Sun, 15 Nov 2026 17:16:08 +0100 Subject: 0.6.0: transcript viewer, turn summary, yolo floor, model/version records - --show renders a session without locking it - status line summarises writes, commands and denials per turn - sessions record harness version; model switches are appended and listed - --yolo refuses $HOME and / unless AGENT686_ALLOW_HOME=1 --- src/agent.rs | 16 ++++- src/main.rs | 221 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++- src/session.rs | 22 ++++++ src/ui.rs | 26 ++++++- 4 files changed, 280 insertions(+), 5 deletions(-) (limited to 'src') 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; use crate::provider::{self, Error, Outcome}; use crate::session::Session; use crate::tools::{self, Approval}; -use crate::ui::{self, Approver, Renderer}; +use crate::ui::{self, Approver, Renderer, Summary}; /// Frozen for the life of the session. Anything session-varying added here /// invalidates the provider's prompt cache, so keep it boring. @@ -128,6 +128,8 @@ pub struct TurnReport { pub steps: usize, pub aborted: bool, pub denied: usize, + pub writes: usize, + pub commands: usize, } pub enum ToolOutcome { @@ -188,6 +190,7 @@ pub fn run_turn( let mut last: Option = None; let mut aborted = false; let mut denied = 0usize; + let mut summary = Summary::default(); let mut truncated: Option = None; loop { @@ -248,6 +251,13 @@ pub fn run_turn( }; if result.denied() { denied += 1; + summary.denied += 1; + } else if !aborted { + match call.name.as_str() { + "write" | "edit" => summary.writes += 1, + "bash" => summary.commands += 1, + _ => {} + } } ui::tool_result(&result.summary(), aborted); let message = json!({ @@ -270,12 +280,14 @@ pub fn run_turn( eprintln!("agent686: {note}"); } if let Some(outcome) = last { - ui::status(steps, started.elapsed(), &outcome); + ui::status(steps, started.elapsed(), &outcome, &summary); } Ok(TurnReport { steps, aborted, denied, + writes: summary.writes, + commands: summary.commands, }) } 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 @@ -use std::io::{BufRead, Write}; +use std::io::{BufRead, IsTerminal, Write}; use std::path::PathBuf; use std::time::SystemTime; @@ -31,6 +31,7 @@ OPTIONS: --session resume a session, creating it if the id is new -c, --continue resume the most recent session --list list sessions and exit + --show [ID] print a transcript (most recent if no ID) and exit --doctor check key, directories, provider and model, then exit --yolo approve every tool call without asking -V, --version print the version and exit @@ -44,6 +45,7 @@ ENVIRONMENT: AGENT686_MODEL default model id AGENT686_BASE_URL default provider base URL AGENT686_DATA where sessions live (default ~/.local/share/agent686) + AGENT686_ALLOW_HOME permit --yolo in $HOME or / NO_COLOR disable colour "; @@ -54,6 +56,7 @@ struct Args { session: Option, continue_last: bool, list: bool, + show: Option>, doctor: bool, yolo: bool, } @@ -77,11 +80,12 @@ fn parse_args() -> Result { session: None, continue_last: false, list: false, + show: None, doctor: false, yolo: false, }; let mut words: Vec = Vec::new(); - let mut iter = std::env::args().skip(1); + let mut iter = std::env::args().skip(1).peekable(); let mut literal = false; while let Some(arg) = iter.next() { @@ -98,6 +102,14 @@ fn parse_args() -> Result { } "-c" | "--continue" => args.continue_last = true, "--list" => args.list = true, + "--show" => { + // Optional value: an id, or nothing for the most recent session. + let id = match iter.peek() { + Some(next) if !next.starts_with('-') => iter.next(), + _ => None, + }; + args.show = Some(id); + } "--doctor" => args.doctor = true, "--yolo" => args.yolo = true, "-V" | "--version" => { @@ -124,6 +136,9 @@ fn parse_args() -> Result { if args.list && args.doctor { return Err("--list and --doctor cannot be combined".into()); } + if args.show.is_some() && (args.list || args.doctor) { + return Err("--show cannot be combined with --list or --doctor".into()); + } if let Some(id) = &args.session { validate_session_id(id)?; } @@ -155,6 +170,11 @@ fn validate_session_id(id: &str) -> Result<(), String> { fn run(args: Args) { signal::install(); + if let Some(id) = args.show { + show_session(id); + return; + } + if args.list { print_sessions(); return; @@ -185,6 +205,17 @@ fn run(args: Args) { cfg.session = session.id.clone(); warn_if_moved(&session); + if !session.version.is_empty() && session.version != env!("CARGO_PKG_VERSION") { + eprintln!( + "agent686: this session was written by {}; the prompt and tool schemas may \ + differ, so the provider's cache will be repopulated", + session.version + ); + } + if !session.model.is_empty() && session.model != cfg.model { + let _ = session.record_model(&cfg.model); + } + refuse_yolo_at_home(&cfg); let mut approver = Approver::new(cfg.yolo); let watched = agent::agents_md(); @@ -430,3 +461,189 @@ fn ago(modified: SystemTime) -> String { _ => format!("{}d", seconds / 86_400), } } + +/// `--yolo` with no approval at all in `$HOME` or `/` is how a transcript ends up +/// overwriting `.bashrc` or deleting a checkout. Refuse it unless asked twice. +fn refuse_yolo_at_home(cfg: &Config) { + if !cfg.yolo { + return; + } + if std::env::var_os("AGENT686_ALLOW_HOME").is_some() { + return; + } + let Ok(cwd) = std::env::current_dir() else { + return; + }; + let home = std::env::var_os("HOME").map(PathBuf::from); + let at_home = home.as_deref() == Some(cwd.as_path()); + let at_root = cwd.parent().is_none(); + if at_home || at_root { + eprintln!( + "agent686: refusing --yolo in {} — the model can overwrite anything here. \ + Run inside a project directory, or set AGENT686_ALLOW_HOME=1.", + cwd.display() + ); + std::process::exit(2); + } +} + +fn style(code: &str, text: &str, color: bool) -> String { + if color { + format!("\x1b[{code}m{text}\x1b[0m") + } else { + text.to_string() + } +} + +fn first_lines(text: &str, max: usize) -> String { + let mut lines: Vec = text + .lines() + .take(max) + .map(|line| crate::truncate_line(line, 160)) + .collect(); + let total = text.lines().count(); + if total > max { + lines.push(format!("… {} more line(s)", total - max)); + } + lines.join("\n ") +} + +fn truncate_line(line: &str, max: usize) -> String { + agent686::provider::truncate(line, max) +} + +/// Renders a transcript: what was said, what was asked, what came back. Reads +/// the file without locking so it works while a session is open elsewhere. +fn show_session(id: Option) { + let id = match id.or_else(|| session::latest().ok().flatten()) { + Some(id) => id, + None => { + println!("no sessions"); + return; + } + }; + let path = session::sessions_dir().join(format!("{id}.jsonl")); + let text = match std::fs::read_to_string(&path) { + Ok(text) => text, + Err(error) => { + eprintln!("agent686: {}: {error}", path.display()); + std::process::exit(1); + } + }; + + let color = std::io::stdout().is_terminal() + && std::env::var_os("NO_COLOR").is_none() + && std::env::var("TERM").map(|t| t != "dumb").unwrap_or(true); + + let mut model = String::from("?"); + let mut cwd = String::new(); + let mut messages = 0usize; + let mut rendered = Vec::new(); + + for line in text.lines() { + let value: Value = match serde_json::from_str(line) { + Ok(value) => value, + Err(_) => continue, + }; + match value.get("t").and_then(|t| t.as_str()) { + Some("header") => { + model = value + .get("model") + .and_then(|m| m.as_str()) + .unwrap_or("?") + .to_string(); + cwd = value + .get("cwd") + .and_then(|c| c.as_str()) + .unwrap_or("") + .to_string(); + } + Some("model") => { + if let Some(name) = value.get("model").and_then(|m| m.as_str()) { + rendered.push(style("2", &format!("— model switched to {name}"), color)); + } + } + Some("msg") => { + messages += 1; + rendered.push(render_message(&value, color)); + } + _ => {} + } + } + + println!( + "{}", + style( + "1", + &format!("session {id} · {model} · {messages} messages"), + color + ) + ); + if !cwd.is_empty() { + println!("{}", style("2", &format!("started in {cwd}"), color)); + } + println!("{}", style("2", &path.display().to_string(), color)); + println!(); + for block in rendered { + println!("{block}"); + } +} + +fn render_message(message: &Value, color: bool) -> String { + match message.get("role").and_then(|r| r.as_str()).unwrap_or("?") { + "user" => format!( + "{}\n{}\n", + style("1;33", "user", color), + message + .get("content") + .and_then(|c| c.as_str()) + .unwrap_or("") + ), + "assistant" => { + let mut out = String::new(); + if let Some(reasoning) = message.get("_reasoning").and_then(|r| r.as_str()) { + out.push_str(&style("2", reasoning, color)); + out.push('\n'); + } + if let Some(content) = message.get("content").and_then(|c| c.as_str()) { + out.push_str(content); + out.push('\n'); + } + if let Some(calls) = message.get("tool_calls").and_then(|c| c.as_array()) { + for call in calls { + let name = call + .get("function") + .and_then(|f| f.get("name")) + .and_then(|n| n.as_str()) + .unwrap_or("?"); + let args = call + .get("function") + .and_then(|f| f.get("arguments")) + .and_then(|a| a.as_str()) + .unwrap_or(""); + out.push_str(&style("1;36", &format!(" ● {name}"), color)); + out.push('\n'); + out.push_str(&style( + "2", + &format!(" {}", truncate_line(args, 200)), + color, + )); + out.push('\n'); + } + } + out + } + "tool" => format!( + "{}\n", + style( + "2", + &format!( + " └ {}", + first_lines(message.get("content").and_then(|c| c.as_str()).unwrap_or(""), 4) + ), + color + ) + ), + other => format!("[{other}]\n"), + } +} 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 { pub model: String, /// Directory the session was started in; the system prompt is frozen with it. pub cwd: String, + /// Harness version that created the session, for prefix-change warnings. + pub version: String, path: PathBuf, file: File, } @@ -107,6 +109,7 @@ impl Session { "session": id, "model": model, "cwd": cwd, + "version": env!("CARGO_PKG_VERSION"), "created": now_ms(), "system": system, }); @@ -117,6 +120,7 @@ impl Session { id, model: model.to_string(), cwd, + version: env!("CARGO_PKG_VERSION").to_string(), path, file, }) @@ -133,6 +137,7 @@ impl Session { let mut system = Value::Null; let mut session_id = id.to_string(); let mut cwd = String::new(); + let mut version = String::new(); let mut messages = Vec::new(); for line in reader.lines() { @@ -159,6 +164,9 @@ impl Session { if let Some(c) = value.get("cwd").and_then(|c| c.as_str()) { cwd = c.to_string(); } + if let Some(v) = value.get("version").and_then(|v| v.as_str()) { + version = v.to_string(); + } } Some("msg") => { let mut message = value.clone(); @@ -185,6 +193,7 @@ impl Session { id: session_id, model, cwd, + version, path, file, }, @@ -213,6 +222,14 @@ impl Session { pub fn path(&self) -> &PathBuf { &self.path } + + /// Records a model switch so `--list` shows what the last turn used. Appending + /// is legal; the header itself is never rewritten. + pub fn record_model(&mut self, model: &str) -> Result<(), String> { + let line = json!({ "t": "model", "model": model, "at": now_ms() }); + writeln!(self.file, "{line}").map_err(|e| e.to_string())?; + self.file.flush().map_err(|e| e.to_string()) + } } pub fn exists(id: &str) -> bool { @@ -271,6 +288,11 @@ fn scan(path: &PathBuf) -> (String, usize) { } } Some("msg") => messages += 1, + Some("model") => { + if let Some(name) = value.get("model").and_then(|m| m.as_str()) { + model = name.to_string(); + } + } _ => {} } } 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) { let _ = std::io::stdout().flush(); } -pub fn status(steps: usize, elapsed: Duration, outcome: &Outcome) { +#[derive(Debug, Default, Clone, Copy)] +pub struct Summary { + pub writes: usize, + pub commands: usize, + pub denied: usize, +} + +pub fn status(steps: usize, elapsed: Duration, outcome: &Outcome, summary: &Summary) { let mut parts = vec![ if steps == 1 { "1 step".to_string() @@ -159,6 +166,23 @@ pub fn status(steps: usize, elapsed: Duration, outcome: &Outcome) { }, format!("{:.1}s", elapsed.as_secs_f64()), ]; + if summary.writes > 0 { + parts.push(format!( + "{} write{}", + summary.writes, + if summary.writes == 1 { "" } else { "s" } + )); + } + if summary.commands > 0 { + parts.push(format!( + "{} command{}", + summary.commands, + if summary.commands == 1 { "" } else { "s" } + )); + } + if summary.denied > 0 { + parts.push(format!("{} denied", summary.denied)); + } let (input, output) = outcome.tokens(); if let (Some(i), Some(o)) = (input, output) { parts.push(format!("{i} in · {o} out")); -- cgit v1.2.3