diff options
| -rw-r--r-- | CHANGELOG.md | 16 | ||||
| -rw-r--r-- | Cargo.lock | 2 | ||||
| -rw-r--r-- | Cargo.toml | 2 | ||||
| -rw-r--r-- | README.md | 9 | ||||
| -rw-r--r-- | docs/KNOWN-ISSUES.md | 72 | ||||
| -rw-r--r-- | src/agent.rs | 16 | ||||
| -rw-r--r-- | src/main.rs | 221 | ||||
| -rw-r--r-- | src/session.rs | 22 | ||||
| -rw-r--r-- | src/ui.rs | 26 | ||||
| -rw-r--r-- | tests/cli.rs | 69 | ||||
| -rw-r--r-- | tests/loop.rs | 2 | ||||
| -rw-r--r-- | tests/sessions.rs | 15 |
12 files changed, 420 insertions, 52 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d63d98..1fd94b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md | |||
| @@ -7,6 +7,22 @@ break the interface, **PATCH** for bug fixes. | |||
| 7 | file, and the tool schemas the model sees. Anything a script or a resumed session | 7 | file, and the tool schemas the model sees. Anything a script or a resumed session |
| 8 | could depend on counts as API. | 8 | could depend on counts as API. |
| 9 | 9 | ||
| 10 | ## 0.6.0 | ||
| 11 | |||
| 12 | ### Added | ||
| 13 | - `--show [ID]`: renders a transcript — user turn, reasoning, assistant text, | ||
| 14 | every tool call with its arguments, and each result — instead of requiring | ||
| 15 | `cat` on the JSONL. Reads without locking, so it works while a session is open. | ||
| 16 | - The status line now summarises the turn: writes, commands and denials. | ||
| 17 | - Sessions record the harness version that wrote them and the model in use; a | ||
| 18 | model switch appends a record so `--list` shows the current model rather than | ||
| 19 | the one the session started with. Resuming with a different binary warns that | ||
| 20 | the prompt and tool schemas may differ. | ||
| 21 | |||
| 22 | ### Changed | ||
| 23 | - `--yolo` is refused in `$HOME` and `/` unless `AGENT686_ALLOW_HOME=1` is set. | ||
| 24 | The documented undo is git, and neither of those is a checkout. | ||
| 25 | |||
| 10 | ## 0.5.3 | 26 | ## 0.5.3 |
| 11 | 27 | ||
| 12 | ### Fixed | 28 | ### Fixed |
| @@ -10,7 +10,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" | |||
| 10 | 10 | ||
| 11 | [[package]] | 11 | [[package]] |
| 12 | name = "agent686" | 12 | name = "agent686" |
| 13 | version = "0.5.3" | 13 | version = "0.6.0" |
| 14 | dependencies = [ | 14 | dependencies = [ |
| 15 | "crossterm", | 15 | "crossterm", |
| 16 | "libc", | 16 | "libc", |
| @@ -1,6 +1,6 @@ | |||
| 1 | [package] | 1 | [package] |
| 2 | name = "agent686" | 2 | name = "agent686" |
| 3 | version = "0.5.3" | 3 | version = "0.6.0" |
| 4 | edition = "2021" | 4 | edition = "2021" |
| 5 | description = "A small coding agent for a 32-bit Debian box" | 5 | description = "A small coding agent for a 32-bit Debian box" |
| 6 | publish = false | 6 | publish = false |
| @@ -30,6 +30,8 @@ export OPENCODE_API_KEY=... # or write it to ~/.config/agent686/key | |||
| 30 | ./agent686 -c # continue the most recent session | 30 | ./agent686 -c # continue the most recent session |
| 31 | ./agent686 --session <id> # resume it, or create it if the id is new | 31 | ./agent686 --session <id> # resume it, or create it if the id is new |
| 32 | ./agent686 --list # id, model, message count, age | 32 | ./agent686 --list # id, model, message count, age |
| 33 | ./agent686 --show [id] # render a transcript | ||
| 34 | ./agent686 --doctor # key, dirs, provider, model | ||
| 33 | ./agent686 --yolo "..." # approve every tool call | 35 | ./agent686 --yolo "..." # approve every tool call |
| 34 | ``` | 36 | ``` |
| 35 | 37 | ||
| @@ -52,13 +54,14 @@ supported), `bash` (fresh shell per call, own process group, 120 s timeout, | |||
| 52 | `glob` (`*`, `?`, `**`, follows file symlinks). | 54 | `glob` (`*`, `?`, `**`, follows file symlinks). |
| 53 | 55 | ||
| 54 | Reads never prompt. The first `write`/`edit` of a session shows a diff and asks; | 56 | Reads never prompt. The first `write`/`edit` of a session shows a diff and asks; |
| 55 | answering `a` allows the rest of the session. Every `bash` call asks, because | 57 | answering `a` allows the rest of the process. Every `bash` call asks, because |
| 56 | that is where `rm -rf` lives. | 58 | that is where `rm -rf` lives. `--yolo` skips both, and is refused in `$HOME` and |
| 59 | `/` unless `AGENT686_ALLOW_HOME=1`. | ||
| 57 | 60 | ||
| 58 | ## Tests | 61 | ## Tests |
| 59 | 62 | ||
| 60 | ```sh | 63 | ```sh |
| 61 | cargo test # 64 tests, no network | 64 | cargo test # 75 tests, no network |
| 62 | python3 scripts/mock-provider.py & # canned SSE provider | 65 | python3 scripts/mock-provider.py & # canned SSE provider |
| 63 | docker run --rm --platform linux/386 \ | 66 | docker run --rm --platform linux/386 \ |
| 64 | -v "$PWD/target/i686-unknown-linux-gnu/release:/b:ro" debian:12 /b/agent686 --version | 67 | -v "$PWD/target/i686-unknown-linux-gnu/release:/b:ro" debian:12 /b/agent686 --version |
diff --git a/docs/KNOWN-ISSUES.md b/docs/KNOWN-ISSUES.md index 44d9f07..79ce26c 100644 --- a/docs/KNOWN-ISSUES.md +++ b/docs/KNOWN-ISSUES.md | |||
| @@ -3,66 +3,54 @@ | |||
| 3 | Understood, deliberately not fixed. Each one has a reason, and a note on what | 3 | Understood, deliberately not fixed. Each one has a reason, and a note on what |
| 4 | would change the decision. | 4 | would change the decision. |
| 5 | 5 | ||
| 6 | ## Concurrent sessions can interleave | ||
| 7 | |||
| 8 | Two processes appending to the same session file will interleave messages and | ||
| 9 | corrupt the conversation, permanently, because history is never rewritten. | ||
| 10 | `flock(LOCK_EX | LOCK_NB)` on the session fd at open would refuse the second | ||
| 11 | process. Not done yet because the failure needs deliberately resuming the same | ||
| 12 | id in two shells, and the fix is easy to add later. If it ever happens once, | ||
| 13 | add the lock. | ||
| 14 | |||
| 15 | ## `--yolo` has no floor | ||
| 16 | |||
| 17 | `--yolo` approves everything, including in `$HOME` or `/`. There is no check | ||
| 18 | that the directory is a git repository, so the documented undo does not exist in | ||
| 19 | some of the places it will run. Refusing `--yolo` outside a repository (or in | ||
| 20 | `$HOME`) would be a small change; it is deferred because the acceptance test runs | ||
| 21 | in an empty temp directory. | ||
| 22 | |||
| 23 | ## `--list` reads every transcript | 6 | ## `--list` reads every transcript |
| 24 | 7 | ||
| 25 | Listing costs O(total bytes of all sessions), because it parses each header and | 8 | Listing costs O(total bytes of all sessions), because it parses each header and |
| 26 | counts messages. At current sizes this is milliseconds; a 200 MB session file | 9 | counts messages. At current sizes this is milliseconds; a 200 MB session file |
| 27 | makes it visibly slow. An index or a `--json` format would fix it. | 10 | makes it visibly slow. An index or a `--json` format would fix it. |
| 28 | 11 | ||
| 29 | ## `edit` loads the whole file | 12 | ## `edit` still holds the file in memory |
| 30 | 13 | ||
| 31 | `edit` reads the file, matches, and writes it back through a temporary file. On | 14 | It now refuses files over 64 MiB and files that are not valid UTF-8, with a |
| 32 | the 32-bit target a file near the address-space limit fails with an out-of-memory | 15 | message pointing at `bash`. Anything under that is read, spliced and written |
| 33 | error rather than a clean refusal. A >32 MB file should be rejected up front with | 16 | through a temporary file, so the peak is roughly twice the file size. On a 3 GB |
| 34 | "too large for edit; use write". | 17 | address space that is fine; the refusal is the guard. |
| 35 | 18 | ||
| 36 | ## Editor width is approximate | 19 | ## `--doctor` fails on an unlisted model |
| 37 | 20 | ||
| 38 | The line editor counts one column per character, so wide (CJK) characters, | 21 | If `GET /models` does not list the model id you use (some gateways only list a |
| 39 | combining marks and raw tabs (from a paste) mis-place the caret. The width is | 22 | subset), doctor exits 1 even though a turn would work. `--doctor --probe`, which |
| 40 | read once per prompt, so a resize mid-edit mis-renders. | 23 | would send a one-token completion, is not implemented; that is what actually |
| 24 | matters. | ||
| 41 | 25 | ||
| 42 | ## No transcript viewer | 26 | ## Retry budget is fixed |
| 43 | 27 | ||
| 44 | Reasoning is stored beside each assistant message for humans, but the only way to | 28 | Four attempts, 1 s / 2 s / 4 s, no jitter, no per-status policy. A 429 with a long |
| 45 | read it is `cat` on the JSONL. A `--show <id>` renderer would make auditing a | 29 | reset window will still fail after ~7 s. |
| 46 | `--yolo` run practical. | ||
| 47 | 30 | ||
| 48 | ## Approval state is per process | 31 | ## Approval state is per process |
| 49 | 32 | ||
| 50 | Restarting the harness re-prompts for the first edit even when resuming a | 33 | Restarting the harness re-prompts for the first edit even when resuming a |
| 51 | session. That is intentional (see CONTEXT.md), but it is worth knowing. | 34 | session. Intentional (see CONTEXT.md), but worth knowing. |
| 52 | 35 | ||
| 53 | ## `--doctor` fails on an unlisted model | 36 | ## `--yolo` is only floored at the obvious places |
| 54 | 37 | ||
| 55 | If `GET /models` does not list the model id you use (some gateways only list a | 38 | It is refused in `$HOME` and `/`, but a model can still write anywhere by absolute |
| 56 | subset), doctor exits 1 even though a turn would work. `--doctor --probe` sending | 39 | path once a turn starts, and `bash` can change directory. The floor is a speed |
| 57 | a one-token completion would test what actually matters. | 40 | bump, not a sandbox; `bash` has no sandbox by design. |
| 58 | 41 | ||
| 59 | ## Retry budget is fixed | 42 | ## No machine-readable output |
| 43 | |||
| 44 | `--list`, `--doctor` and `--show` print for humans. A `--json` shape would let | ||
| 45 | scripts consume them. | ||
| 46 | |||
| 47 | ## Editor gaps | ||
| 60 | 48 | ||
| 61 | Four attempts, 1 s / 2 s / 4 s, no jitter, no per-status policy. A 429 for a | 49 | Wide characters, combining marks and tabs are now measured correctly, and a |
| 62 | model with a long reset window will still fail after ~7 s. | 50 | resize starts a fresh prompt line instead of erasing output. There is still no |
| 51 | Ctrl-L redraw and no Ctrl-Z suspend. | ||
| 63 | 52 | ||
| 64 | ## No per-turn summary | 53 | ## No session garbage collection |
| 65 | 54 | ||
| 66 | The status line reports steps, time, tokens and allowance, but not what changed: | 55 | A failed first turn leaves a session file that `--list` shows forever. Deleting |
| 67 | no "3 files written, 5 commands run, 1 denied". For a `--yolo` run that is the | 56 | files under `~/.local/share/agent686/sessions` is safe; nothing else indexes them. |
| 68 | summary you actually want. | ||
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; | |||
| 9 | use crate::provider::{self, Error, Outcome}; | 9 | use crate::provider::{self, Error, Outcome}; |
| 10 | use crate::session::Session; | 10 | use crate::session::Session; |
| 11 | use crate::tools::{self, Approval}; | 11 | use crate::tools::{self, Approval}; |
| 12 | use crate::ui::{self, Approver, Renderer}; | 12 | use 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 | ||
| 133 | pub enum ToolOutcome { | 135 | pub 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 @@ | |||
| 1 | use std::io::{BufRead, Write}; | 1 | use std::io::{BufRead, IsTerminal, Write}; |
| 2 | use std::path::PathBuf; | 2 | use std::path::PathBuf; |
| 3 | use std::time::SystemTime; | 3 | use 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> { | |||
| 155 | fn run(args: Args) { | 170 | fn 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. | ||
| 467 | fn 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 | |||
| 490 | fn 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 | |||
| 498 | fn 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 | |||
| 511 | fn 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. | ||
| 517 | fn 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 | |||
| 592 | fn 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 | ||
| 218 | pub fn exists(id: &str) -> bool { | 235 | pub 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 | } |
| @@ -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 | ||
| 153 | pub fn status(steps: usize, elapsed: Duration, outcome: &Outcome) { | 153 | #[derive(Debug, Default, Clone, Copy)] |
| 154 | pub struct Summary { | ||
| 155 | pub writes: usize, | ||
| 156 | pub commands: usize, | ||
| 157 | pub denied: usize, | ||
| 158 | } | ||
| 159 | |||
| 160 | pub 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")); |
diff --git a/tests/cli.rs b/tests/cli.rs index 04fd637..6c041fb 100644 --- a/tests/cli.rs +++ b/tests/cli.rs | |||
| @@ -76,3 +76,72 @@ fn unknown_flags_go_to_stderr_with_usage() { | |||
| 76 | assert!(stderr.contains("unknown flag"), "{stderr}"); | 76 | assert!(stderr.contains("unknown flag"), "{stderr}"); |
| 77 | assert!(stderr.contains("USAGE"), "{stderr}"); | 77 | assert!(stderr.contains("USAGE"), "{stderr}"); |
| 78 | } | 78 | } |
| 79 | |||
| 80 | #[test] | ||
| 81 | fn yolo_is_refused_in_the_home_directory() { | ||
| 82 | let home = temp_home("yolo"); | ||
| 83 | let output = agent() | ||
| 84 | .current_dir(&home) | ||
| 85 | .env("HOME", &home) | ||
| 86 | .env("OPENCODE_API_KEY", "test") | ||
| 87 | .arg("--yolo") | ||
| 88 | .stdin(std::process::Stdio::null()) | ||
| 89 | .output() | ||
| 90 | .unwrap(); | ||
| 91 | |||
| 92 | assert_eq!(output.status.code(), Some(2), "{output:?}"); | ||
| 93 | let stderr = String::from_utf8_lossy(&output.stderr); | ||
| 94 | assert!(stderr.contains("refusing --yolo"), "{stderr}"); | ||
| 95 | assert!(stderr.contains("AGENT686_ALLOW_HOME"), "{stderr}"); | ||
| 96 | } | ||
| 97 | |||
| 98 | #[test] | ||
| 99 | fn yolo_in_home_can_be_forced() { | ||
| 100 | let home = temp_home("yolo-force"); | ||
| 101 | let output = agent() | ||
| 102 | .current_dir(&home) | ||
| 103 | .env("HOME", &home) | ||
| 104 | .env("OPENCODE_API_KEY", "test") | ||
| 105 | .env("AGENT686_ALLOW_HOME", "1") | ||
| 106 | .args(["--yolo", "--session", "forced"]) | ||
| 107 | .stdin(std::process::Stdio::null()) | ||
| 108 | .output() | ||
| 109 | .unwrap(); | ||
| 110 | |||
| 111 | assert_eq!(output.status.code(), Some(0), "{output:?}"); | ||
| 112 | } | ||
| 113 | |||
| 114 | #[test] | ||
| 115 | fn show_renders_a_transcript() { | ||
| 116 | use serde_json::json; | ||
| 117 | |||
| 118 | let home = temp_home("show"); | ||
| 119 | let sessions = home.join(".local/share/agent686/sessions"); | ||
| 120 | fs::create_dir_all(&sessions).unwrap(); | ||
| 121 | |||
| 122 | let lines = [ | ||
| 123 | json!({"t":"header","session":"demo","model":"m","cwd":"/tmp","version":"0.0.0", | ||
| 124 | "system":{"role":"system","content":"sys"}}), | ||
| 125 | json!({"t":"msg","role":"user","content":"do the thing"}), | ||
| 126 | json!({"t":"msg","role":"assistant","content":"on it","_reasoning":"thinking about it", | ||
| 127 | "tool_calls":[{"id":"c1","type":"function", | ||
| 128 | "function":{"name":"read","arguments":"{\"path\":\"a\"}"}}]}), | ||
| 129 | json!({"t":"msg","role":"tool","tool_call_id":"c1","content":"line one\nline two"}), | ||
| 130 | ]; | ||
| 131 | let body: String = lines.iter().map(|line| format!("{line}\n")).collect(); | ||
| 132 | fs::write(sessions.join("demo.jsonl"), body).unwrap(); | ||
| 133 | |||
| 134 | let output = agent() | ||
| 135 | .env("HOME", &home) | ||
| 136 | .args(["--show", "demo"]) | ||
| 137 | .output() | ||
| 138 | .unwrap(); | ||
| 139 | |||
| 140 | assert!(output.status.success(), "{output:?}"); | ||
| 141 | let stdout = String::from_utf8_lossy(&output.stdout); | ||
| 142 | assert!(stdout.contains("do the thing"), "{stdout}"); | ||
| 143 | assert!(stdout.contains("● read"), "{stdout}"); | ||
| 144 | assert!(stdout.contains("line one"), "{stdout}"); | ||
| 145 | assert!(stdout.contains("on it"), "{stdout}"); | ||
| 146 | assert!(stdout.contains("thinking about it"), "{stdout}"); | ||
| 147 | } | ||
diff --git a/tests/loop.rs b/tests/loop.rs index d6df43c..b7e56f9 100644 --- a/tests/loop.rs +++ b/tests/loop.rs | |||
| @@ -260,6 +260,8 @@ fn aborting_between_tool_calls_answers_every_call() { | |||
| 260 | .expect("an abort is not an error"); | 260 | .expect("an abort is not an error"); |
| 261 | 261 | ||
| 262 | assert!(report.aborted); | 262 | assert!(report.aborted); |
| 263 | assert_eq!(report.writes, 0, "aborted calls must not count as writes"); | ||
| 264 | assert_eq!(report.commands, 1); | ||
| 263 | 265 | ||
| 264 | // Every announced tool call must have exactly one result, or the provider | 266 | // Every announced tool call must have exactly one result, or the provider |
| 265 | // rejects the session forever and the transcript cannot be rewritten. | 267 | // rejects the session forever and the transcript cannot be rewritten. |
diff --git a/tests/sessions.rs b/tests/sessions.rs index f21be24..1d40f64 100644 --- a/tests/sessions.rs +++ b/tests/sessions.rs | |||
| @@ -95,3 +95,18 @@ fn a_session_cannot_be_open_twice() { | |||
| 95 | drop(first); | 95 | drop(first); |
| 96 | Session::open("locked").expect("after the first handle closes it is available"); | 96 | Session::open("locked").expect("after the first handle closes it is available"); |
| 97 | } | 97 | } |
| 98 | |||
| 99 | #[test] | ||
| 100 | fn listing_reports_the_model_in_use_after_a_switch() { | ||
| 101 | let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner()); | ||
| 102 | let dir = temp_dir("model-switch"); | ||
| 103 | std::env::set_var("AGENT686_DATA", &dir); | ||
| 104 | |||
| 105 | let system = json!({ "role": "system", "content": "x" }); | ||
| 106 | let mut session = Session::create_as("switch".into(), "model-a", &system).unwrap(); | ||
| 107 | session.record_model("model-b").unwrap(); | ||
| 108 | |||
| 109 | let listed = session::list().unwrap(); | ||
| 110 | assert_eq!(listed.len(), 1); | ||
| 111 | assert_eq!(listed[0].model, "model-b"); | ||
| 112 | } | ||
