summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--CHANGELOG.md14
-rw-r--r--CONTEXT.md4
-rw-r--r--Cargo.lock2
-rw-r--r--Cargo.toml2
-rw-r--r--README.md23
-rw-r--r--docs/KNOWN-ISSUES.md68
-rw-r--r--docs/PLAN.md75
-rw-r--r--src/agent.rs15
-rw-r--r--src/provider.rs31
-rw-r--r--src/tools/shell.rs5
-rw-r--r--src/ui.rs8
11 files changed, 191 insertions, 56 deletions
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.
7file, and the tool schemas the model sees. Anything a script or a resumed session 7file, and the tool schemas the model sees. Anything a script or a resumed session
8could depend on counts as API. 8could depend on counts as API.
9 9
10## 0.5.0
11
12### Added
13- The step number is printed on every tool line (`● [3] bash …`), so the progress
14 of a long turn is visible while it runs rather than only at the end.
15- `docs/KNOWN-ISSUES.md` records the defects found in review that are understood
16 and deliberately deferred.
17
18### Changed
19- One HTTP client per turn instead of one per step, avoiding a TLS handshake on
20 every request.
21- Documentation corrected where it had drifted: binary size, test count, `grep`
22 semantics, input handling, instruction scope, and the settled API questions.
23
10## 0.4.5 24## 0.4.5
11 25
12### Fixed 26### 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
27call; its outcome is returned to the model as a result, not raised as an error. 27call; its outcome is returned to the model as a result, not raised as an error.
28 28
29**Approval** — the human's permission for a tool call to run. An approval is 29**Approval** — the human's permission for a tool call to run. An approval is
30scoped to a session, not to a turn: once granted, it holds until the session ends. 30scoped to the process running the session, not to a turn: once granted, it holds
31for the rest of that process. A new process asks again, even when the session is
32resumed, 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"
10 10
11[[package]] 11[[package]]
12name = "agent686" 12name = "agent686"
13version = "0.4.4" 13version = "0.5.0"
14dependencies = [ 14dependencies = [
15 "crossterm", 15 "crossterm",
16 "libc", 16 "libc",
diff --git a/Cargo.toml b/Cargo.toml
index a11845b..ea03c5e 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
1[package] 1[package]
2name = "agent686" 2name = "agent686"
3version = "0.4.5" 3version = "0.5.0"
4edition = "2021" 4edition = "2021"
5description = "A small coding agent for a 32-bit Debian box" 5description = "A small coding agent for a 32-bit Debian box"
6publish = false 6publish = 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
6CPU, and the target here is a Debian 12 i386 machine with 2 cores and 4 GB. 6CPU, and the target here is a Debian 12 i386 machine with 2 cores and 4 GB.
7 7
8``` 8```
92.0 MB ELF 32-bit LSB pie, Intel i386 93.5 MiB ELF 32-bit LSB pie, Intel i386
10GLIBC_2.34 required (target has 2.36) 10GLIBC_2.34 required (target has 2.36)
11startup ~0.8 ms
11``` 12```
12 13
13## Build 14## Build
@@ -44,9 +45,11 @@ honoured); a 429 that survives them explains itself instead of dumping JSON.
44 45
45## Tools 46## Tools
46 47
47`read` (numbered lines), `write` (never creates directories), `edit` (exact 48`read` (numbered lines, streamed, regular files only), `write` (atomic, never
48match, must be unique), `bash` (fresh shell per call, 120 s timeout, capped 49creates directories), `edit` (exact match that must be unique; CRLF files
49output), `grep` (literal, recursive), `glob` (`*`, `?`, `**`). 50supported), `bash` (fresh shell per call, own process group, 120 s timeout,
5164 MiB output limit), `grep` (regular expression; `fixed: true` for literals),
52`glob` (`*`, `?`, `**`, follows file symlinks).
50 53
51Reads never prompt. The first `write`/`edit` of a session shows a diff and asks; 54Reads never prompt. The first `write`/`edit` of a session shows a diff and asks;
52answering `a` allows the rest of the session. Every `bash` call asks, because 55answering `a` allows the rest of the session. Every `bash` call asks, because
@@ -55,9 +58,10 @@ that is where `rm -rf` lives.
55## Tests 58## Tests
56 59
57```sh 60```sh
58cargo test # 29 tests, no network 61cargo test # 64 tests, no network
59python3 scripts/mock-provider.py & # canned SSE provider 62python3 scripts/mock-provider.py & # canned SSE provider
60docker run --rm --platform linux/386 debian:12 /b/agent686 # target-shaped gate 63docker run --rm --platform linux/386 \
64 -v "$PWD/target/i686-unknown-linux-gnu/release:/b:ro" debian:12 /b/agent686 --version
61``` 65```
62 66
63`tests/sse.rs` feeds the stream one byte at a time, so splits inside lines and 67`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.
68 72
69MAJOR for API-breaking changes, MINOR for features that do not break the 73MAJOR for API-breaking changes, MINOR for features that do not break the
70interface, PATCH for bug fixes. The interface is the CLI flags, the session file 74interface, PATCH for bug fixes. The interface is the CLI flags, the session file
71format, the config file, and the tool schemas. See [CHANGELOG.md](CHANGELOG.md). 75format, the config file, and the tool schemas.
76
77While the major version is 0, interface changes ride on MINOR and are called out
78explicitly, because there is no stability promise to break yet. The `grep`
79change in 0.4.0 (literal to regex) is the example. See
80[CHANGELOG.md](CHANGELOG.md) and [docs/KNOWN-ISSUES.md](docs/KNOWN-ISSUES.md).
72 81
73## Design notes 82## Design notes
74 83
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 @@
1# Known issues
2
3Understood, deliberately not fixed. Each one has a reason, and a note on what
4would change the decision.
5
6## Concurrent sessions can interleave
7
8Two processes appending to the same session file will interleave messages and
9corrupt the conversation, permanently, because history is never rewritten.
10`flock(LOCK_EX | LOCK_NB)` on the session fd at open would refuse the second
11process. Not done yet because the failure needs deliberately resuming the same
12id in two shells, and the fix is easy to add later. If it ever happens once,
13add the lock.
14
15## `--yolo` has no floor
16
17`--yolo` approves everything, including in `$HOME` or `/`. There is no check
18that the directory is a git repository, so the documented undo does not exist in
19some 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
21in an empty temp directory.
22
23## `--list` reads every transcript
24
25Listing costs O(total bytes of all sessions), because it parses each header and
26counts messages. At current sizes this is milliseconds; a 200 MB session file
27makes it visibly slow. An index or a `--json` format would fix it.
28
29## `edit` loads the whole file
30
31`edit` reads the file, matches, and writes it back through a temporary file. On
32the 32-bit target a file near the address-space limit fails with an out-of-memory
33error rather than a clean refusal. A >32 MB file should be rejected up front with
34"too large for edit; use write".
35
36## Editor width is approximate
37
38The line editor counts one column per character, so wide (CJK) characters,
39combining marks and raw tabs (from a paste) mis-place the caret. The width is
40read once per prompt, so a resize mid-edit mis-renders.
41
42## No transcript viewer
43
44Reasoning is stored beside each assistant message for humans, but the only way to
45read it is `cat` on the JSONL. A `--show <id>` renderer would make auditing a
46`--yolo` run practical.
47
48## Approval state is per process
49
50Restarting the harness re-prompts for the first edit even when resuming a
51session. That is intentional (see CONTEXT.md), but it is worth knowing.
52
53## `--doctor` fails on an unlisted model
54
55If `GET /models` does not list the model id you use (some gateways only list a
56subset), doctor exits 1 even though a turn would work. `--doctor --probe` sending
57a one-token completion would test what actually matters.
58
59## Retry budget is fixed
60
61Four attempts, 1 s / 2 s / 4 s, no jitter, no per-status policy. A 429 for a
62model with a long reset window will still fail after ~7 s.
63
64## No per-turn summary
65
66The status line reports steps, time, tokens and allowance, but not what changed:
67no "3 files written, 5 commands run, 1 denied". For a `--yolo` run that is the
68summary 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.
31 unless `--yolo`. Prompts happen after the stream ends, never mid-token. 31 unless `--yolo`. Prompts happen after the stream ends, never mid-token.
32- **Turn/step.** A turn ends when the model answers with no tool calls, on user 32- **Turn/step.** A turn ends when the model answers with no tool calls, on user
33 abort, or on a non-retryable provider error. **No step cap** — the brake is the 33 abort, or on a non-retryable provider error. **No step cap** — the brake is the
34 step counter on the status line and Ctrl-C. 34 step number printed on every tool line, the allowance in the status line, and
35 Ctrl-C.
35- **Tool errors are data.** Failures, non-zero exits, and denials are returned to 36- **Tool errors are data.** Failures, non-zero exits, and denials are returned to
36 the model as results. Only transport/auth/process failures end a turn. 37 the model as results. Only transport/auth/process failures end a turn.
37- **Sessions.** Append-only JSONL of wire messages (see ADR 0002). No compaction, 38- **Sessions.** Append-only JSONL of wire messages (see ADR 0002). No compaction,
38 no truncation, no summarisation. Overflow is the provider's 400. 39 no truncation, no summarisation. Overflow is the provider's 400.
39- **Prompt.** Snapshot at session start: fixed system prompt, a 3-line 40- **Prompt.** Snapshot at session start: fixed system prompt, one environment
40 environment block (cwd, platform, git branch), and `AGENTS.md` from cwd up to 41 line (cwd, platform, arch, git branch), and `AGENTS.md` from cwd up to the git
41 the git root. Frozen for the session; mtime change prints a notice only. 42 root — never above it, and only the working directory outside a repository.
42- **UI.** Line-mode. ANSI only when stdout is a TTY. Plain `read_line` plus 43 Frozen for the session; the session records the starting directory and warns if
43 `/paste` (reads until a lone `.` or EOF). No alt-screen, no raw mode, no 44 resumed elsewhere; an mtime change prints a notice only.
44 history, no markdown rendering, no syntax highlighting. 45- **UI.** Line-mode. ANSI only when stdout is a TTY, and disabled by `NO_COLOR`
46 or `TERM=dumb`. A small raw-mode line editor: arrow-key history persisted to
47 disk, bracketed paste as one block, ctrl-a/e/u/k/w editing, ctrl-c abandons the
48 line, ctrl-d exits. Raw mode is on only while a prompt is being read, so Ctrl-C
49 during a turn stays a signal. No alt-screen, no markdown rendering, no syntax
50 highlighting.
45- **Ctrl-C.** SIGINT handler sets a flag; the stream loop closes the socket and 51- **Ctrl-C.** SIGINT handler sets a flag; the stream loop closes the socket and
46 ends the turn. Second Ctrl-C exits. 52 ends the turn. Second Ctrl-C exits.
47- **No model metadata.** No cost display, no pre-flight context check. Token 53- **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.
163## Layout 169## Layout
164 170
165``` 171```
166src/main.rs args, mode selection, exit codes 172src/main.rs args, mode selection, exit codes, /paste
167src/config.rs TOML-free config if possible; env precedence CLI > env > file 173src/config.rs precedence CLI > env > file; key source
168src/provider.rs request construction, ureq call, SSE parsing 174src/provider.rs request construction, retry, SSE parsing, model list
169src/session.rs id, JSONL append/load, replay 175src/session.rs id, JSONL append/load/replay, listing, permissions
170src/agent.rs turn/step loop, tool dispatch, approval hooks 176src/agent.rs turn/step loop, tool dispatch, approval hooks, prompt
177src/line.rs raw-mode line editor, history
178src/signal.rs SIGINT -> cancel flag
179src/doctor.rs --doctor checks
171src/tools/ read, write, edit, bash, grep, glob 180src/tools/ read, write, edit, bash, grep, glob
172src/ui.rs streaming render, diffs, approval prompt, status line, /paste 181src/ui.rs streaming render, diffs, approval prompt, status line
173tests/mock.rs mock provider over std TcpListener 182tests/mock.rs provider over std TcpListener (SSE, retry, truncation)
174scripts/check-glibc.sh 183tests/loop.rs agent loop, abort and repair invariants
184tests/tools.rs tool semantics and edge cases
185tests/sessions.rs session round-trip, listing, permissions
186tests/cli.rs argument validation and exit codes
187tests/doctor.rs --doctor against a mock provider
188tests/sse.rs decoder at every byte boundary
189tests/prompt.rs instruction scope
190scripts/check-glibc.sh, scripts/mock-provider.py
175``` 191```
176 192
177Input is kept behind a single `read_input() -> Option<String>` function so a 193## Settled against the live API
178raw-mode editor with history can replace it later without touching the loop. 194
179 1951. `stream_options: {"include_usage": true}` is honoured; usage arrives in the
180## Open questions to settle against the live API 196 chunk that carries `finish_reason`. ✅
181 1972. Accounting is nested: `usage.opencode.allowance` and `.list_cost`. ✅
182Blocked on a fresh `OPENCODE_API_KEY` (the stored one returns `api_key_expired`). 1983. `reasoning_content` is the delta field. ✅
183 1994. `x-opencode-session` is mandatory: without it the gateway answers 400
1841. Is `stream_options: {"include_usage": true}` honoured, and does usage arrive in 200 `MissingSessionID`. Any opaque stable id works. ✅
185 the final chunk? 2015. Two consecutive user messages are accepted, so a turn that failed after
1862. Exact shape and location of `opencode.allowance`; which unit it is in. 202 writing its prompt can be resumed without editing the transcript. ✅
1873. Is `reasoning_content` the delta field name across all reasoning models, or 2036. The default model accepted a 500k-token prompt, so overflow is rarer than
188 only DeepSeek-derived ones? 204 assumed. The exact limit is unknown and deliberately not modelled. ✅
1894. Does the gateway accept `reasoning_effort`, or is reasoning configured 2057. `reasoning_effort`: not sent; unverified.
190 elsewhere?
1915. Error body shape for context overflow, to map it to "start a new session".
1926. Whether `x-opencode-session` has format constraints (opaque vs UUID).
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(
183 push(session, history, user, None); 183 push(session, history, user, None);
184 184
185 let schemas = tools::schemas(); 185 let schemas = tools::schemas();
186 let client = provider::agent();
186 let mut steps = 0usize; 187 let mut steps = 0usize;
187 let mut last: Option<Outcome> = None; 188 let mut last: Option<Outcome> = None;
188 let mut aborted = false; 189 let mut aborted = false;
@@ -197,7 +198,14 @@ pub fn run_turn(
197 198
198 steps += 1; 199 steps += 1;
199 let mut renderer = Renderer::new(); 200 let mut renderer = Renderer::new();
200 let mut outcome = match provider::chat(cfg, history, &schemas, cancel, &mut renderer) { 201 let mut outcome = match provider::chat_with(
202 &client,
203 cfg,
204 history,
205 &schemas,
206 cancel,
207 &mut renderer,
208 ) {
201 Ok(outcome) => outcome, 209 Ok(outcome) => outcome,
202 Err(Error::Aborted) => { 210 Err(Error::Aborted) => {
203 aborted = true; 211 aborted = true;
@@ -236,7 +244,7 @@ pub fn run_turn(
236 let result = if aborted { 244 let result = if aborted {
237 ToolOutcome::Failed("aborted by the user before this call ran".into()) 245 ToolOutcome::Failed("aborted by the user before this call ran".into())
238 } else { 246 } else {
239 execute(&call, approver, cancel) 247 execute(&call, approver, cancel, steps)
240 }; 248 };
241 if result.denied() { 249 if result.denied() {
242 denied += 1; 250 denied += 1;
@@ -320,9 +328,10 @@ fn execute(
320 call: &provider::ToolCall, 328 call: &provider::ToolCall,
321 approver: &mut Approver, 329 approver: &mut Approver,
322 cancel: &AtomicBool, 330 cancel: &AtomicBool,
331 step: usize,
323) -> ToolOutcome { 332) -> ToolOutcome {
324 let args: Value = serde_json::from_str(&call.arguments).unwrap_or_else(|_| json!({})); 333 let args: Value = serde_json::from_str(&call.arguments).unwrap_or_else(|_| json!({}));
325 ui::tool_line(&call.name, &args); 334 ui::tool_line(step, &call.name, &args);
326 335
327 match tools::approval(&call.name) { 336 match tools::approval(&call.name) {
328 Approval::Never => match tools::run(&call.name, &args, cancel) { 337 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,6 +196,18 @@ fn explain(status: u16, message: &str) -> String {
196 message.to_string() 196 message.to_string()
197} 197}
198 198
199/// One client per turn: rebuilding it per step pays a TLS handshake on every
200/// request, which is noticeable on an i686 core.
201pub fn agent() -> ureq::Agent {
202 ureq::Agent::config_builder()
203 .http_status_as_error(false)
204 .timeout_connect(Some(Duration::from_secs(10)))
205 .timeout_recv_response(Some(Duration::from_secs(180)))
206 .timeout_per_read(Some(Duration::from_secs(180)))
207 .build()
208 .into()
209}
210
199pub fn chat( 211pub fn chat(
200 cfg: &Config, 212 cfg: &Config,
201 messages: &[Value], 213 messages: &[Value],
@@ -203,6 +215,17 @@ pub fn chat(
203 cancel: &AtomicBool, 215 cancel: &AtomicBool,
204 sink: &mut dyn Sink, 216 sink: &mut dyn Sink,
205) -> Result<Outcome, Error> { 217) -> Result<Outcome, Error> {
218 chat_with(&agent(), cfg, messages, tools, cancel, sink)
219}
220
221pub fn chat_with(
222 agent: &ureq::Agent,
223 cfg: &Config,
224 messages: &[Value],
225 tools: &[Value],
226 cancel: &AtomicBool,
227 sink: &mut dyn Sink,
228) -> Result<Outcome, Error> {
206 // serde_json::Value orders objects by key, so the serialised bytes are 229 // serde_json::Value orders objects by key, so the serialised bytes are
207 // stable for the same input. That is what keeps the provider's prompt cache 230 // stable for the same input. That is what keeps the provider's prompt cache
208 // warm. Do not add anything session-varying here. 231 // warm. Do not add anything session-varying here.
@@ -217,14 +240,6 @@ pub fn chat(
217 } 240 }
218 let bytes = serde_json::to_vec(&body).map_err(|e| Error::Transport(e.to_string()))?; 241 let bytes = serde_json::to_vec(&body).map_err(|e| Error::Transport(e.to_string()))?;
219 242
220 let agent: ureq::Agent = ureq::Agent::config_builder()
221 .http_status_as_error(false)
222 .timeout_connect(Some(Duration::from_secs(10)))
223 .timeout_recv_response(Some(Duration::from_secs(180)))
224 .timeout_per_read(Some(Duration::from_secs(180)))
225 .build()
226 .into();
227
228 let started = Instant::now(); 243 let started = Instant::now();
229 let mut resp = { 244 let mut resp = {
230 let mut attempt = 0usize; 245 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(
61 .process_group(0); 61 .process_group(0);
62 unsafe { 62 unsafe {
63 command.pre_exec(|| { 63 command.pre_exec(|| {
64 // rlim_t is u32 on i686 and u64 on x86-64.
64 let limit = libc::rlimit { 65 let limit = libc::rlimit {
65 rlim_cur: MAX_OUTPUT_BYTES, 66 rlim_cur: MAX_OUTPUT_BYTES as libc::rlim_t,
66 rlim_max: MAX_OUTPUT_BYTES, 67 rlim_max: MAX_OUTPUT_BYTES as libc::rlim_t,
67 }; 68 };
68 if libc::setrlimit(libc::RLIMIT_FSIZE, &limit) != 0 { 69 if libc::setrlimit(libc::RLIMIT_FSIZE, &limit) != 0 {
69 return Err(std::io::Error::last_os_error()); 70 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 {
83 } 83 }
84} 84}
85 85
86pub fn tool_line(name: &str, args: &serde_json::Value) { 86pub fn tool_line(step: usize, name: &str, args: &serde_json::Value) {
87 let detail = match name { 87 let detail = match name {
88 "bash" => args 88 "bash" => args
89 .get("cmd") 89 .get("cmd")
@@ -106,7 +106,11 @@ pub fn tool_line(name: &str, args: &serde_json::Value) {
106 .unwrap_or("") 106 .unwrap_or("")
107 .to_string(), 107 .to_string(),
108 }; 108 };
109 println!("{} {}", paint("1;36", &format!("● {name}")), detail); 109 println!(
110 "{} {}",
111 paint("1;36", &format!("● [{step}] {name}")),
112 detail
113 );
110 let _ = std::io::stdout().flush(); 114 let _ = std::io::stdout().flush();
111} 115}
112 116