aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--CHANGELOG.md20
-rw-r--r--Cargo.lock228
-rw-r--r--Cargo.toml4
-rw-r--r--README.md10
-rw-r--r--docs/adr/0003-compact-is-a-sanctioned-rewrite.md37
-rw-r--r--src/agent.rs2
-rw-r--r--src/config.rs61
-rw-r--r--src/git.rs57
-rw-r--r--src/lib.rs1
-rw-r--r--src/main.rs115
-rw-r--r--src/provider.rs81
-rw-r--r--src/session.rs25
-rw-r--r--tests/config.rs28
-rw-r--r--tests/git.rs50
-rw-r--r--tests/loop.rs14
-rw-r--r--tests/mock.rs2
-rw-r--r--tests/sessions.rs23
17 files changed, 710 insertions, 48 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index dc0cc9e..6d1a673 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,26 @@ 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.11.0
11
12### Added
13- `/undo` restores the working tree to the state before the last turn, via a git
14 checkpoint commit taken at each turn start (dirty trees only).
15- `/compact` summarises the conversation and rewrites the session to
16 `header + system + summary`, in the same session id. This is the single
17 sanctioned transcript rewrite, documented in ADR 0003; it breaks the prompt
18 cache and has no rollback.
19- Provider presets: `--provider opencode-go|openai|openrouter|ollama|llamacpp|vllm`
20 (or `AGENT686_PROVIDER`). Local gateways default to lenient streaming.
21- `--lenient` tolerates providers that end a stream with text but no
22 `[DONE]`/`finish_reason`.
23- `--system-ca` verifies TLS against the OS trust store (via
24 `rustls-platform-verifier`) instead of bundled roots.
25
26### Changed
27- HTTP proxies (`HTTPS_PROXY`/`HTTP_PROXY`/`ALL_PROXY`/`NO_PROXY`) are honoured —
28 documented, not implemented: ureq already read them.
29
10## 0.10.0 30## 0.10.0
11 31
12### Added 32### Added
diff --git a/Cargo.lock b/Cargo.lock
index ecfdfd2..eae9425 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.9.2" 13version = "0.10.0"
14dependencies = [ 14dependencies = [
15 "crossterm", 15 "crossterm",
16 "libc", 16 "libc",
@@ -65,6 +65,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
65checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" 65checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
66 66
67[[package]] 67[[package]]
68name = "combine"
69version = "4.6.9"
70source = "registry+https://github.com/rust-lang/crates.io-index"
71checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92"
72dependencies = [
73 "bytes",
74 "memchr",
75]
76
77[[package]]
68name = "convert_case" 78name = "convert_case"
69version = "0.10.0" 79version = "0.10.0"
70source = "registry+https://github.com/rust-lang/crates.io-index" 80source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -74,6 +84,22 @@ dependencies = [
74] 84]
75 85
76[[package]] 86[[package]]
87name = "core-foundation"
88version = "0.10.1"
89source = "registry+https://github.com/rust-lang/crates.io-index"
90checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
91dependencies = [
92 "core-foundation-sys",
93 "libc",
94]
95
96[[package]]
97name = "core-foundation-sys"
98version = "0.8.7"
99source = "registry+https://github.com/rust-lang/crates.io-index"
100checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
101
102[[package]]
77name = "crc32fast" 103name = "crc32fast"
78version = "1.5.5" 104version = "1.5.5"
79source = "registry+https://github.com/rust-lang/crates.io-index" 105source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -201,6 +227,55 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
201checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" 227checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
202 228
203[[package]] 229[[package]]
230name = "jni"
231version = "0.22.4"
232source = "registry+https://github.com/rust-lang/crates.io-index"
233checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498"
234dependencies = [
235 "cfg-if",
236 "combine",
237 "jni-macros",
238 "jni-sys",
239 "log",
240 "simd_cesu8",
241 "thiserror",
242 "walkdir",
243 "windows-link",
244]
245
246[[package]]
247name = "jni-macros"
248version = "0.22.4"
249source = "registry+https://github.com/rust-lang/crates.io-index"
250checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3"
251dependencies = [
252 "proc-macro2",
253 "quote",
254 "rustc_version",
255 "simd_cesu8",
256 "syn 2.0.119",
257]
258
259[[package]]
260name = "jni-sys"
261version = "0.4.1"
262source = "registry+https://github.com/rust-lang/crates.io-index"
263checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"
264dependencies = [
265 "jni-sys-macros",
266]
267
268[[package]]
269name = "jni-sys-macros"
270version = "0.4.1"
271source = "registry+https://github.com/rust-lang/crates.io-index"
272checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"
273dependencies = [
274 "quote",
275 "syn 2.0.119",
276]
277
278[[package]]
204name = "libc" 279name = "libc"
205version = "0.2.191" 280version = "0.2.191"
206source = "registry+https://github.com/rust-lang/crates.io-index" 281source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -268,6 +343,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
268checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" 343checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
269 344
270[[package]] 345[[package]]
346name = "openssl-probe"
347version = "0.2.2"
348source = "registry+https://github.com/rust-lang/crates.io-index"
349checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1"
350
351[[package]]
271name = "parking_lot" 352name = "parking_lot"
272version = "0.12.5" 353version = "0.12.5"
273source = "registry+https://github.com/rust-lang/crates.io-index" 354source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -404,6 +485,18 @@ dependencies = [
404] 485]
405 486
406[[package]] 487[[package]]
488name = "rustls-native-certs"
489version = "0.8.5"
490source = "registry+https://github.com/rust-lang/crates.io-index"
491checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4"
492dependencies = [
493 "openssl-probe",
494 "rustls-pki-types",
495 "schannel",
496 "security-framework",
497]
498
499[[package]]
407name = "rustls-pki-types" 500name = "rustls-pki-types"
408version = "1.16.0" 501version = "1.16.0"
409source = "registry+https://github.com/rust-lang/crates.io-index" 502source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -413,6 +506,33 @@ dependencies = [
413] 506]
414 507
415[[package]] 508[[package]]
509name = "rustls-platform-verifier"
510version = "0.7.1"
511source = "registry+https://github.com/rust-lang/crates.io-index"
512checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98"
513dependencies = [
514 "core-foundation",
515 "core-foundation-sys",
516 "jni",
517 "log",
518 "once_cell",
519 "rustls",
520 "rustls-native-certs",
521 "rustls-platform-verifier-android",
522 "rustls-webpki",
523 "security-framework",
524 "security-framework-sys",
525 "webpki-root-certs",
526 "windows-sys 0.52.0",
527]
528
529[[package]]
530name = "rustls-platform-verifier-android"
531version = "0.2.0"
532source = "registry+https://github.com/rust-lang/crates.io-index"
533checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f"
534
535[[package]]
416name = "rustls-webpki" 536name = "rustls-webpki"
417version = "0.103.17" 537version = "0.103.17"
418source = "registry+https://github.com/rust-lang/crates.io-index" 538source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -424,12 +544,53 @@ dependencies = [
424] 544]
425 545
426[[package]] 546[[package]]
547name = "same-file"
548version = "1.0.6"
549source = "registry+https://github.com/rust-lang/crates.io-index"
550checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
551dependencies = [
552 "winapi-util",
553]
554
555[[package]]
556name = "schannel"
557version = "0.1.30"
558source = "registry+https://github.com/rust-lang/crates.io-index"
559checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5"
560dependencies = [
561 "windows-sys 0.61.2",
562]
563
564[[package]]
427name = "scopeguard" 565name = "scopeguard"
428version = "1.2.0" 566version = "1.2.0"
429source = "registry+https://github.com/rust-lang/crates.io-index" 567source = "registry+https://github.com/rust-lang/crates.io-index"
430checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" 568checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
431 569
432[[package]] 570[[package]]
571name = "security-framework"
572version = "3.7.0"
573source = "registry+https://github.com/rust-lang/crates.io-index"
574checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
575dependencies = [
576 "bitflags",
577 "core-foundation",
578 "core-foundation-sys",
579 "libc",
580 "security-framework-sys",
581]
582
583[[package]]
584name = "security-framework-sys"
585version = "2.17.0"
586source = "registry+https://github.com/rust-lang/crates.io-index"
587checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
588dependencies = [
589 "core-foundation-sys",
590 "libc",
591]
592
593[[package]]
433name = "semver" 594name = "semver"
434version = "1.0.28" 595version = "1.0.28"
435source = "registry+https://github.com/rust-lang/crates.io-index" 596source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -522,6 +683,22 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
522checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" 683checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
523 684
524[[package]] 685[[package]]
686name = "simd_cesu8"
687version = "1.2.0"
688source = "registry+https://github.com/rust-lang/crates.io-index"
689checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520"
690dependencies = [
691 "rustc_version",
692 "simdutf8",
693]
694
695[[package]]
696name = "simdutf8"
697version = "0.1.5"
698source = "registry+https://github.com/rust-lang/crates.io-index"
699checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
700
701[[package]]
525name = "smallvec" 702name = "smallvec"
526version = "1.16.5" 703version = "1.16.5"
527source = "registry+https://github.com/rust-lang/crates.io-index" 704source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -556,6 +733,26 @@ dependencies = [
556] 733]
557 734
558[[package]] 735[[package]]
736name = "thiserror"
737version = "2.0.21"
738source = "registry+https://github.com/rust-lang/crates.io-index"
739checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
740dependencies = [
741 "thiserror-impl",
742]
743
744[[package]]
745name = "thiserror-impl"
746version = "2.0.21"
747source = "registry+https://github.com/rust-lang/crates.io-index"
748checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
749dependencies = [
750 "proc-macro2",
751 "quote",
752 "syn 3.0.10",
753]
754
755[[package]]
559name = "unicode-ident" 756name = "unicode-ident"
560version = "1.0.27" 757version = "1.0.27"
561source = "registry+https://github.com/rust-lang/crates.io-index" 758source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -591,6 +788,7 @@ dependencies = [
591 "percent-encoding", 788 "percent-encoding",
592 "rustls", 789 "rustls",
593 "rustls-pki-types", 790 "rustls-pki-types",
791 "rustls-platform-verifier",
594 "ureq-proto", 792 "ureq-proto",
595 "utf8-zero", 793 "utf8-zero",
596 "webpki-roots", 794 "webpki-roots",
@@ -615,12 +813,31 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
615checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" 813checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e"
616 814
617[[package]] 815[[package]]
816name = "walkdir"
817version = "2.5.0"
818source = "registry+https://github.com/rust-lang/crates.io-index"
819checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
820dependencies = [
821 "same-file",
822 "winapi-util",
823]
824
825[[package]]
618name = "wasi" 826name = "wasi"
619version = "0.11.1+wasi-snapshot-preview1" 827version = "0.11.1+wasi-snapshot-preview1"
620source = "registry+https://github.com/rust-lang/crates.io-index" 828source = "registry+https://github.com/rust-lang/crates.io-index"
621checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" 829checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
622 830
623[[package]] 831[[package]]
832name = "webpki-root-certs"
833version = "1.0.11"
834source = "registry+https://github.com/rust-lang/crates.io-index"
835checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a"
836dependencies = [
837 "rustls-pki-types",
838]
839
840[[package]]
624name = "webpki-roots" 841name = "webpki-roots"
625version = "1.0.12" 842version = "1.0.12"
626source = "registry+https://github.com/rust-lang/crates.io-index" 843source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -646,6 +863,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
646checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 863checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
647 864
648[[package]] 865[[package]]
866name = "winapi-util"
867version = "0.1.11"
868source = "registry+https://github.com/rust-lang/crates.io-index"
869checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
870dependencies = [
871 "windows-sys 0.52.0",
872]
873
874[[package]]
649name = "winapi-x86_64-pc-windows-gnu" 875name = "winapi-x86_64-pc-windows-gnu"
650version = "0.4.0" 876version = "0.4.0"
651source = "registry+https://github.com/rust-lang/crates.io-index" 877source = "registry+https://github.com/rust-lang/crates.io-index"
diff --git a/Cargo.toml b/Cargo.toml
index e4a6ecb..44d2fee 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
1[package] 1[package]
2name = "agent686" 2name = "agent686"
3version = "0.10.0" 3version = "0.11.0"
4edition = "2021" 4edition = "2021"
5description = "A small coding agent for Debian-class Linux" 5description = "A small coding agent for Debian-class Linux"
6publish = false 6publish = false
@@ -8,7 +8,7 @@ publish = false
8[dependencies] 8[dependencies]
9serde = { version = "1", features = ["derive"] } 9serde = { version = "1", features = ["derive"] }
10serde_json = "1" 10serde_json = "1"
11ureq = { version = "3", features = ["rustls"] } 11ureq = { version = "3", features = ["rustls", "platform-verifier"] }
12libc = "0.2" 12libc = "0.2"
13crossterm = "0.29.0" 13crossterm = "0.29.0"
14regex = "1.13.1" 14regex = "1.13.1"
diff --git a/README.md b/README.md
index 6f5260a..6990701 100644
--- a/README.md
+++ b/README.md
@@ -56,11 +56,15 @@ export OPENCODE_API_KEY=... # or write it to ~/.config/agent686/key
56``` 56```
57 57
58Provider is OpenCode Go, `chat/completions`, model `deepseek-v4.1-flash` by 58Provider is OpenCode Go, `chat/completions`, model `deepseek-v4.1-flash` by
59default. Every request carries a stable `x-opencode-session` header, which the 59default; `--provider ollama|openai|openrouter|vllm|llamacpp` switches to another
60service uses for routing and prompt caching. 60OpenAI-compatible endpoint, with `--lenient` for servers that omit `[DONE]`.
61`HTTPS_PROXY`/`NO_PROXY` are honoured. Every request carries a stable
62`x-opencode-session` header, which the service uses for routing and prompt caching.
61 63
62In a terminal: up/down walks history, bracketed paste arrives as one block 64In a terminal: up/down walks history, bracketed paste arrives as one block
63(multi-line is fine), ctrl-c abandons the line, ctrl-d exits. 65(multi-line is fine), ctrl-c abandons the line, ctrl-d exits. `/undo` reverts the
66working tree to before the last turn, `/compact` summarises a long conversation,
67`/models` and `/model <id>` manage the model, `/forget <id>` prunes sessions.
64 68
65Rate limits and transient failures retry with backoff (four attempts, `Retry-After` 69Rate limits and transient failures retry with backoff (four attempts, `Retry-After`
66honoured); a 429 that survives them explains itself instead of dumping JSON. 70honoured); a 429 that survives them explains itself instead of dumping JSON.
diff --git a/docs/adr/0003-compact-is-a-sanctioned-rewrite.md b/docs/adr/0003-compact-is-a-sanctioned-rewrite.md
new file mode 100644
index 0000000..19a42dc
--- /dev/null
+++ b/docs/adr/0003-compact-is-a-sanctioned-rewrite.md
@@ -0,0 +1,37 @@
1# 0003 — `/compact` is the single sanctioned rewrite of a transcript
2
3**Status:** accepted
4
5## Context
6
7ADR 0002 made sessions append-only and forbade rewriting history, because the
8provider's prompt cache depends on a byte-identical prefix and any edit to
9earlier messages invalidates it. The cost of that decision was a hard context
10ceiling: a long conversation could not be shortened, only abandoned.
11
12The default model accepts ~500k tokens, so the ceiling is rarely reached, but
13when it is, "start a new session" loses everything in the conversation.
14
15## Decision
16
17`/compact` is an explicit, user-initiated command that:
18
191. asks the model for a one-paragraph summary of the conversation (a single
20 non-streaming completion),
212. rewrites the session file to `header + system + one user message` carrying
22 that summary, under the same session id,
233. continues in place.
24
25It is the **only** code path that truncates a transcript, and it deliberately
26breaks the prompt cache — an accepted cost, because the user asked for it and it
27happens once, not on every step.
28
29## Consequences
30
31- A long session can now be continued instead of abandoned, at the price of the
32 detail the summary omits.
33- The cache is cold after `/compact`; the next turn re-bills the whole prefix.
34- There is no rollback: the pre-compact messages are gone. The summary is the
35 only record, so a bad summary loses real context.
36- ADR 0002 still governs everything else: no summarisation, truncation, or
37 sliding window happens automatically.
diff --git a/src/agent.rs b/src/agent.rs
index afd662c..c3d77c1 100644
--- a/src/agent.rs
+++ b/src/agent.rs
@@ -185,7 +185,7 @@ pub fn run_turn(
185 push(session, history, user, None); 185 push(session, history, user, None);
186 186
187 let schemas = tools::schemas(); 187 let schemas = tools::schemas();
188 let client = provider::agent(); 188 let client = provider::agent(cfg.system_ca);
189 let mut steps = 0usize; 189 let mut steps = 0usize;
190 let mut last: Option<Outcome> = None; 190 let mut last: Option<Outcome> = None;
191 let mut aborted = false; 191 let mut aborted = false;
diff --git a/src/config.rs b/src/config.rs
index 77bdc52..1d259c7 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -3,6 +3,17 @@ use std::path::PathBuf;
3pub const DEFAULT_BASE_URL: &str = "https://opencode.ai/inference/go/openai/v1"; 3pub const DEFAULT_BASE_URL: &str = "https://opencode.ai/inference/go/openai/v1";
4pub const DEFAULT_MODEL: &str = "deepseek-v4.1-flash"; 4pub const DEFAULT_MODEL: &str = "deepseek-v4.1-flash";
5 5
6/// (name, base_url, default_model, lenient). Local gateways that omit `[DONE]`
7/// or `usage` are marked lenient so a truncated-looking stream is not an error.
8const PRESETS: &[(&str, &str, &str, bool)] = &[
9 ("opencode-go", DEFAULT_BASE_URL, DEFAULT_MODEL, false),
10 ("openai", "https://api.openai.com/v1", "gpt-4o-mini", false),
11 ("openrouter", "https://openrouter.ai/api/v1", "", false),
12 ("ollama", "http://localhost:11434/v1", "", true),
13 ("llamacpp", "http://localhost:8080/v1", "", true),
14 ("vllm", "http://localhost:8000/v1", "", true),
15];
16
6#[derive(Debug, Clone, PartialEq, Eq)] 17#[derive(Debug, Clone, PartialEq, Eq)]
7pub enum KeySource { 18pub enum KeySource {
8 Env, 19 Env,
@@ -19,16 +30,24 @@ pub struct Config {
19 /// the session exists. 30 /// the session exists.
20 pub session: String, 31 pub session: String,
21 pub yolo: bool, 32 pub yolo: bool,
33 /// Tolerate providers that omit `[DONE]`/`usage`/`finish_reason`.
34 pub lenient: bool,
35 /// Verify TLS against the system trust store instead of bundled roots.
36 pub system_ca: bool,
22} 37}
23 38
24impl Config { 39impl Config {
25 /// CLI flags win over environment variables, which win over defaults. 40 /// CLI flags win over environment variables, which win over defaults.
41 #[allow(clippy::too_many_arguments)]
26 pub fn resolve( 42 pub fn resolve(
27 model: Option<String>, 43 model: Option<String>,
28 base_url: Option<String>, 44 base_url: Option<String>,
29 yolo: bool, 45 yolo: bool,
46 provider: Option<String>,
47 lenient: bool,
48 system_ca: bool,
30 ) -> Result<Config, String> { 49 ) -> Result<Config, String> {
31 let config = Self::resolve_lenient(model, base_url, yolo); 50 let config = Self::resolve_lenient(model, base_url, yolo, provider, lenient, system_ca);
32 if config.api_key.is_empty() { 51 if config.api_key.is_empty() {
33 return Err(format!( 52 return Err(format!(
34 "no API key: set OPENCODE_API_KEY or write one to {}", 53 "no API key: set OPENCODE_API_KEY or write one to {}",
@@ -42,17 +61,39 @@ impl Config {
42 61
43 /// Same as `resolve`, but tolerates a missing key so `--doctor` can report 62 /// Same as `resolve`, but tolerates a missing key so `--doctor` can report
44 /// the missing key instead of failing to start. 63 /// the missing key instead of failing to start.
45 pub fn resolve_lenient(model: Option<String>, base_url: Option<String>, yolo: bool) -> Config { 64 pub fn resolve_lenient(
65 model: Option<String>,
66 base_url: Option<String>,
67 yolo: bool,
68 provider: Option<String>,
69 lenient: bool,
70 system_ca: bool,
71 ) -> Config {
72 // Presets fill the base URL and a default model; explicit values win.
73 let provider = provider.or_else(|| env_nonempty("AGENT686_PROVIDER"));
74 let (preset_url, preset_model, preset_lenient) = provider
75 .as_deref()
76 .and_then(|name| PRESETS.iter().find(|(n, ..)| *n == name))
77 .map(|(_, url, model, lenient)| (*url, *model, *lenient))
78 .unwrap_or((DEFAULT_BASE_URL, "", false));
79
80 let base_url = base_url
81 .or_else(|| env_nonempty("AGENT686_BASE_URL"))
82 .unwrap_or_else(|| preset_url.to_string());
83
84 let model = model
85 .or_else(|| env_nonempty("AGENT686_MODEL"))
86 .or_else(|| (!preset_model.is_empty()).then(|| preset_model.to_string()))
87 .unwrap_or_else(|| DEFAULT_MODEL.to_string());
88
46 Config { 89 Config {
47 api_key: api_key().unwrap_or_default(), 90 api_key: api_key().unwrap_or_default(),
48 base_url: base_url 91 base_url,
49 .or_else(|| env_nonempty("AGENT686_BASE_URL")) 92 model,
50 .unwrap_or_else(|| DEFAULT_BASE_URL.to_string()),
51 model: model
52 .or_else(|| env_nonempty("AGENT686_MODEL"))
53 .unwrap_or_else(|| DEFAULT_MODEL.to_string()),
54 session: String::new(), 93 session: String::new(),
55 yolo, 94 yolo,
95 lenient: lenient || preset_lenient,
96 system_ca: system_ca || env_nonempty("AGENT686_SYSTEM_CA").is_some(),
56 } 97 }
57 } 98 }
58 99
@@ -61,6 +102,10 @@ impl Config {
61 } 102 }
62} 103}
63 104
105pub fn provider_names() -> Vec<&'static str> {
106 PRESETS.iter().map(|(name, ..)| *name).collect()
107}
108
64fn env_nonempty(key: &str) -> Option<String> { 109fn env_nonempty(key: &str) -> Option<String> {
65 std::env::var(key).ok().filter(|v| !v.trim().is_empty()) 110 std::env::var(key).ok().filter(|v| !v.trim().is_empty())
66} 111}
diff --git a/src/git.rs b/src/git.rs
new file mode 100644
index 0000000..78348af
--- /dev/null
+++ b/src/git.rs
@@ -0,0 +1,57 @@
1//! Git helpers for the checkpoint/undo feature. In a separate module so they
2//! are unit-testable without driving the whole CLI.
3
4use std::path::Path;
5use std::process::Command;
6
7/// Runs `git -C <dir> <args>`, returning trimmed stdout on success.
8pub fn run(dir: &Path, args: &[&str]) -> Option<String> {
9 Command::new("git")
10 .arg("-C")
11 .arg(dir)
12 .args(args)
13 .output()
14 .ok()
15 .and_then(|output| {
16 output
17 .status
18 .success()
19 .then(|| String::from_utf8_lossy(&output.stdout).trim().to_string())
20 })
21}
22
23/// True when `dir` is inside a work tree (a `.git` dir or file up the tree).
24pub fn in_repo(dir: &Path) -> bool {
25 let mut current = dir.to_path_buf();
26 loop {
27 if current.join(".git").exists() {
28 return true;
29 }
30 if !current.pop() {
31 return false;
32 }
33 }
34}
35
36/// Snapshots the tree as a commit when it is dirty, and returns HEAD. Returns
37/// `None` outside a repository.
38pub fn checkpoint(dir: &Path) -> Option<String> {
39 if !in_repo(dir) {
40 return None;
41 }
42 run(dir, &["add", "-A"]);
43 let dirty = run(dir, &["status", "--porcelain"])
44 .map(|status| !status.is_empty())
45 .unwrap_or(false);
46 if dirty {
47 run(dir, &["commit", "-m", "agent686: checkpoint"]);
48 }
49 run(dir, &["rev-parse", "HEAD"])
50}
51
52/// Resets to the checkpoint commit and drops untracked files, undoing a turn's
53/// changes.
54pub fn undo(dir: &Path, sha: &str) {
55 run(dir, &["reset", "--hard", sha]);
56 run(dir, &["clean", "-fd"]);
57}
diff --git a/src/lib.rs b/src/lib.rs
index c5c02b1..b1e0592 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,6 +1,7 @@
1pub mod agent; 1pub mod agent;
2pub mod config; 2pub mod config;
3pub mod doctor; 3pub mod doctor;
4pub mod git;
4pub mod line; 5pub mod line;
5pub mod provider; 6pub mod provider;
6pub mod session; 7pub mod session;
diff --git a/src/main.rs b/src/main.rs
index a425d71..8f53d9e 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,4 +1,5 @@
1use std::io::{BufRead, IsTerminal, Write}; 1use std::io::{BufRead, IsTerminal, Write};
2use std::path::Path;
2use serde_json::json; 3use serde_json::json;
3use std::time::UNIX_EPOCH; 4use std::time::UNIX_EPOCH;
4use std::path::PathBuf; 5use std::path::PathBuf;
@@ -37,6 +38,10 @@ OPTIONS:
37 --show [ID] print a transcript (most recent if no ID) and exit 38 --show [ID] print a transcript (most recent if no ID) and exit
38 --doctor check key, directories, provider and model, then exit 39 --doctor check key, directories, provider and model, then exit
39 --yolo approve every tool call without asking 40 --yolo approve every tool call without asking
41 --provider <NAME> preset: opencode-go, openai, openrouter, ollama,
42 llamacpp, vllm
43 --lenient tolerate providers that omit [DONE]/usage
44 --system-ca verify TLS with the system trust store
40 -V, --version print the version and exit 45 -V, --version print the version and exit
41 -h, --help this text 46 -h, --help this text
42 47
@@ -63,6 +68,9 @@ struct Args {
63 doctor: bool, 68 doctor: bool,
64 yolo: bool, 69 yolo: bool,
65 json: bool, 70 json: bool,
71 provider: Option<String>,
72 lenient: bool,
73 system_ca: bool,
66} 74}
67 75
68fn main() { 76fn main() {
@@ -88,6 +96,9 @@ fn parse_args() -> Result<Args, String> {
88 doctor: false, 96 doctor: false,
89 yolo: false, 97 yolo: false,
90 json: false, 98 json: false,
99 provider: None,
100 lenient: false,
101 system_ca: false,
91 }; 102 };
92 let mut words: Vec<String> = Vec::new(); 103 let mut words: Vec<String> = Vec::new();
93 let mut iter = std::env::args().skip(1).peekable(); 104 let mut iter = std::env::args().skip(1).peekable();
@@ -118,6 +129,10 @@ fn parse_args() -> Result<Args, String> {
118 args.show = Some(Some(value.to_string())); 129 args.show = Some(Some(value.to_string()));
119 continue; 130 continue;
120 } 131 }
132 "--provider" => {
133 args.provider = Some(value.to_string());
134 continue;
135 }
121 _ => return Err(format!("unknown flag {flag}\n\n{HELP}")), 136 _ => return Err(format!("unknown flag {flag}\n\n{HELP}")),
122 } 137 }
123 } 138 }
@@ -142,6 +157,9 @@ fn parse_args() -> Result<Args, String> {
142 "--doctor" => args.doctor = true, 157 "--doctor" => args.doctor = true,
143 "--yolo" => args.yolo = true, 158 "--yolo" => args.yolo = true,
144 "--json" => args.json = true, 159 "--json" => args.json = true,
160 "--provider" => args.provider = Some(take_value(&mut iter, "--provider")?),
161 "--lenient" => args.lenient = true,
162 "--system-ca" => args.system_ca = true,
145 "-V" | "--version" => { 163 "-V" | "--version" => {
146 println!("agent686 {}", env!("CARGO_PKG_VERSION")); 164 println!("agent686 {}", env!("CARGO_PKG_VERSION"));
147 std::process::exit(0); 165 std::process::exit(0);
@@ -216,13 +234,27 @@ fn run(args: Args) {
216 } 234 }
217 235
218 if args.doctor { 236 if args.doctor {
219 let mut config = Config::resolve_lenient(args.model, args.base_url, args.yolo); 237 let mut config = Config::resolve_lenient(
238 args.model,
239 args.base_url,
240 args.yolo,
241 args.provider,
242 args.lenient,
243 args.system_ca,
244 );
220 // `/models` needs the session header too, even though this is not a turn. 245 // `/models` needs the session header too, even though this is not a turn.
221 config.session = session::new_id(); 246 config.session = session::new_id();
222 std::process::exit(doctor::run(&config, args.json)); 247 std::process::exit(doctor::run(&config, args.json));
223 } 248 }
224 249
225 let mut cfg = match Config::resolve(args.model, args.base_url, args.yolo) { 250 let mut cfg = match Config::resolve(
251 args.model,
252 args.base_url,
253 args.yolo,
254 args.provider,
255 args.lenient,
256 args.system_ca,
257 ) {
226 Ok(cfg) => cfg, 258 Ok(cfg) => cfg,
227 Err(message) => { 259 Err(message) => {
228 eprintln!("agent686: {message}"); 260 eprintln!("agent686: {message}");
@@ -287,6 +319,7 @@ fn run(args: Args) {
287 319
288 let mut editor = Editor::new(); 320 let mut editor = Editor::new();
289 let interactive = editor.is_interactive(); 321 let interactive = editor.is_interactive();
322 let mut checkpoint: Option<String> = None;
290 if !interactive && !cfg.yolo { 323 if !interactive && !cfg.yolo {
291 eprintln!( 324 eprintln!(
292 "agent686: stdin is not a terminal, so write/edit/bash will be denied; \ 325 "agent686: stdin is not a terminal, so write/edit/bash will be denied; \
@@ -330,6 +363,14 @@ fn run(args: Args) {
330 forget_sessions(&text, &session); 363 forget_sessions(&text, &session);
331 continue; 364 continue;
332 } 365 }
366 if text == "/undo" {
367 undo(checkpoint.as_deref());
368 continue;
369 }
370 if text == "/compact" {
371 compact(&cfg, &mut session, &mut history);
372 continue;
373 }
333 374
334 match text.as_str() { 375 match text.as_str() {
335 "/exit" | "/quit" => break, 376 "/exit" | "/quit" => break,
@@ -364,6 +405,7 @@ fn run(args: Args) {
364 } 405 }
365 406
366 warn_if_changed(&watched, &mut warned); 407 warn_if_changed(&watched, &mut warned);
408 checkpoint = git_checkpoint();
367 if let Err(error) = agent::run_turn( 409 if let Err(error) = agent::run_turn(
368 &cfg, 410 &cfg,
369 &mut session, 411 &mut session,
@@ -439,6 +481,63 @@ fn open_session(
439 481
440/// The system prompt is frozen with the directory the session started in. If the 482/// The system prompt is frozen with the directory the session started in. If the
441/// user resumes from somewhere else, tools and prompt disagree. 483/// user resumes from somewhere else, tools and prompt disagree.
484/// Git is the documented undo, so before a turn we snapshot the tree with a
485/// commit when it is dirty. `/undo` resets back to this.
486fn git_checkpoint() -> Option<String> {
487 let Ok(cwd) = std::env::current_dir() else {
488 return None;
489 };
490 agent686::git::checkpoint(&cwd)
491}
492
493fn undo(checkpoint: Option<&str>) {
494 let Some(sha) = checkpoint else {
495 eprintln!("agent686: /undo needs a git repository");
496 return;
497 };
498 let Ok(cwd) = std::env::current_dir() else {
499 return;
500 };
501 agent686::git::undo(&cwd, sha);
502 eprintln!("agent686: restored to {sha}");
503}
504
505/// `/compact`: summarise the conversation and start again from the summary, in
506/// the same session id. The only sanctioned rewrite of the transcript (ADR 0003).
507fn compact(cfg: &Config, session: &mut Session, history: &mut Vec<Value>) {
508 let system = history.first().cloned().unwrap_or_else(|| agent::system_prompt());
509 let mut messages = history.clone();
510 messages.push(json!({
511 "role": "user",
512 "content": "Summarize the conversation so far into one concise paragraph that \
513 preserves the goal, decisions made, files changed, and the current \
514 state. Omit pleasantries."
515 }));
516 let summary = match agent686::provider::summarize(cfg, &messages) {
517 Ok(summary) if !summary.trim().is_empty() => summary,
518 Ok(_) => {
519 eprintln!("agent686: /compact produced an empty summary; aborting");
520 return;
521 }
522 Err(error) => {
523 eprintln!("agent686: /compact failed: {error}");
524 return;
525 }
526 };
527
528 let user = json!({
529 "role": "user",
530 "content": format!("[earlier conversation, summarized]\n{summary}"),
531 });
532 let new_history = vec![system.clone(), user];
533 if let Err(error) = session.rewrite(&system, &new_history[1..]) {
534 eprintln!("agent686: /compact could not rewrite the session: {error}");
535 return;
536 }
537 *history = new_history;
538 eprintln!("agent686: compacted into a {}-character summary", summary.len());
539}
540
442fn list_models(cfg: &Config) { 541fn list_models(cfg: &Config) {
443 match agent686::provider::models(cfg) { 542 match agent686::provider::models(cfg) {
444 Ok(models) => { 543 Ok(models) => {
@@ -640,16 +739,8 @@ fn refuse_yolo(cfg: &Config) {
640 } 739 }
641} 740}
642 741
643fn in_git_repo(dir: &std::path::Path) -> bool { 742fn in_git_repo(dir: &Path) -> bool {
644 let mut current = dir.to_path_buf(); 743 agent686::git::in_repo(dir)
645 loop {
646 if current.join(".git").exists() {
647 return true;
648 }
649 if !current.pop() {
650 return false;
651 }
652 }
653} 744}
654 745
655fn style(code: &str, text: &str, color: bool) -> String { 746fn style(code: &str, text: &str, color: bool) -> String {
diff --git a/src/provider.rs b/src/provider.rs
index b08d1f2..c03dea2 100644
--- a/src/provider.rs
+++ b/src/provider.rs
@@ -197,15 +197,22 @@ fn explain(status: u16, message: &str) -> String {
197} 197}
198 198
199/// One client per turn: rebuilding it per step pays a TLS handshake on every 199/// One client per turn: rebuilding it per step pays a TLS handshake on every
200/// request, which is noticeable on an i686 core. 200/// request, which is noticeable on an i686 core. `system_ca` verifies against
201pub fn agent() -> ureq::Agent { 201/// the OS trust store instead of bundled roots.
202 ureq::Agent::config_builder() 202pub fn agent(system_ca: bool) -> ureq::Agent {
203 let mut builder = ureq::Agent::config_builder()
203 .http_status_as_error(false) 204 .http_status_as_error(false)
204 .timeout_connect(Some(Duration::from_secs(10))) 205 .timeout_connect(Some(Duration::from_secs(10)))
205 .timeout_recv_response(Some(Duration::from_secs(180))) 206 .timeout_recv_response(Some(Duration::from_secs(180)))
206 .timeout_per_read(Some(Duration::from_secs(180))) 207 .timeout_per_read(Some(Duration::from_secs(180)));
207 .build() 208 if system_ca {
208 .into() 209 builder = builder.tls_config(
210 ureq::tls::TlsConfig::builder()
211 .root_certs(ureq::tls::RootCerts::PlatformVerifier)
212 .build(),
213 );
214 }
215 builder.build().into()
209} 216}
210 217
211pub fn chat( 218pub fn chat(
@@ -215,7 +222,7 @@ pub fn chat(
215 cancel: &AtomicBool, 222 cancel: &AtomicBool,
216 sink: &mut dyn Sink, 223 sink: &mut dyn Sink,
217) -> Result<Outcome, Error> { 224) -> Result<Outcome, Error> {
218 chat_with(&agent(), cfg, messages, tools, cancel, sink) 225 chat_with(&agent(cfg.system_ca), cfg, messages, tools, cancel, sink)
219} 226}
220 227
221pub fn chat_with( 228pub fn chat_with(
@@ -378,14 +385,18 @@ pub fn chat_with(
378 } 385 }
379 386
380 // A connection that closes early, or a 200 that is not SSE at all, must not 387 // A connection that closes early, or a 200 that is not SSE at all, must not
381 // be recorded as a complete answer. 388 // be recorded as a complete answer. Lenient mode tolerates local servers
389 // that finish with text but no [DONE]/finish_reason.
382 if !completed { 390 if !completed {
383 return Err(Error::Transport(format!( 391 let lenient_ok = cfg.lenient && outcome.tool_calls.is_empty() && !outcome.content.is_empty();
384 "stream ended before completion ({} bytes of text, {} tool call(s)); \ 392 if !lenient_ok {
385 the turn was not recorded as answered", 393 return Err(Error::Transport(format!(
386 outcome.content.len(), 394 "stream ended before completion ({} bytes of text, {} tool call(s)); \
387 outcome.tool_calls.len() 395 the turn was not recorded as answered",
388 ))); 396 outcome.content.len(),
397 outcome.tool_calls.len()
398 )));
399 }
389 } 400 }
390 401
391 sink.done(&outcome, started.elapsed()); 402 sink.done(&outcome, started.elapsed());
@@ -555,15 +566,43 @@ struct FunctionDelta {
555 arguments: Option<String>, 566 arguments: Option<String>,
556} 567}
557 568
569/// A single non-streaming completion, used by `/compact` to summarise history.
570pub fn summarize(cfg: &Config, messages: &[Value]) -> Result<String, Error> {
571 let body = serde_json::json!({ "model": cfg.model, "messages": messages, "stream": false });
572 let bytes = serde_json::to_vec(&body).map_err(|e| Error::Transport(e.to_string()))?;
573 let mut response = agent(cfg.system_ca)
574 .post(&cfg.endpoint())
575 .header("Content-Type", "application/json")
576 .header("Authorization", format!("Bearer {}", cfg.api_key))
577 .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION")))
578 .header("x-opencode-session", &cfg.session)
579 .send(bytes)
580 .map_err(|e| Error::Transport(e.to_string()))?;
581
582 let status = response.status().as_u16();
583 let text = response
584 .body_mut()
585 .with_config()
586 .limit(2 * 1024 * 1024)
587 .read_to_string()
588 .unwrap_or_default();
589 if !(200..300).contains(&status) {
590 return Err(Error::Status {
591 code: status,
592 message: error_message(&text),
593 });
594 }
595 let value: Value = serde_json::from_str(&text)
596 .map_err(|e| Error::Transport(format!("could not parse the completion: {e}")))?;
597 Ok(value["choices"][0]["message"]["content"]
598 .as_str()
599 .unwrap_or("")
600 .to_string())
601}
602
558/// Lists the models the provider offers for this key, for `--doctor`. 603/// Lists the models the provider offers for this key, for `--doctor`.
559pub fn models(cfg: &Config) -> Result<Vec<String>, Error> { 604pub fn models(cfg: &Config) -> Result<Vec<String>, Error> {
560 let agent: ureq::Agent = ureq::Agent::config_builder() 605 let agent = agent(cfg.system_ca);
561 .http_status_as_error(false)
562 .timeout_connect(Some(Duration::from_secs(10)))
563 .timeout_recv_response(Some(Duration::from_secs(20)))
564 .timeout_per_read(Some(Duration::from_secs(20)))
565 .build()
566 .into();
567 606
568 let url = format!("{}/models", cfg.base_url.trim_end_matches('/')); 607 let url = format!("{}/models", cfg.base_url.trim_end_matches('/'));
569 let mut response = agent 608 let mut response = agent
diff --git a/src/session.rs b/src/session.rs
index 881b1ed..8fc6d29 100644
--- a/src/session.rs
+++ b/src/session.rs
@@ -252,6 +252,31 @@ impl Session {
252 &self.path 252 &self.path
253 } 253 }
254 254
255 /// Rewrites the transcript from scratch: a fresh header plus the given
256 /// messages. This is the one sanctioned rewrite, called only by `/compact`
257 /// (see ADR 0003); everything else appends.
258 pub fn rewrite(&mut self, system: &Value, messages: &[Value]) -> Result<(), String> {
259 use std::io::{Seek, SeekFrom, Write};
260 self.file.set_len(0).map_err(|e| e.to_string())?;
261 self.file.seek(SeekFrom::Start(0)).map_err(|e| e.to_string())?;
262 let header = json!({
263 "t": "header",
264 "session": self.id,
265 "model": self.model,
266 "cwd": self.cwd,
267 "version": self.version,
268 "created": now_ms(),
269 "system": system,
270 });
271 writeln!(self.file, "{header}").map_err(|e| e.to_string())?;
272 for message in messages {
273 let mut line = message.as_object().cloned().unwrap_or_default();
274 line.insert("t".into(), json!("msg"));
275 writeln!(self.file, "{}", Value::Object(line)).map_err(|e| e.to_string())?;
276 }
277 self.file.flush().map_err(|e| e.to_string())
278 }
279
255 /// Records a model switch so `--list` shows what the last turn used. Appending 280 /// Records a model switch so `--list` shows what the last turn used. Appending
256 /// is legal; the header itself is never rewritten. 281 /// is legal; the header itself is never rewritten.
257 pub fn record_model(&mut self, model: &str) -> Result<(), String> { 282 pub fn record_model(&mut self, model: &str) -> Result<(), String> {
diff --git a/tests/config.rs b/tests/config.rs
new file mode 100644
index 0000000..05361d3
--- /dev/null
+++ b/tests/config.rs
@@ -0,0 +1,28 @@
1use agent686::config::Config;
2
3#[test]
4fn presets_fill_base_url_model_and_leniency() {
5 let ollama = Config::resolve_lenient(None, None, false, Some("ollama".into()), false, false);
6 assert_eq!(ollama.base_url, "http://localhost:11434/v1");
7 assert!(ollama.lenient, "local gateways default to lenient");
8
9 let opencode =
10 Config::resolve_lenient(None, None, false, Some("opencode-go".into()), false, false);
11 assert!(!opencode.lenient);
12 assert!(opencode.base_url.contains("opencode.ai"));
13
14 // An explicit --base-url beats the preset.
15 let explicit = Config::resolve_lenient(
16 None,
17 Some("http://127.0.0.1:9/v1".into()),
18 false,
19 Some("ollama".into()),
20 false,
21 false,
22 );
23 assert_eq!(explicit.base_url, "http://127.0.0.1:9/v1");
24
25 // Unknown preset falls back to the default endpoint.
26 let unknown = Config::resolve_lenient(None, None, false, Some("nope".into()), false, false);
27 assert!(unknown.base_url.contains("opencode.ai"));
28}
diff --git a/tests/git.rs b/tests/git.rs
new file mode 100644
index 0000000..19eced1
--- /dev/null
+++ b/tests/git.rs
@@ -0,0 +1,50 @@
1use std::fs;
2use std::path::PathBuf;
3use std::process::Command;
4
5use agent686::git;
6
7fn temp_dir(tag: &str) -> PathBuf {
8 let dir = std::env::temp_dir().join(format!("agent686-git-{tag}-{}", std::process::id()));
9 let _ = fs::remove_dir_all(&dir);
10 fs::create_dir_all(&dir).unwrap();
11 dir
12}
13
14fn repo(tag: &str) -> PathBuf {
15 let dir = temp_dir(tag);
16 for args in [
17 &["init", "-q"][..],
18 &["config", "user.email", "agent686@test"][..],
19 &["config", "user.name", "agent686"][..],
20 ] {
21 assert!(
22 Command::new("git").arg("-C").arg(&dir).args(args).status().unwrap().success()
23 );
24 }
25 dir
26}
27
28#[test]
29fn checkpoint_then_undo_restores_the_tree() {
30 let dir = repo("roundtrip");
31 fs::write(dir.join("a.txt"), "original\n").unwrap();
32
33 let sha = git::checkpoint(&dir).expect("in a repo");
34 assert!(!sha.is_empty());
35
36 // The turn mutates the tree.
37 fs::write(dir.join("a.txt"), "changed\n").unwrap();
38 fs::write(dir.join("b.txt"), "untracked\n").unwrap();
39
40 git::undo(&dir, &sha);
41
42 assert_eq!(fs::read_to_string(dir.join("a.txt")).unwrap(), "original\n");
43 assert!(!dir.join("b.txt").exists(), "untracked files must be removed");
44}
45
46#[test]
47fn checkpoint_is_none_outside_a_repo() {
48 let dir = temp_dir("norepo");
49 assert!(git::checkpoint(&dir).is_none());
50}
diff --git a/tests/loop.rs b/tests/loop.rs
index e913302..8c913cd 100644
--- a/tests/loop.rs
+++ b/tests/loop.rs
@@ -99,6 +99,8 @@ fn runs_a_tool_call_then_finishes_and_records_every_message() {
99 model: "test-model".into(), 99 model: "test-model".into(),
100 session: session.id.clone(), 100 session: session.id.clone(),
101 yolo: true, 101 yolo: true,
102 lenient: false,
103 system_ca: false,
102 }; 104 };
103 let mut history = agent::new_history(system); 105 let mut history = agent::new_history(system);
104 let mut approver = Approver::new(true); 106 let mut approver = Approver::new(true);
@@ -170,6 +172,8 @@ fn a_denied_tool_call_is_returned_as_data() {
170 model: "test-model".into(), 172 model: "test-model".into(),
171 session: session.id.clone(), 173 session: session.id.clone(),
172 yolo: false, 174 yolo: false,
175 lenient: false,
176 system_ca: false,
173 }; 177 };
174 let mut history = agent::new_history(system); 178 let mut history = agent::new_history(system);
175 // Not a terminal, so the approver must deny rather than block. 179 // Not a terminal, so the approver must deny rather than block.
@@ -238,6 +242,8 @@ fn aborting_between_tool_calls_answers_every_call() {
238 model: "test-model".into(), 242 model: "test-model".into(),
239 session: session.id.clone(), 243 session: session.id.clone(),
240 yolo: true, 244 yolo: true,
245 lenient: false,
246 system_ca: false,
241 }; 247 };
242 let mut history = agent::new_history(system); 248 let mut history = agent::new_history(system);
243 let mut approver = Approver::new(true); 249 let mut approver = Approver::new(true);
@@ -313,6 +319,8 @@ fn opening_a_session_with_unanswered_calls_repairs_it() {
313 model: "test-model".into(), 319 model: "test-model".into(),
314 session: session.id.clone(), 320 session: session.id.clone(),
315 yolo: true, 321 yolo: true,
322 lenient: false,
323 system_ca: false,
316 }; 324 };
317 let mut approver = Approver::new(true); 325 let mut approver = Approver::new(true);
318 agent::run_turn( 326 agent::run_turn(
@@ -367,6 +375,8 @@ fn an_empty_bash_call_is_never_approved() {
367 model: "test-model".into(), 375 model: "test-model".into(),
368 session: session.id.clone(), 376 session: session.id.clone(),
369 yolo: false, 377 yolo: false,
378 lenient: false,
379 system_ca: false,
370 }; 380 };
371 let mut history = agent::new_history(system); 381 let mut history = agent::new_history(system);
372 // Not a terminal: if this reaches the approval path it is denied, which the 382 // Not a terminal: if this reaches the approval path it is denied, which the
@@ -421,6 +431,8 @@ fn a_tool_call_with_no_arguments_is_reported_to_the_model() {
421 model: "test-model".into(), 431 model: "test-model".into(),
422 session: session.id.clone(), 432 session: session.id.clone(),
423 yolo: false, 433 yolo: false,
434 lenient: false,
435 system_ca: false,
424 }; 436 };
425 let mut history = agent::new_history(system); 437 let mut history = agent::new_history(system);
426 let mut approver = Approver::new(false); 438 let mut approver = Approver::new(false);
@@ -475,6 +487,8 @@ fn a_wrong_argument_key_names_both_keys() {
475 model: "test-model".into(), 487 model: "test-model".into(),
476 session: session.id.clone(), 488 session: session.id.clone(),
477 yolo: false, 489 yolo: false,
490 lenient: false,
491 system_ca: false,
478 }; 492 };
479 let mut history = agent::new_history(system); 493 let mut history = agent::new_history(system);
480 let mut approver = Approver::new(false); 494 let mut approver = Approver::new(false);
diff --git a/tests/mock.rs b/tests/mock.rs
index 7e076e3..fdbaca4 100644
--- a/tests/mock.rs
+++ b/tests/mock.rs
@@ -74,6 +74,8 @@ fn config(base_url: String) -> Config {
74 model: "test-model".into(), 74 model: "test-model".into(),
75 session: "testsession".into(), 75 session: "testsession".into(),
76 yolo: true, 76 yolo: true,
77 lenient: false,
78 system_ca: false,
77 } 79 }
78} 80}
79 81
diff --git a/tests/sessions.rs b/tests/sessions.rs
index b381888..4f8ebd5 100644
--- a/tests/sessions.rs
+++ b/tests/sessions.rs
@@ -176,3 +176,26 @@ fn last_reply_prefers_content_and_falls_back_to_reasoning() {
176 assert!(reply.content.is_empty()); 176 assert!(reply.content.is_empty());
177 assert_eq!(reply.reasoning, "thoughts"); 177 assert_eq!(reply.reasoning, "thoughts");
178} 178}
179
180#[test]
181fn rewrite_replaces_messages_but_keeps_the_header() {
182 let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
183 let dir = temp_dir("rewrite");
184 std::env::set_var("AGENT686_DATA", &dir);
185
186 let system = json!({ "role": "system", "content": "sys" });
187 let mut session = Session::create_as("rw".into(), "m", &system).unwrap();
188 session
189 .append(&json!({ "role": "user", "content": "old turn" }), None)
190 .unwrap();
191
192 let summary = json!({ "role": "user", "content": "the summary" });
193 session.rewrite(&system, &[summary]).unwrap();
194 drop(session);
195
196 let (opened, system_back, messages) = Session::open("rw").unwrap();
197 assert_eq!(opened.id, "rw", "id preserved");
198 assert_eq!(system_back["content"], "sys", "system preserved");
199 assert_eq!(messages.len(), 1, "old messages gone: {messages:#?}");
200 assert_eq!(messages[0]["content"], "the summary");
201}