From d48aa4f0bce28159b6c5ee6bd0085a7f5a82e962 Mon Sep 17 00:00:00 2001 From: salmonik Date: Sun, 15 Nov 2026 15:43:07 +0100 Subject: 0.5.0: visible step counter, one client per turn, docs corrected Also fixes a 32-bit-only rlim_t mismatch found by building the target. --- CHANGELOG.md | 14 ++++++++++ CONTEXT.md | 4 ++- Cargo.lock | 2 +- Cargo.toml | 2 +- README.md | 23 +++++++++++----- docs/KNOWN-ISSUES.md | 68 +++++++++++++++++++++++++++++++++++++++++++++++ docs/PLAN.md | 75 ++++++++++++++++++++++++++++++---------------------- src/agent.rs | 15 ++++++++--- src/provider.rs | 31 ++++++++++++++++------ src/tools/shell.rs | 5 ++-- src/ui.rs | 8 ++++-- 11 files changed, 191 insertions(+), 56 deletions(-) create mode 100644 docs/KNOWN-ISSUES.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c00ccb..6340520 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,20 @@ break the interface, **PATCH** for bug fixes. file, and the tool schemas the model sees. Anything a script or a resumed session could depend on counts as API. +## 0.5.0 + +### Added +- The step number is printed on every tool line (`● [3] bash …`), so the progress + of a long turn is visible while it runs rather than only at the end. +- `docs/KNOWN-ISSUES.md` records the defects found in review that are understood + and deliberately deferred. + +### Changed +- One HTTP client per turn instead of one per step, avoiding a TLS handshake on + every request. +- Documentation corrected where it had drifted: binary size, test count, `grep` + semantics, input handling, instruction scope, and the settled API questions. + ## 0.4.5 ### Fixed diff --git a/CONTEXT.md b/CONTEXT.md index e48cb1a..a6b0d7a 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -27,4 +27,6 @@ tool call that fails, is denied, or produces no output is still a completed tool call; its outcome is returned to the model as a result, not raised as an error. **Approval** — the human's permission for a tool call to run. An approval is -scoped to a session, not to a turn: once granted, it holds until the session ends. +scoped to the process running the session, not to a turn: once granted, it holds +for the rest of that process. A new process asks again, even when the session is +resumed, because the human at the keyboard is not assumed to be the same one. diff --git a/Cargo.lock b/Cargo.lock index 2e60859..ea416df 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10,7 +10,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "agent686" -version = "0.4.4" +version = "0.5.0" dependencies = [ "crossterm", "libc", diff --git a/Cargo.toml b/Cargo.toml index a11845b..ea03c5e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "agent686" -version = "0.4.5" +version = "0.5.0" edition = "2021" description = "A small coding agent for a 32-bit Debian box" publish = false diff --git a/README.md b/README.md index c44bdec..4530686 100644 --- a/README.md +++ b/README.md @@ -6,8 +6,9 @@ Built because the existing harnesses are TypeScript bundles that need a modern CPU, and the target here is a Debian 12 i386 machine with 2 cores and 4 GB. ``` -2.0 MB ELF 32-bit LSB pie, Intel i386 +3.5 MiB ELF 32-bit LSB pie, Intel i386 GLIBC_2.34 required (target has 2.36) +startup ~0.8 ms ``` ## Build @@ -44,9 +45,11 @@ honoured); a 429 that survives them explains itself instead of dumping JSON. ## Tools -`read` (numbered lines), `write` (never creates directories), `edit` (exact -match, must be unique), `bash` (fresh shell per call, 120 s timeout, capped -output), `grep` (literal, recursive), `glob` (`*`, `?`, `**`). +`read` (numbered lines, streamed, regular files only), `write` (atomic, never +creates directories), `edit` (exact match that must be unique; CRLF files +supported), `bash` (fresh shell per call, own process group, 120 s timeout, +64 MiB output limit), `grep` (regular expression; `fixed: true` for literals), +`glob` (`*`, `?`, `**`, follows file symlinks). Reads never prompt. The first `write`/`edit` of a session shows a diff and asks; answering `a` allows the rest of the session. Every `bash` call asks, because @@ -55,9 +58,10 @@ that is where `rm -rf` lives. ## Tests ```sh -cargo test # 29 tests, no network +cargo test # 64 tests, no network python3 scripts/mock-provider.py & # canned SSE provider -docker run --rm --platform linux/386 debian:12 /b/agent686 # target-shaped gate +docker run --rm --platform linux/386 \ + -v "$PWD/target/i686-unknown-linux-gnu/release:/b:ro" debian:12 /b/agent686 --version ``` `tests/sse.rs` feeds the stream one byte at a time, so splits inside lines and @@ -68,7 +72,12 @@ executed, recorded, and that a denial is returned to the model as data. MAJOR for API-breaking changes, MINOR for features that do not break the interface, PATCH for bug fixes. The interface is the CLI flags, the session file -format, the config file, and the tool schemas. See [CHANGELOG.md](CHANGELOG.md). +format, the config file, and the tool schemas. + +While the major version is 0, interface changes ride on MINOR and are called out +explicitly, because there is no stability promise to break yet. The `grep` +change in 0.4.0 (literal to regex) is the example. See +[CHANGELOG.md](CHANGELOG.md) and [docs/KNOWN-ISSUES.md](docs/KNOWN-ISSUES.md). ## Design notes diff --git a/docs/KNOWN-ISSUES.md b/docs/KNOWN-ISSUES.md new file mode 100644 index 0000000..44d9f07 --- /dev/null +++ b/docs/KNOWN-ISSUES.md @@ -0,0 +1,68 @@ +# Known issues + +Understood, deliberately not fixed. Each one has a reason, and a note on what +would change the decision. + +## Concurrent sessions can interleave + +Two processes appending to the same session file will interleave messages and +corrupt the conversation, permanently, because history is never rewritten. +`flock(LOCK_EX | LOCK_NB)` on the session fd at open would refuse the second +process. Not done yet because the failure needs deliberately resuming the same +id in two shells, and the fix is easy to add later. If it ever happens once, +add the lock. + +## `--yolo` has no floor + +`--yolo` approves everything, including in `$HOME` or `/`. There is no check +that the directory is a git repository, so the documented undo does not exist in +some of the places it will run. Refusing `--yolo` outside a repository (or in +`$HOME`) would be a small change; it is deferred because the acceptance test runs +in an empty temp directory. + +## `--list` reads every transcript + +Listing costs O(total bytes of all sessions), because it parses each header and +counts messages. At current sizes this is milliseconds; a 200 MB session file +makes it visibly slow. An index or a `--json` format would fix it. + +## `edit` loads the whole file + +`edit` reads the file, matches, and writes it back through a temporary file. On +the 32-bit target a file near the address-space limit fails with an out-of-memory +error rather than a clean refusal. A >32 MB file should be rejected up front with +"too large for edit; use write". + +## Editor width is approximate + +The line editor counts one column per character, so wide (CJK) characters, +combining marks and raw tabs (from a paste) mis-place the caret. The width is +read once per prompt, so a resize mid-edit mis-renders. + +## No transcript viewer + +Reasoning is stored beside each assistant message for humans, but the only way to +read it is `cat` on the JSONL. A `--show ` renderer would make auditing a +`--yolo` run practical. + +## Approval state is per process + +Restarting the harness re-prompts for the first edit even when resuming a +session. That is intentional (see CONTEXT.md), but it is worth knowing. + +## `--doctor` fails on an unlisted model + +If `GET /models` does not list the model id you use (some gateways only list a +subset), doctor exits 1 even though a turn would work. `--doctor --probe` sending +a one-token completion would test what actually matters. + +## Retry budget is fixed + +Four attempts, 1 s / 2 s / 4 s, no jitter, no per-status policy. A 429 for a +model with a long reset window will still fail after ~7 s. + +## No per-turn summary + +The status line reports steps, time, tokens and allowance, but not what changed: +no "3 files written, 5 commands run, 1 denied". For a `--yolo` run that is the +summary you actually want. diff --git a/docs/PLAN.md b/docs/PLAN.md index 9be54fa..f22b230 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -31,17 +31,23 @@ line-mode, six tools. Built for understanding, not parity with anything. unless `--yolo`. Prompts happen after the stream ends, never mid-token. - **Turn/step.** A turn ends when the model answers with no tool calls, on user abort, or on a non-retryable provider error. **No step cap** — the brake is the - step counter on the status line and Ctrl-C. + step number printed on every tool line, the allowance in the status line, and + Ctrl-C. - **Tool errors are data.** Failures, non-zero exits, and denials are returned to the model as results. Only transport/auth/process failures end a turn. - **Sessions.** Append-only JSONL of wire messages (see ADR 0002). No compaction, no truncation, no summarisation. Overflow is the provider's 400. -- **Prompt.** Snapshot at session start: fixed system prompt, a 3-line - environment block (cwd, platform, git branch), and `AGENTS.md` from cwd up to - the git root. Frozen for the session; mtime change prints a notice only. -- **UI.** Line-mode. ANSI only when stdout is a TTY. Plain `read_line` plus - `/paste` (reads until a lone `.` or EOF). No alt-screen, no raw mode, no - history, no markdown rendering, no syntax highlighting. +- **Prompt.** Snapshot at session start: fixed system prompt, one environment + line (cwd, platform, arch, git branch), and `AGENTS.md` from cwd up to the git + root — never above it, and only the working directory outside a repository. + Frozen for the session; the session records the starting directory and warns if + resumed elsewhere; an mtime change prints a notice only. +- **UI.** Line-mode. ANSI only when stdout is a TTY, and disabled by `NO_COLOR` + or `TERM=dumb`. A small raw-mode line editor: arrow-key history persisted to + disk, bracketed paste as one block, ctrl-a/e/u/k/w editing, ctrl-c abandons the + line, ctrl-d exits. Raw mode is on only while a prompt is being read, so Ctrl-C + during a turn stays a signal. No alt-screen, no markdown rendering, no syntax + highlighting. - **Ctrl-C.** SIGINT handler sets a flag; the stream loop closes the socket and ends the turn. Second Ctrl-C exits. - **No model metadata.** No cost display, no pre-flight context check. Token @@ -163,30 +169,37 @@ Independently rebuilt and re-run outside the agent both times. ## Layout ``` -src/main.rs args, mode selection, exit codes -src/config.rs TOML-free config if possible; env precedence CLI > env > file -src/provider.rs request construction, ureq call, SSE parsing -src/session.rs id, JSONL append/load, replay -src/agent.rs turn/step loop, tool dispatch, approval hooks +src/main.rs args, mode selection, exit codes, /paste +src/config.rs precedence CLI > env > file; key source +src/provider.rs request construction, retry, SSE parsing, model list +src/session.rs id, JSONL append/load/replay, listing, permissions +src/agent.rs turn/step loop, tool dispatch, approval hooks, prompt +src/line.rs raw-mode line editor, history +src/signal.rs SIGINT -> cancel flag +src/doctor.rs --doctor checks src/tools/ read, write, edit, bash, grep, glob -src/ui.rs streaming render, diffs, approval prompt, status line, /paste -tests/mock.rs mock provider over std TcpListener -scripts/check-glibc.sh +src/ui.rs streaming render, diffs, approval prompt, status line +tests/mock.rs provider over std TcpListener (SSE, retry, truncation) +tests/loop.rs agent loop, abort and repair invariants +tests/tools.rs tool semantics and edge cases +tests/sessions.rs session round-trip, listing, permissions +tests/cli.rs argument validation and exit codes +tests/doctor.rs --doctor against a mock provider +tests/sse.rs decoder at every byte boundary +tests/prompt.rs instruction scope +scripts/check-glibc.sh, scripts/mock-provider.py ``` -Input is kept behind a single `read_input() -> Option` function so a -raw-mode editor with history can replace it later without touching the loop. - -## Open questions to settle against the live API - -Blocked on a fresh `OPENCODE_API_KEY` (the stored one returns `api_key_expired`). - -1. Is `stream_options: {"include_usage": true}` honoured, and does usage arrive in - the final chunk? -2. Exact shape and location of `opencode.allowance`; which unit it is in. -3. Is `reasoning_content` the delta field name across all reasoning models, or - only DeepSeek-derived ones? -4. Does the gateway accept `reasoning_effort`, or is reasoning configured - elsewhere? -5. Error body shape for context overflow, to map it to "start a new session". -6. Whether `x-opencode-session` has format constraints (opaque vs UUID). +## Settled against the live API + +1. `stream_options: {"include_usage": true}` is honoured; usage arrives in the + chunk that carries `finish_reason`. ✅ +2. Accounting is nested: `usage.opencode.allowance` and `.list_cost`. ✅ +3. `reasoning_content` is the delta field. ✅ +4. `x-opencode-session` is mandatory: without it the gateway answers 400 + `MissingSessionID`. Any opaque stable id works. ✅ +5. Two consecutive user messages are accepted, so a turn that failed after + writing its prompt can be resumed without editing the transcript. ✅ +6. The default model accepted a 500k-token prompt, so overflow is rarer than + assumed. The exact limit is unknown and deliberately not modelled. ✅ +7. `reasoning_effort`: not sent; unverified. diff --git a/src/agent.rs b/src/agent.rs index a8ad717..d574934 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -183,6 +183,7 @@ pub fn run_turn( push(session, history, user, None); let schemas = tools::schemas(); + let client = provider::agent(); let mut steps = 0usize; let mut last: Option = None; let mut aborted = false; @@ -197,7 +198,14 @@ pub fn run_turn( steps += 1; let mut renderer = Renderer::new(); - let mut outcome = match provider::chat(cfg, history, &schemas, cancel, &mut renderer) { + let mut outcome = match provider::chat_with( + &client, + cfg, + history, + &schemas, + cancel, + &mut renderer, + ) { Ok(outcome) => outcome, Err(Error::Aborted) => { aborted = true; @@ -236,7 +244,7 @@ pub fn run_turn( let result = if aborted { ToolOutcome::Failed("aborted by the user before this call ran".into()) } else { - execute(&call, approver, cancel) + execute(&call, approver, cancel, steps) }; if result.denied() { denied += 1; @@ -320,9 +328,10 @@ fn execute( call: &provider::ToolCall, approver: &mut Approver, cancel: &AtomicBool, + step: usize, ) -> ToolOutcome { let args: Value = serde_json::from_str(&call.arguments).unwrap_or_else(|_| json!({})); - ui::tool_line(&call.name, &args); + ui::tool_line(step, &call.name, &args); match tools::approval(&call.name) { Approval::Never => match tools::run(&call.name, &args, cancel) { diff --git a/src/provider.rs b/src/provider.rs index b45282e..1b9e220 100644 --- a/src/provider.rs +++ b/src/provider.rs @@ -196,12 +196,35 @@ fn explain(status: u16, message: &str) -> String { message.to_string() } +/// One client per turn: rebuilding it per step pays a TLS handshake on every +/// request, which is noticeable on an i686 core. +pub fn agent() -> ureq::Agent { + ureq::Agent::config_builder() + .http_status_as_error(false) + .timeout_connect(Some(Duration::from_secs(10))) + .timeout_recv_response(Some(Duration::from_secs(180))) + .timeout_per_read(Some(Duration::from_secs(180))) + .build() + .into() +} + pub fn chat( cfg: &Config, messages: &[Value], tools: &[Value], cancel: &AtomicBool, sink: &mut dyn Sink, +) -> Result { + chat_with(&agent(), cfg, messages, tools, cancel, sink) +} + +pub fn chat_with( + agent: &ureq::Agent, + cfg: &Config, + messages: &[Value], + tools: &[Value], + cancel: &AtomicBool, + sink: &mut dyn Sink, ) -> Result { // serde_json::Value orders objects by key, so the serialised bytes are // stable for the same input. That is what keeps the provider's prompt cache @@ -217,14 +240,6 @@ pub fn chat( } let bytes = serde_json::to_vec(&body).map_err(|e| Error::Transport(e.to_string()))?; - let agent: ureq::Agent = ureq::Agent::config_builder() - .http_status_as_error(false) - .timeout_connect(Some(Duration::from_secs(10))) - .timeout_recv_response(Some(Duration::from_secs(180))) - .timeout_per_read(Some(Duration::from_secs(180))) - .build() - .into(); - let started = Instant::now(); let mut resp = { let mut attempt = 0usize; diff --git a/src/tools/shell.rs b/src/tools/shell.rs index 29d2375..6f095c6 100644 --- a/src/tools/shell.rs +++ b/src/tools/shell.rs @@ -61,9 +61,10 @@ pub fn bash( .process_group(0); unsafe { command.pre_exec(|| { + // rlim_t is u32 on i686 and u64 on x86-64. let limit = libc::rlimit { - rlim_cur: MAX_OUTPUT_BYTES, - rlim_max: MAX_OUTPUT_BYTES, + rlim_cur: MAX_OUTPUT_BYTES as libc::rlim_t, + rlim_max: MAX_OUTPUT_BYTES as libc::rlim_t, }; if libc::setrlimit(libc::RLIMIT_FSIZE, &limit) != 0 { return Err(std::io::Error::last_os_error()); diff --git a/src/ui.rs b/src/ui.rs index d7716a9..69e7aa9 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -83,7 +83,7 @@ impl Sink for Renderer { } } -pub fn tool_line(name: &str, args: &serde_json::Value) { +pub fn tool_line(step: usize, name: &str, args: &serde_json::Value) { let detail = match name { "bash" => args .get("cmd") @@ -106,7 +106,11 @@ pub fn tool_line(name: &str, args: &serde_json::Value) { .unwrap_or("") .to_string(), }; - println!("{} {}", paint("1;36", &format!("● {name}")), detail); + println!( + "{} {}", + paint("1;36", &format!("● [{step}] {name}")), + detail + ); let _ = std::io::stdout().flush(); } -- cgit v1.2.3