diff options
| -rw-r--r-- | .gitignore | 1 | ||||
| -rw-r--r-- | CONTEXT.md | 30 | ||||
| -rw-r--r-- | Cargo.lock | 437 | ||||
| -rw-r--r-- | Cargo.toml | 16 | ||||
| -rw-r--r-- | docs/PLAN.md | 137 | ||||
| -rw-r--r-- | docs/adr/0001-dynamic-glibc-i686.md | 49 | ||||
| -rw-r--r-- | docs/adr/0002-append-only-sessions.md | 51 | ||||
| -rwxr-xr-x | scripts/check-glibc.sh | 35 | ||||
| -rwxr-xr-x | scripts/mock-provider.py | 86 | ||||
| -rw-r--r-- | src/agent.rs | 67 | ||||
| -rw-r--r-- | src/config.rs | 67 | ||||
| -rw-r--r-- | src/lib.rs | 5 | ||||
| -rw-r--r-- | src/main.rs | 136 | ||||
| -rw-r--r-- | src/provider.rs | 319 | ||||
| -rw-r--r-- | src/session.rs | 39 | ||||
| -rw-r--r-- | src/ui.rs | 75 | ||||
| -rw-r--r-- | tests/mock.rs | 192 | ||||
| -rw-r--r-- | tests/sse.rs | 40 |
18 files changed, 1782 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore | |||
| @@ -0,0 +1 @@ | |||
| /target | |||
diff --git a/CONTEXT.md b/CONTEXT.md new file mode 100644 index 0000000..e48cb1a --- /dev/null +++ b/CONTEXT.md | |||
| @@ -0,0 +1,30 @@ | |||
| 1 | # Context | ||
| 2 | |||
| 3 | ## Language | ||
| 4 | |||
| 5 | **Provider** — a service that serves models over HTTP, with its own credential and | ||
| 6 | request/response shape. v1 supports exactly one: **OpenCode Go** (called | ||
| 7 | `opencode-go` in OpenCode's vocabulary), an OpenAI-compatible gateway. | ||
| 8 | |||
| 9 | **Model** — a model id served by a provider, e.g. `deepseek-v4.1-flash`. A model | ||
| 10 | is not a provider, and not a config profile. The same model may be reachable | ||
| 11 | through more than one wire protocol. | ||
| 12 | |||
| 13 | **Session** — one conversation, identified by an id that is stable for the life of | ||
| 14 | that conversation and survives the process exiting. Continuing a session reuses | ||
| 15 | its id; starting a new conversation gets a new one. A session is not a run, not a | ||
| 16 | process, and not a file. | ||
| 17 | |||
| 18 | **Turn** — one user message plus every step the agent takes until the model | ||
| 19 | answers without tool calls. A turn is the unit of interruption: aborting a turn | ||
| 20 | leaves the session and its history intact. | ||
| 21 | |||
| 22 | **Step** — one request/response cycle with the model within a turn. A turn is one | ||
| 23 | or more steps. | ||
| 24 | |||
| 25 | **Tool call** — the model asking the harness to run one tool with arguments. A | ||
| 26 | tool call that fails, is denied, or produces no output is still a completed tool | ||
| 27 | call; its outcome is returned to the model as a result, not raised as an error. | ||
| 28 | |||
| 29 | **Approval** — the human's permission for a tool call to run. An approval is | ||
| 30 | scoped to a session, not to a turn: once granted, it holds until the session ends. | ||
diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..2af945a --- /dev/null +++ b/Cargo.lock | |||
| @@ -0,0 +1,437 @@ | |||
| 1 | # This file is automatically @generated by Cargo. | ||
| 2 | # It is not intended for manual editing. | ||
| 3 | version = 4 | ||
| 4 | |||
| 5 | [[package]] | ||
| 6 | name = "adler2" | ||
| 7 | version = "2.0.1" | ||
| 8 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 9 | checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" | ||
| 10 | |||
| 11 | [[package]] | ||
| 12 | name = "agent686" | ||
| 13 | version = "0.1.0" | ||
| 14 | dependencies = [ | ||
| 15 | "serde", | ||
| 16 | "serde_json", | ||
| 17 | "ureq", | ||
| 18 | ] | ||
| 19 | |||
| 20 | [[package]] | ||
| 21 | name = "base64" | ||
| 22 | version = "0.23.1" | ||
| 23 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 24 | checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" | ||
| 25 | |||
| 26 | [[package]] | ||
| 27 | name = "bytes" | ||
| 28 | version = "1.12.1" | ||
| 29 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 30 | checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" | ||
| 31 | |||
| 32 | [[package]] | ||
| 33 | name = "cc" | ||
| 34 | version = "1.11.2" | ||
| 35 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 36 | checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" | ||
| 37 | dependencies = [ | ||
| 38 | "find-msvc-tools", | ||
| 39 | "shlex", | ||
| 40 | ] | ||
| 41 | |||
| 42 | [[package]] | ||
| 43 | name = "cfg-if" | ||
| 44 | version = "1.0.5" | ||
| 45 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 46 | checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" | ||
| 47 | |||
| 48 | [[package]] | ||
| 49 | name = "crc32fast" | ||
| 50 | version = "1.5.5" | ||
| 51 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 52 | checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" | ||
| 53 | dependencies = [ | ||
| 54 | "cfg-if", | ||
| 55 | ] | ||
| 56 | |||
| 57 | [[package]] | ||
| 58 | name = "find-msvc-tools" | ||
| 59 | version = "0.1.15" | ||
| 60 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 61 | checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" | ||
| 62 | |||
| 63 | [[package]] | ||
| 64 | name = "flate2" | ||
| 65 | version = "1.1.11" | ||
| 66 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 67 | checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" | ||
| 68 | dependencies = [ | ||
| 69 | "crc32fast", | ||
| 70 | "miniz_oxide", | ||
| 71 | "zlib-rs", | ||
| 72 | ] | ||
| 73 | |||
| 74 | [[package]] | ||
| 75 | name = "getrandom" | ||
| 76 | version = "0.2.17" | ||
| 77 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 78 | checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" | ||
| 79 | dependencies = [ | ||
| 80 | "cfg-if", | ||
| 81 | "libc", | ||
| 82 | "wasi", | ||
| 83 | ] | ||
| 84 | |||
| 85 | [[package]] | ||
| 86 | name = "http" | ||
| 87 | version = "1.5.0" | ||
| 88 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 89 | checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" | ||
| 90 | dependencies = [ | ||
| 91 | "bytes", | ||
| 92 | "itoa", | ||
| 93 | ] | ||
| 94 | |||
| 95 | [[package]] | ||
| 96 | name = "httparse" | ||
| 97 | version = "1.10.1" | ||
| 98 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 99 | checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" | ||
| 100 | |||
| 101 | [[package]] | ||
| 102 | name = "itoa" | ||
| 103 | version = "1.0.19" | ||
| 104 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 105 | checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" | ||
| 106 | |||
| 107 | [[package]] | ||
| 108 | name = "libc" | ||
| 109 | version = "0.2.191" | ||
| 110 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 111 | checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" | ||
| 112 | |||
| 113 | [[package]] | ||
| 114 | name = "log" | ||
| 115 | version = "0.4.35" | ||
| 116 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 117 | checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" | ||
| 118 | |||
| 119 | [[package]] | ||
| 120 | name = "memchr" | ||
| 121 | version = "2.8.3" | ||
| 122 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 123 | checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" | ||
| 124 | |||
| 125 | [[package]] | ||
| 126 | name = "miniz_oxide" | ||
| 127 | version = "0.9.1" | ||
| 128 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 129 | checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" | ||
| 130 | dependencies = [ | ||
| 131 | "adler2", | ||
| 132 | "simd-adler32", | ||
| 133 | ] | ||
| 134 | |||
| 135 | [[package]] | ||
| 136 | name = "once_cell" | ||
| 137 | version = "1.21.4" | ||
| 138 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 139 | checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" | ||
| 140 | |||
| 141 | [[package]] | ||
| 142 | name = "percent-encoding" | ||
| 143 | version = "2.3.2" | ||
| 144 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 145 | checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" | ||
| 146 | |||
| 147 | [[package]] | ||
| 148 | name = "proc-macro2" | ||
| 149 | version = "1.0.107" | ||
| 150 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 151 | checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" | ||
| 152 | dependencies = [ | ||
| 153 | "unicode-ident", | ||
| 154 | ] | ||
| 155 | |||
| 156 | [[package]] | ||
| 157 | name = "quote" | ||
| 158 | version = "1.0.47" | ||
| 159 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 160 | checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" | ||
| 161 | dependencies = [ | ||
| 162 | "proc-macro2", | ||
| 163 | ] | ||
| 164 | |||
| 165 | [[package]] | ||
| 166 | name = "ring" | ||
| 167 | version = "0.17.14" | ||
| 168 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 169 | checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" | ||
| 170 | dependencies = [ | ||
| 171 | "cc", | ||
| 172 | "cfg-if", | ||
| 173 | "getrandom", | ||
| 174 | "libc", | ||
| 175 | "untrusted", | ||
| 176 | "windows-sys", | ||
| 177 | ] | ||
| 178 | |||
| 179 | [[package]] | ||
| 180 | name = "rustls" | ||
| 181 | version = "0.23.46" | ||
| 182 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 183 | checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" | ||
| 184 | dependencies = [ | ||
| 185 | "log", | ||
| 186 | "once_cell", | ||
| 187 | "ring", | ||
| 188 | "rustls-pki-types", | ||
| 189 | "rustls-webpki", | ||
| 190 | "subtle", | ||
| 191 | "zeroize", | ||
| 192 | ] | ||
| 193 | |||
| 194 | [[package]] | ||
| 195 | name = "rustls-pki-types" | ||
| 196 | version = "1.16.0" | ||
| 197 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 198 | checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" | ||
| 199 | dependencies = [ | ||
| 200 | "zeroize", | ||
| 201 | ] | ||
| 202 | |||
| 203 | [[package]] | ||
| 204 | name = "rustls-webpki" | ||
| 205 | version = "0.103.17" | ||
| 206 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 207 | checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" | ||
| 208 | dependencies = [ | ||
| 209 | "ring", | ||
| 210 | "rustls-pki-types", | ||
| 211 | "untrusted", | ||
| 212 | ] | ||
| 213 | |||
| 214 | [[package]] | ||
| 215 | name = "serde" | ||
| 216 | version = "1.0.229" | ||
| 217 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 218 | checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" | ||
| 219 | dependencies = [ | ||
| 220 | "serde_core", | ||
| 221 | "serde_derive", | ||
| 222 | ] | ||
| 223 | |||
| 224 | [[package]] | ||
| 225 | name = "serde_core" | ||
| 226 | version = "1.0.229" | ||
| 227 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 228 | checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" | ||
| 229 | dependencies = [ | ||
| 230 | "serde_derive", | ||
| 231 | ] | ||
| 232 | |||
| 233 | [[package]] | ||
| 234 | name = "serde_derive" | ||
| 235 | version = "1.0.229" | ||
| 236 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 237 | checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" | ||
| 238 | dependencies = [ | ||
| 239 | "proc-macro2", | ||
| 240 | "quote", | ||
| 241 | "syn", | ||
| 242 | ] | ||
| 243 | |||
| 244 | [[package]] | ||
| 245 | name = "serde_json" | ||
| 246 | version = "1.0.154" | ||
| 247 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 248 | checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" | ||
| 249 | dependencies = [ | ||
| 250 | "itoa", | ||
| 251 | "memchr", | ||
| 252 | "serde", | ||
| 253 | "serde_core", | ||
| 254 | "zmij", | ||
| 255 | ] | ||
| 256 | |||
| 257 | [[package]] | ||
| 258 | name = "shlex" | ||
| 259 | version = "2.0.1" | ||
| 260 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 261 | checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" | ||
| 262 | |||
| 263 | [[package]] | ||
| 264 | name = "simd-adler32" | ||
| 265 | version = "0.3.10" | ||
| 266 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 267 | checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" | ||
| 268 | |||
| 269 | [[package]] | ||
| 270 | name = "subtle" | ||
| 271 | version = "2.6.1" | ||
| 272 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 273 | checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" | ||
| 274 | |||
| 275 | [[package]] | ||
| 276 | name = "syn" | ||
| 277 | version = "3.0.10" | ||
| 278 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 279 | checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" | ||
| 280 | dependencies = [ | ||
| 281 | "proc-macro2", | ||
| 282 | "quote", | ||
| 283 | "unicode-ident", | ||
| 284 | ] | ||
| 285 | |||
| 286 | [[package]] | ||
| 287 | name = "unicode-ident" | ||
| 288 | version = "1.0.27" | ||
| 289 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 290 | checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" | ||
| 291 | |||
| 292 | [[package]] | ||
| 293 | name = "untrusted" | ||
| 294 | version = "0.9.0" | ||
| 295 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 296 | checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" | ||
| 297 | |||
| 298 | [[package]] | ||
| 299 | name = "ureq" | ||
| 300 | version = "3.5.2" | ||
| 301 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 302 | checksum = "3ac5cecf619ca81f66a96482db09687c9f7465af65f4300a8c30cca05bd5a59d" | ||
| 303 | dependencies = [ | ||
| 304 | "base64", | ||
| 305 | "flate2", | ||
| 306 | "log", | ||
| 307 | "percent-encoding", | ||
| 308 | "rustls", | ||
| 309 | "rustls-pki-types", | ||
| 310 | "ureq-proto", | ||
| 311 | "utf8-zero", | ||
| 312 | "webpki-roots", | ||
| 313 | ] | ||
| 314 | |||
| 315 | [[package]] | ||
| 316 | name = "ureq-proto" | ||
| 317 | version = "0.7.1" | ||
| 318 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 319 | checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3" | ||
| 320 | dependencies = [ | ||
| 321 | "base64", | ||
| 322 | "http", | ||
| 323 | "httparse", | ||
| 324 | "log", | ||
| 325 | ] | ||
| 326 | |||
| 327 | [[package]] | ||
| 328 | name = "utf8-zero" | ||
| 329 | version = "0.8.1" | ||
| 330 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 331 | checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" | ||
| 332 | |||
| 333 | [[package]] | ||
| 334 | name = "wasi" | ||
| 335 | version = "0.11.1+wasi-snapshot-preview1" | ||
| 336 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 337 | checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" | ||
| 338 | |||
| 339 | [[package]] | ||
| 340 | name = "webpki-roots" | ||
| 341 | version = "1.0.12" | ||
| 342 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 343 | checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" | ||
| 344 | dependencies = [ | ||
| 345 | "rustls-pki-types", | ||
| 346 | ] | ||
| 347 | |||
| 348 | [[package]] | ||
| 349 | name = "windows-sys" | ||
| 350 | version = "0.52.0" | ||
| 351 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 352 | checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" | ||
| 353 | dependencies = [ | ||
| 354 | "windows-targets", | ||
| 355 | ] | ||
| 356 | |||
| 357 | [[package]] | ||
| 358 | name = "windows-targets" | ||
| 359 | version = "0.52.6" | ||
| 360 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 361 | checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" | ||
| 362 | dependencies = [ | ||
| 363 | "windows_aarch64_gnullvm", | ||
| 364 | "windows_aarch64_msvc", | ||
| 365 | "windows_i686_gnu", | ||
| 366 | "windows_i686_gnullvm", | ||
| 367 | "windows_i686_msvc", | ||
| 368 | "windows_x86_64_gnu", | ||
| 369 | "windows_x86_64_gnullvm", | ||
| 370 | "windows_x86_64_msvc", | ||
| 371 | ] | ||
| 372 | |||
| 373 | [[package]] | ||
| 374 | name = "windows_aarch64_gnullvm" | ||
| 375 | version = "0.52.6" | ||
| 376 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 377 | checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" | ||
| 378 | |||
| 379 | [[package]] | ||
| 380 | name = "windows_aarch64_msvc" | ||
| 381 | version = "0.52.6" | ||
| 382 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 383 | checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" | ||
| 384 | |||
| 385 | [[package]] | ||
| 386 | name = "windows_i686_gnu" | ||
| 387 | version = "0.52.6" | ||
| 388 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 389 | checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" | ||
| 390 | |||
| 391 | [[package]] | ||
| 392 | name = "windows_i686_gnullvm" | ||
| 393 | version = "0.52.6" | ||
| 394 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 395 | checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" | ||
| 396 | |||
| 397 | [[package]] | ||
| 398 | name = "windows_i686_msvc" | ||
| 399 | version = "0.52.6" | ||
| 400 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 401 | checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" | ||
| 402 | |||
| 403 | [[package]] | ||
| 404 | name = "windows_x86_64_gnu" | ||
| 405 | version = "0.52.6" | ||
| 406 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 407 | checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" | ||
| 408 | |||
| 409 | [[package]] | ||
| 410 | name = "windows_x86_64_gnullvm" | ||
| 411 | version = "0.52.6" | ||
| 412 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 413 | checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" | ||
| 414 | |||
| 415 | [[package]] | ||
| 416 | name = "windows_x86_64_msvc" | ||
| 417 | version = "0.52.6" | ||
| 418 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 419 | checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" | ||
| 420 | |||
| 421 | [[package]] | ||
| 422 | name = "zeroize" | ||
| 423 | version = "1.9.1" | ||
| 424 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 425 | checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" | ||
| 426 | |||
| 427 | [[package]] | ||
| 428 | name = "zlib-rs" | ||
| 429 | version = "0.6.8" | ||
| 430 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 431 | checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" | ||
| 432 | |||
| 433 | [[package]] | ||
| 434 | name = "zmij" | ||
| 435 | version = "1.0.23" | ||
| 436 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 437 | checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" | ||
diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..4806119 --- /dev/null +++ b/Cargo.toml | |||
| @@ -0,0 +1,16 @@ | |||
| 1 | [package] | ||
| 2 | name = "agent686" | ||
| 3 | version = "0.1.0" | ||
| 4 | edition = "2021" | ||
| 5 | description = "A small coding agent for a 32-bit Debian box" | ||
| 6 | publish = false | ||
| 7 | |||
| 8 | [dependencies] | ||
| 9 | serde = { version = "1", features = ["derive"] } | ||
| 10 | serde_json = "1" | ||
| 11 | ureq = { version = "3", features = ["rustls"] } | ||
| 12 | |||
| 13 | [profile.release] | ||
| 14 | strip = true | ||
| 15 | lto = true | ||
| 16 | codegen-units = 1 | ||
diff --git a/docs/PLAN.md b/docs/PLAN.md new file mode 100644 index 0000000..2766664 --- /dev/null +++ b/docs/PLAN.md | |||
| @@ -0,0 +1,137 @@ | |||
| 1 | # agent686 — v1 plan | ||
| 2 | |||
| 3 | A small coding agent for a Debian 12 i386 box (2 cores, 4 GB). Single binary, | ||
| 4 | line-mode, six tools. Built for understanding, not parity with anything. | ||
| 5 | |||
| 6 | ## Fixed constraints | ||
| 7 | |||
| 8 | | | | | ||
| 9 | |---|---| | ||
| 10 | | Target | Debian 12 i386, glibc 2.36, 2 cores, 4 GB | | ||
| 11 | | Build | `i686-unknown-linux-gnu`, dynamic glibc (see ADR 0001) | | ||
| 12 | | Dev host | x86-64, `gcc-multilib`, `i686` + `i686-unknown-linux-musl` targets | | ||
| 13 | | Provider | OpenCode Go — `https://opencode.ai/inference/go/openai/v1`, `chat/completions` | | ||
| 14 | | Auth | `OPENCODE_API_KEY`, else `~/.config/agent686/key` (600 perms) | | ||
| 15 | | Concurrency | blocking, single-threaded; `ureq` + `rustls`/ring; no async runtime | | ||
| 16 | |||
| 17 | ## Decisions | ||
| 18 | |||
| 19 | - **One provider, one wire protocol.** `chat/completions` only. Console translates, | ||
| 20 | so Claude/Gemini/GPT models are reachable through it. No `/responses`, no | ||
| 21 | `/anthropic/v1/messages`, no provider abstraction. | ||
| 22 | - **Client identity.** `User-Agent: agent686/<version>`, and a stable | ||
| 23 | `x-opencode-session` header carrying the session id on every request. | ||
| 24 | - **Six tools.** `read` (numbered lines, offset/limit, 2000-line cap), `write` | ||
| 25 | (no implicit `mkdir`), `edit` (exact match, must be unique, else fail with match | ||
| 26 | count and line numbers), `bash` (fresh shell each call, `cwd` param, 120 s | ||
| 27 | timeout, capped output, exit code), `grep`, `glob`. All native — no dependence | ||
| 28 | on `rg` being installed. | ||
| 29 | - **Approval.** Reads free. First `write`/`edit` of a session prompts with a | ||
| 30 | unified diff and offers "always" (session-scoped). Every `bash` call prompts | ||
| 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 | ||
| 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. | ||
| 35 | - **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 | - **Sessions.** Append-only JSONL of wire messages (see ADR 0002). No compaction, | ||
| 38 | no truncation, no summarisation. Overflow is the provider's 400. | ||
| 39 | - **Prompt.** Snapshot at session start: fixed system prompt, a 3-line | ||
| 40 | environment block (cwd, platform, git branch), and `AGENTS.md` from cwd up to | ||
| 41 | the git root. Frozen for the session; mtime change prints a notice only. | ||
| 42 | - **UI.** Line-mode. ANSI only when stdout is a TTY. Plain `read_line` plus | ||
| 43 | `/paste` (reads until a lone `.` or EOF). No alt-screen, no raw mode, no | ||
| 44 | history, no markdown rendering, no syntax highlighting. | ||
| 45 | - **Ctrl-C.** SIGINT handler sets a flag; the stream loop closes the socket and | ||
| 46 | ends the turn. Second Ctrl-C exits. | ||
| 47 | - **No model metadata.** No cost display, no pre-flight context check. Token | ||
| 48 | counts shown only if the gateway returns usage; `opencode.allowance` shown if | ||
| 49 | present. | ||
| 50 | - **Dependencies.** `serde`, `serde_json`, `ureq` (rustls). Nothing else unless | ||
| 51 | justified. Tests use `std` only. | ||
| 52 | |||
| 53 | ## Non-goals for v1 | ||
| 54 | |||
| 55 | Subagents, MCP, LSP, plugins/hooks, multiple providers, Anthropic-native wire | ||
| 56 | format, image input, RAG, worktrees, session sharing, syntax highlighting, | ||
| 57 | full-screen TUI, undo/snapshots (git is the undo), config knobs for step limits. | ||
| 58 | |||
| 59 | ## Milestones | ||
| 60 | |||
| 61 | Each milestone is done when it runs, not when it compiles. | ||
| 62 | |||
| 63 | **M0 — Skeleton and mock provider.** ✅ Done 2026-11-15. | ||
| 64 | |||
| 65 | Crate, config load, request builder, SSE parser, one turn printed to stdout, no | ||
| 66 | tools. Mock provider over `std::net::TcpListener` in `tests/mock.rs` (no HTTP | ||
| 67 | crate) replaying canned SSE: text deltas, a split tool call, a 401. Parser tests | ||
| 68 | feed the stream one byte at a time, so splits inside SSE lines and inside | ||
| 69 | multi-byte UTF-8 are covered. | ||
| 70 | |||
| 71 | Verified: `cargo test` 8/8; 2.0 MB stripped i686 binary, max symbol | ||
| 72 | `GLIBC_2.34`, runs inside `debian:12` for `linux/386` against the mock and | ||
| 73 | streams correctly; `scripts/check-glibc.sh` passes and fails as expected; | ||
| 74 | `scripts/mock-provider.py` gives a no-key provider for manual work. | ||
| 75 | |||
| 76 | **M1 — Sessions, status line, abort.** JSONL append/load, session id, `--continue`, | ||
| 77 | `--resume <id>`, status line, SIGINT handling. | ||
| 78 | *Done when:* a turn survives `kill -9` between steps, `--continue` resumes it, and | ||
| 79 | Ctrl-C returns the prompt without losing the transcript. | ||
| 80 | |||
| 81 | **M2 — Read-side tools and edits.** `read`, `write`, `edit`, `grep`, `glob`, the | ||
| 82 | agent loop, tool-call accumulation, the approval prompt with diff. | ||
| 83 | *Done when:* a canned mock session writes a C file, greps it, edits it, and the | ||
| 84 | transcript replays byte-identically. | ||
| 85 | |||
| 86 | **M3 — `bash`.** Command execution, timeout, output capping, per-call approval, | ||
| 87 | head/tail rendering. | ||
| 88 | *Done when:* the mock session compiles the C file and handles a non-zero exit as | ||
| 89 | data rather than an error. | ||
| 90 | |||
| 91 | **M4 — Prompt and input.** System prompt, environment block, `AGENTS.md` | ||
| 92 | snapshot, `/paste`, TTY detection, real-API smoke test. | ||
| 93 | *Done when:* one real turn against OpenCode Go works end to end. | ||
| 94 | |||
| 95 | **M5 — Target gate.** `scripts/check-glibc.sh` (max symbol version ≤ 2.36), | ||
| 96 | `cargo check --target i686` clean, release run inside | ||
| 97 | `docker run --platform linux/386 debian:12`, binary copied to the i386 box. | ||
| 98 | *Done when:* the acceptance test runs there. | ||
| 99 | |||
| 100 | ## Acceptance test (v1) | ||
| 101 | |||
| 102 | > "Make a simple calculator in C" — run on the i386 box, from an empty directory. | ||
| 103 | |||
| 104 | Exercises `write` (create files), `bash` (compile, run), `read` (inspect what it | ||
| 105 | wrote), and terminates on its own. Success is: it compiles, it runs, it does | ||
| 106 | addition and division, and it did not need more than a handful of files. | ||
| 107 | |||
| 108 | ## Layout | ||
| 109 | |||
| 110 | ``` | ||
| 111 | src/main.rs args, mode selection, exit codes | ||
| 112 | src/config.rs TOML-free config if possible; env precedence CLI > env > file | ||
| 113 | src/provider.rs request construction, ureq call, SSE parsing | ||
| 114 | src/session.rs id, JSONL append/load, replay | ||
| 115 | src/agent.rs turn/step loop, tool dispatch, approval hooks | ||
| 116 | src/tools/ read, write, edit, bash, grep, glob | ||
| 117 | src/ui.rs streaming render, diffs, approval prompt, status line, /paste | ||
| 118 | tests/mock.rs mock provider over std TcpListener | ||
| 119 | scripts/check-glibc.sh | ||
| 120 | ``` | ||
| 121 | |||
| 122 | Input is kept behind a single `read_input() -> Option<String>` function so a | ||
| 123 | raw-mode editor with history can replace it later without touching the loop. | ||
| 124 | |||
| 125 | ## Open questions to settle against the live API | ||
| 126 | |||
| 127 | Blocked on a fresh `OPENCODE_API_KEY` (the stored one returns `api_key_expired`). | ||
| 128 | |||
| 129 | 1. Is `stream_options: {"include_usage": true}` honoured, and does usage arrive in | ||
| 130 | the final chunk? | ||
| 131 | 2. Exact shape and location of `opencode.allowance`; which unit it is in. | ||
| 132 | 3. Is `reasoning_content` the delta field name across all reasoning models, or | ||
| 133 | only DeepSeek-derived ones? | ||
| 134 | 4. Does the gateway accept `reasoning_effort`, or is reasoning configured | ||
| 135 | elsewhere? | ||
| 136 | 5. Error body shape for context overflow, to map it to "start a new session". | ||
| 137 | 6. Whether `x-opencode-session` has format constraints (opaque vs UUID). | ||
diff --git a/docs/adr/0001-dynamic-glibc-i686.md b/docs/adr/0001-dynamic-glibc-i686.md new file mode 100644 index 0000000..df791e0 --- /dev/null +++ b/docs/adr/0001-dynamic-glibc-i686.md | |||
| @@ -0,0 +1,49 @@ | |||
| 1 | # 0001 — Ship a dynamically linked glibc i686 binary, not a static one | ||
| 2 | |||
| 3 | **Status:** accepted | ||
| 4 | |||
| 5 | ## Context | ||
| 6 | |||
| 7 | The target is a Debian 12 i386 machine: glibc 2.36, 2 cores, 4 GB RAM. The | ||
| 8 | development machine is x86-64 with `gcc-multilib` and the `i686-unknown-linux-gnu` | ||
| 9 | Rust target installed. | ||
| 10 | |||
| 11 | "Single static binary" was the original plan, on the assumption that it removes | ||
| 12 | all runtime dependencies. Two measurements on the development machine contradict | ||
| 13 | that: | ||
| 14 | |||
| 15 | 1. **Static glibc cannot use NSS modules, and crashes trying.** An i686 binary | ||
| 16 | built with `+crt-static` segfaults inside `libnss_resolve.so.2` at | ||
| 17 | `getaddrinfo()`, because the host's `nsswitch.conf` lists `resolve` before | ||
| 18 | `files`. Static glibc is documented as unable to load NSS modules; on any | ||
| 19 | systemd-resolved machine, DNS from a static glibc binary is a SIGSEGV. The | ||
| 20 | failure mode is invisible at build time and appears on the first network call. | ||
| 21 | 2. **Static musl requires a C-free dependency tree, which we do not have.** | ||
| 22 | `ring` (pulled in by `rustls`/`ureq`) compiles C and assembly; cc-rs invokes | ||
| 23 | `musl-gcc -m32` and fails because no 32-bit musl sysroot exists here. Making | ||
| 24 | musl work means adding an `i686-linux-musl` cross toolchain, or swapping the | ||
| 25 | TLS stack for a pre-1.0 pure-Rust provider. | ||
| 26 | |||
| 27 | The dynamic i686 build works unchanged: TLS handshake, DNS, JSON parse, exit 0. | ||
| 28 | Its highest required symbol version is `GLIBC_2.34`, and it runs correctly inside | ||
| 29 | `docker run --platform linux/386 debian:12` (glibc 2.36). | ||
| 30 | |||
| 31 | ## Decision | ||
| 32 | |||
| 33 | Build `i686-unknown-linux-gnu` **dynamically linked against glibc**, using the | ||
| 34 | host's 32-bit toolchain. Do not use `+crt-static`. Gate every release on a check | ||
| 35 | that the maximum required symbol version is `<= GLIBC_2.36`, and verify releases | ||
| 36 | by running them inside the `linux/386 debian:12` container before copying to the | ||
| 37 | target machine. | ||
| 38 | |||
| 39 | ## Consequences | ||
| 40 | |||
| 41 | - The binary is ~3 MB stripped and needs the target's glibc to be at least 2.34. | ||
| 42 | Debian 12 provides 2.36, so there is headroom, but a future dependency can pull | ||
| 43 | in newer symbol versions. The `readelf` ceiling check is mandatory, not | ||
| 44 | advisory — without it the failure appears only on the i686 machine. | ||
| 45 | - Distribution is a binary plus its glibc, not a single file to `scp` anywhere. | ||
| 46 | Accepted: the target is a known Debian 12 box, not an unknown fleet. | ||
| 47 | - `ring`/`rustls` stay available, so the dependency tree is unconstrained. | ||
| 48 | - If the target later turns out to be older than glibc 2.34, or a second target | ||
| 49 | appears with an older libc, this decision reopens and musl becomes the path. | ||
diff --git a/docs/adr/0002-append-only-sessions.md b/docs/adr/0002-append-only-sessions.md new file mode 100644 index 0000000..2acfbd4 --- /dev/null +++ b/docs/adr/0002-append-only-sessions.md | |||
| @@ -0,0 +1,51 @@ | |||
| 1 | # 0002 — Sessions are append-only wire transcripts; history is never rewritten | ||
| 2 | |||
| 3 | **Status:** accepted | ||
| 4 | |||
| 5 | ## Context | ||
| 6 | |||
| 7 | Two forces meet in the session format. | ||
| 8 | |||
| 9 | The first is cost. The provider bills cached prompt reads at roughly 1/50th of | ||
| 10 | input price (DeepSeek V4.1 Flash: $0.003/M cached vs $0.15/M input). Cache hits | ||
| 11 | depend on the request prefix being byte-identical to the previous request. The | ||
| 12 | prefix is the system prompt, the tool schemas, and the message history — so any | ||
| 13 | edit to an earlier message invalidates the cache for everything after it and | ||
| 14 | re-bills the whole context. | ||
| 15 | |||
| 16 | The second is fidelity. The model's next step depends on what it actually said | ||
| 17 | and what the tools actually returned, so the stored history has to reproduce the | ||
| 18 | wire messages exactly: `reasoning_content` from a reasoning model must not be | ||
| 19 | sent back (wasted tokens at best, a 400 at worst on DeepSeek-style backends), | ||
| 20 | and tool-call arguments must round-trip as the original JSON string rather than | ||
| 21 | being parsed and re-serialised, which can reorder keys and change whitespace. | ||
| 22 | |||
| 23 | Summarising old turns, truncating old tool output, and dropping old messages all | ||
| 24 | solve context exhaustion, and all of them rewrite the prefix. They are | ||
| 25 | incompatible with cache stability. | ||
| 26 | |||
| 27 | ## Decision | ||
| 28 | |||
| 29 | Store each session as **append-only JSONL of wire-level messages**, replayed | ||
| 30 | verbatim. No compaction, no truncation, no summarisation, no sliding window. | ||
| 31 | |||
| 32 | - `reasoning_content` is stored (for the human to read) and stripped on replay. | ||
| 33 | - Tool-call arguments are stored and replayed as the original JSON string. | ||
| 34 | - The system prompt, environment block, and tool schemas are frozen at session | ||
| 35 | start and built from fixed-order structs — never a `HashMap`, never containing | ||
| 36 | session-varying values. | ||
| 37 | - When the conversation exceeds the model's context window, the provider returns | ||
| 38 | an error, the turn ends, and the user is told to start a new session. | ||
| 39 | |||
| 40 | ## Consequences | ||
| 41 | |||
| 42 | - Prompt caching stays warm for the life of a session, which is the dominant cost | ||
| 43 | factor on a $10/month plan. | ||
| 44 | - Resuming a session is exact: replay the file and continue. No reconstruction | ||
| 45 | logic, no "the summary forgot the decision from ten turns ago". | ||
| 46 | - Long sessions have a hard ceiling and cannot be extended. The only remedy is a | ||
| 47 | new session, which loses the conversation. Accepted: with 128k-class windows | ||
| 48 | this is a rare event, and the failure is loud rather than silent. | ||
| 49 | - Session files grow without bound and are never garbage-collected. Accepted. | ||
| 50 | - Any future feature that wants to show a compacted view of history must render | ||
| 51 | it separately from what is sent to the provider. The transcript is the truth. | ||
diff --git a/scripts/check-glibc.sh b/scripts/check-glibc.sh new file mode 100755 index 0000000..bb9052f --- /dev/null +++ b/scripts/check-glibc.sh | |||
| @@ -0,0 +1,35 @@ | |||
| 1 | #!/usr/bin/env bash | ||
| 2 | # Gate a release on the glibc the target actually has. | ||
| 3 | # | ||
| 4 | # The dev host's 32-bit glibc is newer than Debian 12's, so a dependency can | ||
| 5 | # silently raise the required symbol version. Without this check the failure | ||
| 6 | # only shows up as "version `GLIBC_2.38' not found" on the target machine. | ||
| 7 | set -euo pipefail | ||
| 8 | |||
| 9 | binary=${1:?usage: check-glibc.sh <binary> [ceiling, default 2.36]} | ||
| 10 | ceiling=${2:-2.36} | ||
| 11 | |||
| 12 | if [ ! -f "$binary" ]; then | ||
| 13 | echo "check-glibc: no such file: $binary" >&2 | ||
| 14 | exit 2 | ||
| 15 | fi | ||
| 16 | |||
| 17 | max=$(readelf -V "$binary" 2>/dev/null \ | ||
| 18 | | grep -oE 'GLIBC_[0-9]+\.[0-9]+' \ | ||
| 19 | | sed 's/^GLIBC_//' \ | ||
| 20 | | sort -Vu \ | ||
| 21 | | tail -1 || true) | ||
| 22 | |||
| 23 | if [ -z "${max:-}" ]; then | ||
| 24 | echo "check-glibc: no versioned symbols (statically linked?) — nothing to check" | ||
| 25 | exit 0 | ||
| 26 | fi | ||
| 27 | |||
| 28 | echo "check-glibc: max symbol version GLIBC_$max, ceiling GLIBC_$ceiling" | ||
| 29 | |||
| 30 | if [ "$(printf '%s\n%s\n' "$ceiling" "$max" | sort -V | tail -1)" != "$ceiling" ]; then | ||
| 31 | echo "check-glibc: FAIL — binary needs GLIBC_$max, target has GLIBC_$ceiling" >&2 | ||
| 32 | exit 1 | ||
| 33 | fi | ||
| 34 | |||
| 35 | echo "check-glibc: ok" | ||
diff --git a/scripts/mock-provider.py b/scripts/mock-provider.py new file mode 100755 index 0000000..4d11349 --- /dev/null +++ b/scripts/mock-provider.py | |||
| @@ -0,0 +1,86 @@ | |||
| 1 | #!/usr/bin/env python3 | ||
| 2 | """A canned OpenAI-compatible SSE provider for manual testing. | ||
| 3 | |||
| 4 | No API key, no network, no quota. Streams a reasoning delta, a text answer and | ||
| 5 | a usage frame, with a small pause between them so the renderer can be seen | ||
| 6 | working incrementally. | ||
| 7 | |||
| 8 | scripts/mock-provider.py --port 8765 | ||
| 9 | OPENCODE_API_KEY=test ./agent686 --base-url http://127.0.0.1:8765/v1 "hi" | ||
| 10 | """ | ||
| 11 | import argparse | ||
| 12 | import json | ||
| 13 | import time | ||
| 14 | from http.server import BaseHTTPRequestHandler, HTTPServer | ||
| 15 | |||
| 16 | |||
| 17 | def frames(answer: str): | ||
| 18 | yield {"choices": [{"delta": {"reasoning_content": "The user said hi. "}}]} | ||
| 19 | yield {"choices": [{"delta": {"reasoning_content": "A short greeting is enough."}}]} | ||
| 20 | for word in answer.split(" "): | ||
| 21 | yield {"choices": [{"delta": {"content": word + " "}}]} | ||
| 22 | yield {"choices": [{"delta": {}, "finish_reason": "stop"}]} | ||
| 23 | yield {"choices": [], "usage": {"prompt_tokens": 24, "completion_tokens": 9}} | ||
| 24 | |||
| 25 | |||
| 26 | class Handler(BaseHTTPRequestHandler): | ||
| 27 | protocol_version = "HTTP/1.0" | ||
| 28 | |||
| 29 | def do_POST(self): | ||
| 30 | length = int(self.headers.get("content-length") or 0) | ||
| 31 | self.rfile.read(length) | ||
| 32 | |||
| 33 | if self.server.status != 200: | ||
| 34 | body = json.dumps( | ||
| 35 | { | ||
| 36 | "error": { | ||
| 37 | "type": "authentication_error", | ||
| 38 | "code": "api_key_expired", | ||
| 39 | "message": "This API key has expired.", | ||
| 40 | } | ||
| 41 | } | ||
| 42 | ).encode() | ||
| 43 | self.send_response(self.server.status) | ||
| 44 | self.send_header("Content-Type", "application/json") | ||
| 45 | self.end_headers() | ||
| 46 | self.wfile.write(body) | ||
| 47 | return | ||
| 48 | |||
| 49 | self.send_response(200) | ||
| 50 | self.send_header("Content-Type", "text/event-stream") | ||
| 51 | self.send_header("Cache-Control", "no-cache") | ||
| 52 | self.end_headers() | ||
| 53 | |||
| 54 | for frame in frames(self.server.answer): | ||
| 55 | if self.server.delay: | ||
| 56 | time.sleep(self.server.delay) | ||
| 57 | self.wfile.write(f"data: {json.dumps(frame)}\n\n".encode()) | ||
| 58 | self.wfile.flush() | ||
| 59 | self.wfile.write(b"data: [DONE]\n\n") | ||
| 60 | self.wfile.flush() | ||
| 61 | |||
| 62 | def log_message(self, fmt, *args): | ||
| 63 | if not self.server.quiet: | ||
| 64 | super().log_message(fmt, *args) | ||
| 65 | |||
| 66 | |||
| 67 | def main(): | ||
| 68 | parser = argparse.ArgumentParser() | ||
| 69 | parser.add_argument("--port", type=int, default=8765) | ||
| 70 | parser.add_argument("--delay", type=float, default=0.05, help="seconds between frames") | ||
| 71 | parser.add_argument("--status", type=int, default=200, help="return this HTTP status") | ||
| 72 | parser.add_argument("--answer", default="Hello from the mock provider.") | ||
| 73 | parser.add_argument("--quiet", action="store_true") | ||
| 74 | args = parser.parse_args() | ||
| 75 | |||
| 76 | server = HTTPServer(("127.0.0.1", args.port), Handler) | ||
| 77 | server.answer = args.answer | ||
| 78 | server.delay = args.delay | ||
| 79 | server.status = args.status | ||
| 80 | server.quiet = args.quiet | ||
| 81 | print(f"mock provider on http://127.0.0.1:{args.port}/v1", flush=True) | ||
| 82 | server.serve_forever() | ||
| 83 | |||
| 84 | |||
| 85 | if __name__ == "__main__": | ||
| 86 | main() | ||
diff --git a/src/agent.rs b/src/agent.rs new file mode 100644 index 0000000..2d84566 --- /dev/null +++ b/src/agent.rs | |||
| @@ -0,0 +1,67 @@ | |||
| 1 | use std::sync::atomic::AtomicBool; | ||
| 2 | |||
| 3 | use serde_json::{json, Value}; | ||
| 4 | |||
| 5 | use crate::config::Config; | ||
| 6 | use crate::provider::{self, Error, Outcome, Sink}; | ||
| 7 | |||
| 8 | /// Frozen for the life of the process. Anything session-varying added here | ||
| 9 | /// invalidates the provider's prompt cache, so keep it boring. | ||
| 10 | pub fn system_message() -> Value { | ||
| 11 | json!({ | ||
| 12 | "role": "system", | ||
| 13 | "content": "You are agent686, a coding agent working in a Unix terminal. \ | ||
| 14 | You edit files and run commands. Be terse and do not explain \ | ||
| 15 | what you are about to do before doing it." | ||
| 16 | }) | ||
| 17 | } | ||
| 18 | |||
| 19 | /// Appends the user message, runs one provider round trip, and appends the | ||
| 20 | /// assistant message to the history whether or not it asked for tools. | ||
| 21 | pub fn run_turn( | ||
| 22 | cfg: &Config, | ||
| 23 | history: &mut Vec<Value>, | ||
| 24 | prompt: &str, | ||
| 25 | cancel: &AtomicBool, | ||
| 26 | sink: &mut dyn Sink, | ||
| 27 | ) -> Result<Outcome, Error> { | ||
| 28 | history.push(json!({ "role": "user", "content": prompt })); | ||
| 29 | |||
| 30 | let outcome = provider::chat(cfg, history, cancel, sink)?; | ||
| 31 | |||
| 32 | let mut message = serde_json::Map::new(); | ||
| 33 | message.insert("role".into(), json!("assistant")); | ||
| 34 | message.insert( | ||
| 35 | "content".into(), | ||
| 36 | if outcome.content.is_empty() { | ||
| 37 | Value::Null | ||
| 38 | } else { | ||
| 39 | json!(outcome.content) | ||
| 40 | }, | ||
| 41 | ); | ||
| 42 | if !outcome.tool_calls.is_empty() { | ||
| 43 | let calls: Vec<Value> = outcome | ||
| 44 | .tool_calls | ||
| 45 | .iter() | ||
| 46 | .map(|call| { | ||
| 47 | json!({ | ||
| 48 | "id": call.id, | ||
| 49 | "type": "function", | ||
| 50 | "function": { | ||
| 51 | "name": call.name, | ||
| 52 | // Byte-for-byte what the model sent. | ||
| 53 | "arguments": call.arguments, | ||
| 54 | } | ||
| 55 | }) | ||
| 56 | }) | ||
| 57 | .collect(); | ||
| 58 | message.insert("tool_calls".into(), Value::Array(calls)); | ||
| 59 | } | ||
| 60 | history.push(Value::Object(message)); | ||
| 61 | |||
| 62 | Ok(outcome) | ||
| 63 | } | ||
| 64 | |||
| 65 | pub fn new_history() -> Vec<Value> { | ||
| 66 | vec![system_message()] | ||
| 67 | } | ||
diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..b781637 --- /dev/null +++ b/src/config.rs | |||
| @@ -0,0 +1,67 @@ | |||
| 1 | use std::path::PathBuf; | ||
| 2 | |||
| 3 | pub const DEFAULT_BASE_URL: &str = "https://opencode.ai/inference/go/openai/v1"; | ||
| 4 | pub const DEFAULT_MODEL: &str = "deepseek-v4.1-flash"; | ||
| 5 | |||
| 6 | #[derive(Debug, Clone)] | ||
| 7 | pub struct Config { | ||
| 8 | pub base_url: String, | ||
| 9 | pub api_key: String, | ||
| 10 | pub model: String, | ||
| 11 | pub session: String, | ||
| 12 | } | ||
| 13 | |||
| 14 | impl Config { | ||
| 15 | /// CLI flags win over environment variables, which win over defaults. | ||
| 16 | pub fn resolve( | ||
| 17 | model: Option<String>, | ||
| 18 | base_url: Option<String>, | ||
| 19 | session: Option<String>, | ||
| 20 | ) -> Result<Config, String> { | ||
| 21 | Ok(Config { | ||
| 22 | api_key: api_key()?, | ||
| 23 | base_url: base_url | ||
| 24 | .or_else(|| env_nonempty("AGENT686_BASE_URL")) | ||
| 25 | .unwrap_or_else(|| DEFAULT_BASE_URL.to_string()), | ||
| 26 | model: model | ||
| 27 | .or_else(|| env_nonempty("AGENT686_MODEL")) | ||
| 28 | .unwrap_or_else(|| DEFAULT_MODEL.to_string()), | ||
| 29 | session: session.unwrap_or_else(crate::session::new_id), | ||
| 30 | }) | ||
| 31 | } | ||
| 32 | |||
| 33 | pub fn endpoint(&self) -> String { | ||
| 34 | format!("{}/chat/completions", self.base_url.trim_end_matches('/')) | ||
| 35 | } | ||
| 36 | } | ||
| 37 | |||
| 38 | fn env_nonempty(key: &str) -> Option<String> { | ||
| 39 | std::env::var(key).ok().filter(|v| !v.trim().is_empty()) | ||
| 40 | } | ||
| 41 | |||
| 42 | /// The key comes from the environment first, then from a file, so a key never | ||
| 43 | /// has to live in shell history or in a process listing. | ||
| 44 | fn api_key() -> Result<String, String> { | ||
| 45 | if let Some(k) = env_nonempty("OPENCODE_API_KEY") { | ||
| 46 | return Ok(k.trim().to_string()); | ||
| 47 | } | ||
| 48 | if let Some(path) = key_file() { | ||
| 49 | if let Ok(k) = std::fs::read_to_string(&path) { | ||
| 50 | let k = k.trim().to_string(); | ||
| 51 | if !k.is_empty() { | ||
| 52 | return Ok(k); | ||
| 53 | } | ||
| 54 | } | ||
| 55 | } | ||
| 56 | Err(format!( | ||
| 57 | "no API key: set OPENCODE_API_KEY or write one to {}", | ||
| 58 | key_file() | ||
| 59 | .map(|p| p.display().to_string()) | ||
| 60 | .unwrap_or_else(|| "~/.config/agent686/key".into()) | ||
| 61 | )) | ||
| 62 | } | ||
| 63 | |||
| 64 | fn key_file() -> Option<PathBuf> { | ||
| 65 | let home = std::env::var_os("HOME")?; | ||
| 66 | Some(PathBuf::from(home).join(".config/agent686/key")) | ||
| 67 | } | ||
diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..20913b2 --- /dev/null +++ b/src/lib.rs | |||
| @@ -0,0 +1,5 @@ | |||
| 1 | pub mod agent; | ||
| 2 | pub mod config; | ||
| 3 | pub mod provider; | ||
| 4 | pub mod session; | ||
| 5 | pub mod ui; | ||
diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..8c9a58c --- /dev/null +++ b/src/main.rs | |||
| @@ -0,0 +1,136 @@ | |||
| 1 | use std::io::{BufRead, IsTerminal, Write}; | ||
| 2 | use std::sync::atomic::AtomicBool; | ||
| 3 | |||
| 4 | use agent686::{agent, config::Config, ui}; | ||
| 5 | |||
| 6 | const HELP: &str = "\ | ||
| 7 | agent686 — a small coding agent | ||
| 8 | |||
| 9 | USAGE: | ||
| 10 | agent686 [OPTIONS] [PROMPT...] | ||
| 11 | |||
| 12 | With a prompt it runs one turn and exits; without one it reads prompts from | ||
| 13 | stdin, one per line. /exit quits. | ||
| 14 | |||
| 15 | OPTIONS: | ||
| 16 | -m, --model <ID> model id (default: deepseek-v4.1-flash) | ||
| 17 | --base-url <URL> provider base URL, e.g. http://127.0.0.1:8080/v1 | ||
| 18 | --session <ID> reuse a session id, including for the provider header | ||
| 19 | -h, --help this text | ||
| 20 | |||
| 21 | ENVIRONMENT: | ||
| 22 | OPENCODE_API_KEY credential (falls back to ~/.config/agent686/key) | ||
| 23 | AGENT686_MODEL default model id | ||
| 24 | AGENT686_BASE_URL default provider base URL | ||
| 25 | "; | ||
| 26 | |||
| 27 | fn main() { | ||
| 28 | let mut prompt: Option<String> = None; | ||
| 29 | let mut model = None; | ||
| 30 | let mut base_url = None; | ||
| 31 | let mut session = None; | ||
| 32 | |||
| 33 | let mut args = std::env::args().skip(1); | ||
| 34 | while let Some(arg) = args.next() { | ||
| 35 | match arg.as_str() { | ||
| 36 | "-m" | "--model" => model = args.next(), | ||
| 37 | "--base-url" => base_url = args.next(), | ||
| 38 | "--session" => session = args.next(), | ||
| 39 | "-h" | "--help" => { | ||
| 40 | print!("{HELP}"); | ||
| 41 | return; | ||
| 42 | } | ||
| 43 | flag if flag.starts_with('-') && flag.len() > 1 => { | ||
| 44 | eprintln!("agent686: unknown flag {flag}\n"); | ||
| 45 | print!("{HELP}"); | ||
| 46 | std::process::exit(2); | ||
| 47 | } | ||
| 48 | word => { | ||
| 49 | prompt = Some(match prompt.take() { | ||
| 50 | Some(existing) => format!("{existing} {word}"), | ||
| 51 | None => word.to_string(), | ||
| 52 | }) | ||
| 53 | } | ||
| 54 | } | ||
| 55 | } | ||
| 56 | |||
| 57 | let cfg = match Config::resolve(model, base_url, session) { | ||
| 58 | Ok(cfg) => cfg, | ||
| 59 | Err(message) => { | ||
| 60 | eprintln!("agent686: {message}"); | ||
| 61 | std::process::exit(2); | ||
| 62 | } | ||
| 63 | }; | ||
| 64 | |||
| 65 | let cancel = AtomicBool::new(false); | ||
| 66 | let mut history = agent::new_history(); | ||
| 67 | |||
| 68 | // One-shot mode: a prompt on the command line means one turn, then exit. | ||
| 69 | if let Some(prompt) = prompt { | ||
| 70 | let mut sink = ui::Renderer::new(ui::stdout_is_tty()); | ||
| 71 | match agent::run_turn(&cfg, &mut history, &prompt, &cancel, &mut sink) { | ||
| 72 | Ok(outcome) => note_tool_calls(&outcome), | ||
| 73 | Err(error) => { | ||
| 74 | eprintln!("agent686: {error}"); | ||
| 75 | std::process::exit(1); | ||
| 76 | } | ||
| 77 | } | ||
| 78 | return; | ||
| 79 | } | ||
| 80 | |||
| 81 | let interactive = std::io::stdin().is_terminal(); | ||
| 82 | if interactive { | ||
| 83 | eprintln!( | ||
| 84 | "agent686 · {} · session {}{}", | ||
| 85 | cfg.model, | ||
| 86 | cfg.session, | ||
| 87 | if is_local(&cfg.base_url) { " · local" } else { "" } | ||
| 88 | ); | ||
| 89 | eprintln!("one prompt per line · /exit to quit"); | ||
| 90 | } | ||
| 91 | |||
| 92 | let stdin = std::io::stdin(); | ||
| 93 | let mut line = String::new(); | ||
| 94 | loop { | ||
| 95 | if interactive { | ||
| 96 | print!("> "); | ||
| 97 | let _ = std::io::stdout().flush(); | ||
| 98 | } | ||
| 99 | line.clear(); | ||
| 100 | if stdin.lock().read_line(&mut line).unwrap_or(0) == 0 { | ||
| 101 | break; | ||
| 102 | } | ||
| 103 | let text = line.trim_end(); | ||
| 104 | if text.is_empty() { | ||
| 105 | continue; | ||
| 106 | } | ||
| 107 | if text == "/exit" || text == "/quit" { | ||
| 108 | break; | ||
| 109 | } | ||
| 110 | let mut sink = ui::Renderer::new(ui::stdout_is_tty()); | ||
| 111 | match agent::run_turn(&cfg, &mut history, text, &cancel, &mut sink) { | ||
| 112 | Ok(outcome) => note_tool_calls(&outcome), | ||
| 113 | Err(error) => eprintln!("agent686: {error}"), | ||
| 114 | } | ||
| 115 | } | ||
| 116 | } | ||
| 117 | |||
| 118 | fn note_tool_calls(outcome: &agent686::provider::Outcome) { | ||
| 119 | if outcome.tool_calls.is_empty() { | ||
| 120 | return; | ||
| 121 | } | ||
| 122 | let names: Vec<&str> = outcome | ||
| 123 | .tool_calls | ||
| 124 | .iter() | ||
| 125 | .map(|call| call.name.as_str()) | ||
| 126 | .collect(); | ||
| 127 | eprintln!( | ||
| 128 | "agent686: model asked for {} tool call(s) [{}]; tools arrive in milestone 2", | ||
| 129 | names.len(), | ||
| 130 | names.join(", ") | ||
| 131 | ); | ||
| 132 | } | ||
| 133 | |||
| 134 | fn is_local(base_url: &str) -> bool { | ||
| 135 | base_url.contains("127.0.0.1") || base_url.contains("localhost") | ||
| 136 | } | ||
diff --git a/src/provider.rs b/src/provider.rs new file mode 100644 index 0000000..a2aed64 --- /dev/null +++ b/src/provider.rs | |||
| @@ -0,0 +1,319 @@ | |||
| 1 | use std::io::Read; | ||
| 2 | use std::sync::atomic::{AtomicBool, Ordering}; | ||
| 3 | use std::time::{Duration, Instant}; | ||
| 4 | |||
| 5 | use serde::Deserialize; | ||
| 6 | use serde_json::Value; | ||
| 7 | |||
| 8 | use crate::config::Config; | ||
| 9 | |||
| 10 | #[derive(Debug)] | ||
| 11 | pub enum Error { | ||
| 12 | Transport(String), | ||
| 13 | Status { code: u16, message: String }, | ||
| 14 | Aborted, | ||
| 15 | } | ||
| 16 | |||
| 17 | impl std::fmt::Display for Error { | ||
| 18 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
| 19 | match self { | ||
| 20 | Error::Transport(m) => write!(f, "{m}"), | ||
| 21 | Error::Status { code, message } => write!(f, "HTTP {code}: {message}"), | ||
| 22 | Error::Aborted => write!(f, "aborted"), | ||
| 23 | } | ||
| 24 | } | ||
| 25 | } | ||
| 26 | |||
| 27 | impl std::error::Error for Error {} | ||
| 28 | |||
| 29 | /// One completed tool call, assembled from streamed deltas. | ||
| 30 | #[derive(Debug, Default, Clone)] | ||
| 31 | pub struct ToolCall { | ||
| 32 | pub index: usize, | ||
| 33 | pub id: String, | ||
| 34 | pub name: String, | ||
| 35 | /// The argument JSON exactly as the model emitted it. Never re-serialised: | ||
| 36 | /// re-encoding can change key order and invalidate the provider's cache. | ||
| 37 | pub arguments: String, | ||
| 38 | } | ||
| 39 | |||
| 40 | #[derive(Debug, Default)] | ||
| 41 | pub struct Outcome { | ||
| 42 | pub content: String, | ||
| 43 | pub reasoning: String, | ||
| 44 | pub tool_calls: Vec<ToolCall>, | ||
| 45 | pub finish: Option<String>, | ||
| 46 | pub usage: Option<Value>, | ||
| 47 | pub opencode: Option<Value>, | ||
| 48 | } | ||
| 49 | |||
| 50 | pub trait Sink { | ||
| 51 | fn text(&mut self, s: &str); | ||
| 52 | fn reasoning(&mut self, s: &str); | ||
| 53 | fn done(&mut self, outcome: &Outcome, elapsed: Duration); | ||
| 54 | } | ||
| 55 | |||
| 56 | /// Decodes an SSE byte stream into `data:` payloads. | ||
| 57 | /// | ||
| 58 | /// Kept as a state machine so that chunk boundaries can fall anywhere: inside a | ||
| 59 | /// line, or inside a multi-byte UTF-8 character. Only complete lines are ever | ||
| 60 | /// converted to text. | ||
| 61 | #[derive(Default)] | ||
| 62 | pub struct SseDecoder { | ||
| 63 | buf: Vec<u8>, | ||
| 64 | } | ||
| 65 | |||
| 66 | impl SseDecoder { | ||
| 67 | pub fn new() -> Self { | ||
| 68 | Self::default() | ||
| 69 | } | ||
| 70 | |||
| 71 | pub fn feed(&mut self, chunk: &[u8]) -> Vec<String> { | ||
| 72 | self.buf.extend_from_slice(chunk); | ||
| 73 | let mut out = Vec::new(); | ||
| 74 | let mut start = 0; | ||
| 75 | while let Some(rel) = self.buf[start..].iter().position(|&b| b == b'\n') { | ||
| 76 | let end = start + rel; | ||
| 77 | let mut line = &self.buf[start..end]; | ||
| 78 | if line.last() == Some(&b'\r') { | ||
| 79 | line = &line[..line.len() - 1]; | ||
| 80 | } | ||
| 81 | start = end + 1; | ||
| 82 | if let Some(payload) = line.strip_prefix(b"data:") { | ||
| 83 | let payload = payload.strip_prefix(b" ").unwrap_or(payload); | ||
| 84 | out.push(String::from_utf8_lossy(payload).into_owned()); | ||
| 85 | } | ||
| 86 | } | ||
| 87 | self.buf.drain(..start); | ||
| 88 | out | ||
| 89 | } | ||
| 90 | } | ||
| 91 | |||
| 92 | pub fn chat( | ||
| 93 | cfg: &Config, | ||
| 94 | messages: &[Value], | ||
| 95 | cancel: &AtomicBool, | ||
| 96 | sink: &mut dyn Sink, | ||
| 97 | ) -> Result<Outcome, Error> { | ||
| 98 | // serde_json::Value is ordered by key, not by insertion, so the serialised | ||
| 99 | // bytes are stable for the same input. That is what keeps the cache warm; | ||
| 100 | // do not switch this to a struct with fields in a different order, and do | ||
| 101 | // not add anything session-varying to the system message. | ||
| 102 | let body = serde_json::json!({ | ||
| 103 | "model": cfg.model, | ||
| 104 | "messages": messages, | ||
| 105 | "stream": true, | ||
| 106 | "stream_options": { "include_usage": true }, | ||
| 107 | }); | ||
| 108 | let bytes = serde_json::to_vec(&body).map_err(|e| Error::Transport(e.to_string()))?; | ||
| 109 | |||
| 110 | let agent: ureq::Agent = ureq::Agent::config_builder() | ||
| 111 | .http_status_as_error(false) | ||
| 112 | .timeout_connect(Some(Duration::from_secs(10))) | ||
| 113 | .timeout_recv_response(Some(Duration::from_secs(180))) | ||
| 114 | .timeout_per_read(Some(Duration::from_secs(180))) | ||
| 115 | .build() | ||
| 116 | .into(); | ||
| 117 | |||
| 118 | let started = Instant::now(); | ||
| 119 | let mut resp = agent | ||
| 120 | .post(&cfg.endpoint()) | ||
| 121 | .header("Content-Type", "application/json") | ||
| 122 | .header("Accept", "text/event-stream") | ||
| 123 | .header("Authorization", format!("Bearer {}", cfg.api_key)) | ||
| 124 | .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION"))) | ||
| 125 | // Required by OpenCode Go: stable per conversation, used for routing and | ||
| 126 | // prompt caching. | ||
| 127 | .header("x-opencode-session", &cfg.session) | ||
| 128 | .send(bytes) | ||
| 129 | .map_err(|e| Error::Transport(e.to_string()))?; | ||
| 130 | |||
| 131 | let status = resp.status().as_u16(); | ||
| 132 | if !(200..300).contains(&status) { | ||
| 133 | let text = resp | ||
| 134 | .body_mut() | ||
| 135 | .with_config() | ||
| 136 | .limit(256 * 1024) | ||
| 137 | .read_to_string() | ||
| 138 | .unwrap_or_default(); | ||
| 139 | return Err(Error::Status { | ||
| 140 | code: status, | ||
| 141 | message: error_message(&text), | ||
| 142 | }); | ||
| 143 | } | ||
| 144 | |||
| 145 | let mut outcome = Outcome::default(); | ||
| 146 | let mut decoder = SseDecoder::new(); | ||
| 147 | let mut buf = [0u8; 8192]; | ||
| 148 | let mut reader = resp.body_mut().as_reader(); | ||
| 149 | let mut done = false; | ||
| 150 | |||
| 151 | while !done { | ||
| 152 | // Blocking reads mean an abort is only noticed when bytes arrive or the | ||
| 153 | // per-read timeout fires. Good enough: the model streams constantly. | ||
| 154 | if cancel.load(Ordering::Relaxed) { | ||
| 155 | return Err(Error::Aborted); | ||
| 156 | } | ||
| 157 | let n = match reader.read(&mut buf) { | ||
| 158 | Ok(0) => break, | ||
| 159 | Ok(n) => n, | ||
| 160 | Err(e) => return Err(Error::Transport(e.to_string())), | ||
| 161 | }; | ||
| 162 | for data in decoder.feed(&buf[..n]) { | ||
| 163 | if data.is_empty() { | ||
| 164 | continue; | ||
| 165 | } | ||
| 166 | if data.trim() == "[DONE]" { | ||
| 167 | done = true; | ||
| 168 | break; | ||
| 169 | } | ||
| 170 | let chunk: Chunk = match serde_json::from_str(&data) { | ||
| 171 | Ok(c) => c, | ||
| 172 | // A malformed frame is dropped rather than killing the turn; the | ||
| 173 | // stream is the only recovery path and it is still valid SSE. | ||
| 174 | Err(_) => continue, | ||
| 175 | }; | ||
| 176 | apply_chunk(&chunk, &mut outcome, sink); | ||
| 177 | } | ||
| 178 | } | ||
| 179 | |||
| 180 | if let Some(usage) = &outcome.usage { | ||
| 181 | if usage.is_null() { | ||
| 182 | outcome.usage = None; | ||
| 183 | } | ||
| 184 | } | ||
| 185 | if let Some(opencode) = &outcome.opencode { | ||
| 186 | if opencode.is_null() { | ||
| 187 | outcome.opencode = None; | ||
| 188 | } | ||
| 189 | } | ||
| 190 | |||
| 191 | sink.done(&outcome, started.elapsed()); | ||
| 192 | Ok(outcome) | ||
| 193 | } | ||
| 194 | |||
| 195 | fn apply_chunk(chunk: &Chunk, outcome: &mut Outcome, sink: &mut dyn Sink) { | ||
| 196 | if let Some(usage) = &chunk.usage { | ||
| 197 | outcome.usage = Some(usage.clone()); | ||
| 198 | } | ||
| 199 | if let Some(opencode) = &chunk.opencode { | ||
| 200 | outcome.opencode = Some(opencode.clone()); | ||
| 201 | } | ||
| 202 | for choice in &chunk.choices { | ||
| 203 | if let Some(r) = &choice.delta.reasoning_content { | ||
| 204 | if !r.is_empty() { | ||
| 205 | outcome.reasoning.push_str(r); | ||
| 206 | sink.reasoning(r); | ||
| 207 | } | ||
| 208 | } | ||
| 209 | if let Some(t) = &choice.delta.content { | ||
| 210 | if !t.is_empty() { | ||
| 211 | outcome.content.push_str(t); | ||
| 212 | sink.text(t); | ||
| 213 | } | ||
| 214 | } | ||
| 215 | if let Some(calls) = &choice.delta.tool_calls { | ||
| 216 | for call in calls { | ||
| 217 | accumulate_tool_call(&mut outcome.tool_calls, call); | ||
| 218 | } | ||
| 219 | } | ||
| 220 | if let Some(finish) = &choice.finish_reason { | ||
| 221 | outcome.finish = Some(finish.clone()); | ||
| 222 | } | ||
| 223 | } | ||
| 224 | } | ||
| 225 | |||
| 226 | /// Tool call deltas arrive split across chunks and are keyed by `index`: the | ||
| 227 | /// name and id usually come once, the arguments a fragment at a time. | ||
| 228 | fn accumulate_tool_call(calls: &mut Vec<ToolCall>, delta: &ToolCallDelta) { | ||
| 229 | while calls.len() <= delta.index { | ||
| 230 | let index = calls.len(); | ||
| 231 | calls.push(ToolCall { | ||
| 232 | index, | ||
| 233 | id: String::new(), | ||
| 234 | name: String::new(), | ||
| 235 | arguments: String::new(), | ||
| 236 | }); | ||
| 237 | } | ||
| 238 | let call = &mut calls[delta.index]; | ||
| 239 | if let Some(id) = &delta.id { | ||
| 240 | call.id.push_str(id); | ||
| 241 | } | ||
| 242 | if let Some(function) = &delta.function { | ||
| 243 | if let Some(name) = &function.name { | ||
| 244 | call.name.push_str(name); | ||
| 245 | } | ||
| 246 | if let Some(args) = &function.arguments { | ||
| 247 | call.arguments.push_str(args); | ||
| 248 | } | ||
| 249 | } | ||
| 250 | } | ||
| 251 | |||
| 252 | fn error_message(body: &str) -> String { | ||
| 253 | if let Ok(v) = serde_json::from_str::<Value>(body) { | ||
| 254 | if let Some(err) = v.get("error") { | ||
| 255 | if let Some(message) = err.get("message").and_then(|m| m.as_str()) { | ||
| 256 | return match err.get("code").and_then(|c| c.as_str()) { | ||
| 257 | Some(code) if !code.is_empty() => format!("{message} ({code})"), | ||
| 258 | _ => message.to_string(), | ||
| 259 | }; | ||
| 260 | } | ||
| 261 | } | ||
| 262 | if let Some(message) = v.get("message").and_then(|m| m.as_str()) { | ||
| 263 | return message.to_string(); | ||
| 264 | } | ||
| 265 | } | ||
| 266 | truncate(body.trim(), 500) | ||
| 267 | } | ||
| 268 | |||
| 269 | fn truncate(s: &str, max: usize) -> String { | ||
| 270 | match s.char_indices().nth(max) { | ||
| 271 | Some((i, _)) => format!("{}…", &s[..i]), | ||
| 272 | None => s.to_string(), | ||
| 273 | } | ||
| 274 | } | ||
| 275 | |||
| 276 | #[derive(Debug, Deserialize)] | ||
| 277 | struct Chunk { | ||
| 278 | #[serde(default)] | ||
| 279 | choices: Vec<Choice>, | ||
| 280 | #[serde(default)] | ||
| 281 | usage: Option<Value>, | ||
| 282 | #[serde(default)] | ||
| 283 | opencode: Option<Value>, | ||
| 284 | } | ||
| 285 | |||
| 286 | #[derive(Debug, Deserialize)] | ||
| 287 | struct Choice { | ||
| 288 | #[serde(default)] | ||
| 289 | delta: Delta, | ||
| 290 | #[serde(default)] | ||
| 291 | finish_reason: Option<String>, | ||
| 292 | } | ||
| 293 | |||
| 294 | #[derive(Debug, Default, Deserialize)] | ||
| 295 | struct Delta { | ||
| 296 | #[serde(default)] | ||
| 297 | content: Option<String>, | ||
| 298 | #[serde(default)] | ||
| 299 | reasoning_content: Option<String>, | ||
| 300 | #[serde(default)] | ||
| 301 | tool_calls: Option<Vec<ToolCallDelta>>, | ||
| 302 | } | ||
| 303 | |||
| 304 | #[derive(Debug, Deserialize)] | ||
| 305 | struct ToolCallDelta { | ||
| 306 | index: usize, | ||
| 307 | #[serde(default)] | ||
| 308 | id: Option<String>, | ||
| 309 | #[serde(default)] | ||
| 310 | function: Option<FunctionDelta>, | ||
| 311 | } | ||
| 312 | |||
| 313 | #[derive(Debug, Deserialize)] | ||
| 314 | struct FunctionDelta { | ||
| 315 | #[serde(default)] | ||
| 316 | name: Option<String>, | ||
| 317 | #[serde(default)] | ||
| 318 | arguments: Option<String>, | ||
| 319 | } | ||
diff --git a/src/session.rs b/src/session.rs new file mode 100644 index 0000000..aef4835 --- /dev/null +++ b/src/session.rs | |||
| @@ -0,0 +1,39 @@ | |||
| 1 | use std::hash::{Hash, Hasher}; | ||
| 2 | use std::io::Read; | ||
| 3 | use std::time::{SystemTime, UNIX_EPOCH}; | ||
| 4 | |||
| 5 | /// A session id is opaque to the provider: it only has to be stable for the life | ||
| 6 | /// of one conversation. 16 random-ish bytes as lowercase hex is plenty and keeps | ||
| 7 | /// it usable as a file name. | ||
| 8 | pub fn new_id() -> String { | ||
| 9 | let mut bytes = random_bytes(); | ||
| 10 | // Put the creation time in the first bytes so ids sort roughly by age. | ||
| 11 | let ms = SystemTime::now() | ||
| 12 | .duration_since(UNIX_EPOCH) | ||
| 13 | .map(|d| d.as_millis() as u64) | ||
| 14 | .unwrap_or(0); | ||
| 15 | bytes[..8].copy_from_slice(&ms.to_be_bytes()); | ||
| 16 | |||
| 17 | let mut out = String::with_capacity(32); | ||
| 18 | for b in bytes { | ||
| 19 | out.push_str(&format!("{b:02x}")); | ||
| 20 | } | ||
| 21 | out | ||
| 22 | } | ||
| 23 | |||
| 24 | fn random_bytes() -> [u8; 16] { | ||
| 25 | let mut bytes = [0u8; 16]; | ||
| 26 | if let Ok(mut f) = std::fs::File::open("/dev/urandom") { | ||
| 27 | if f.read_exact(&mut bytes).is_ok() { | ||
| 28 | return bytes; | ||
| 29 | } | ||
| 30 | } | ||
| 31 | // Fallback: not cryptographic, but an id only has to not collide. | ||
| 32 | let mut h = std::collections::hash_map::DefaultHasher::new(); | ||
| 33 | SystemTime::now().hash(&mut h); | ||
| 34 | std::process::id().hash(&mut h); | ||
| 35 | let v = h.finish(); | ||
| 36 | bytes[..8].copy_from_slice(&v.to_be_bytes()); | ||
| 37 | bytes[8..].copy_from_slice(&(v ^ 0x9e37_79b9_7f4a_7c15).to_be_bytes()); | ||
| 38 | bytes | ||
| 39 | } | ||
diff --git a/src/ui.rs b/src/ui.rs new file mode 100644 index 0000000..13440b2 --- /dev/null +++ b/src/ui.rs | |||
| @@ -0,0 +1,75 @@ | |||
| 1 | use std::io::{IsTerminal, Write}; | ||
| 2 | use std::time::Duration; | ||
| 3 | |||
| 4 | use crate::provider::{Outcome, Sink}; | ||
| 5 | |||
| 6 | pub fn stdout_is_tty() -> bool { | ||
| 7 | std::io::stdout().is_terminal() | ||
| 8 | } | ||
| 9 | |||
| 10 | /// Streams to stdout. Colour is used only when stdout is a terminal, so piping | ||
| 11 | /// the output somewhere gives clean text. | ||
| 12 | pub struct Renderer { | ||
| 13 | color: bool, | ||
| 14 | dimmed: bool, | ||
| 15 | wrote_text: bool, | ||
| 16 | } | ||
| 17 | |||
| 18 | impl Renderer { | ||
| 19 | pub fn new(color: bool) -> Self { | ||
| 20 | Self { | ||
| 21 | color, | ||
| 22 | dimmed: false, | ||
| 23 | wrote_text: false, | ||
| 24 | } | ||
| 25 | } | ||
| 26 | |||
| 27 | fn undim(&mut self) { | ||
| 28 | if self.dimmed { | ||
| 29 | print!("\x1b[0m"); | ||
| 30 | self.dimmed = false; | ||
| 31 | } | ||
| 32 | } | ||
| 33 | } | ||
| 34 | |||
| 35 | impl Sink for Renderer { | ||
| 36 | fn text(&mut self, s: &str) { | ||
| 37 | self.undim(); | ||
| 38 | print!("{s}"); | ||
| 39 | let _ = std::io::stdout().flush(); | ||
| 40 | self.wrote_text = true; | ||
| 41 | } | ||
| 42 | |||
| 43 | fn reasoning(&mut self, s: &str) { | ||
| 44 | if !self.color { | ||
| 45 | return; | ||
| 46 | } | ||
| 47 | if !self.dimmed { | ||
| 48 | print!("\x1b[2m"); | ||
| 49 | self.dimmed = true; | ||
| 50 | } | ||
| 51 | print!("{s}"); | ||
| 52 | let _ = std::io::stdout().flush(); | ||
| 53 | } | ||
| 54 | |||
| 55 | fn done(&mut self, outcome: &Outcome, elapsed: Duration) { | ||
| 56 | self.undim(); | ||
| 57 | if self.wrote_text { | ||
| 58 | println!(); | ||
| 59 | } | ||
| 60 | let mut parts = vec![format!("{:.1}s", elapsed.as_secs_f64())]; | ||
| 61 | if let Some(usage) = &outcome.usage { | ||
| 62 | let input = usage.get("prompt_tokens").and_then(|v| v.as_u64()); | ||
| 63 | let output = usage.get("completion_tokens").and_then(|v| v.as_u64()); | ||
| 64 | if let (Some(i), Some(o)) = (input, output) { | ||
| 65 | parts.push(format!("{i} in · {o} out")); | ||
| 66 | } | ||
| 67 | } | ||
| 68 | let line = format!("─ {}", parts.join(" · ")); | ||
| 69 | if self.color { | ||
| 70 | println!("\x1b[2m{line}\x1b[0m"); | ||
| 71 | } else { | ||
| 72 | println!("{line}"); | ||
| 73 | } | ||
| 74 | } | ||
| 75 | } | ||
diff --git a/tests/mock.rs b/tests/mock.rs new file mode 100644 index 0000000..80d965b --- /dev/null +++ b/tests/mock.rs | |||
| @@ -0,0 +1,192 @@ | |||
| 1 | use std::io::{BufRead, BufReader, Read, Write}; | ||
| 2 | use std::net::TcpListener; | ||
| 3 | use std::sync::atomic::AtomicBool; | ||
| 4 | use std::sync::mpsc; | ||
| 5 | use std::thread; | ||
| 6 | use std::time::Duration; | ||
| 7 | |||
| 8 | use serde_json::json; | ||
| 9 | |||
| 10 | use agent686::config::Config; | ||
| 11 | use agent686::provider::{self, Error, Outcome, Sink}; | ||
| 12 | |||
| 13 | #[derive(Default)] | ||
| 14 | struct Collector { | ||
| 15 | text: String, | ||
| 16 | reasoning: String, | ||
| 17 | finished: bool, | ||
| 18 | } | ||
| 19 | |||
| 20 | impl Sink for Collector { | ||
| 21 | fn text(&mut self, s: &str) { | ||
| 22 | self.text.push_str(s); | ||
| 23 | } | ||
| 24 | fn reasoning(&mut self, s: &str) { | ||
| 25 | self.reasoning.push_str(s); | ||
| 26 | } | ||
| 27 | fn done(&mut self, _outcome: &Outcome, _elapsed: Duration) { | ||
| 28 | self.finished = true; | ||
| 29 | } | ||
| 30 | } | ||
| 31 | |||
| 32 | /// Serves exactly one request on a random port, then closes. Returns the base | ||
| 33 | /// URL and a receiver for the request as the client sent it. | ||
| 34 | fn serve_once(response: &'static str) -> (String, mpsc::Receiver<String>) { | ||
| 35 | let listener = TcpListener::bind("127.0.0.1:0").unwrap(); | ||
| 36 | let addr = listener.local_addr().unwrap(); | ||
| 37 | let (tx, rx) = mpsc::channel(); | ||
| 38 | |||
| 39 | thread::spawn(move || { | ||
| 40 | let (mut stream, _) = listener.accept().unwrap(); | ||
| 41 | let mut reader = BufReader::new(stream.try_clone().unwrap()); | ||
| 42 | |||
| 43 | let mut request = String::new(); | ||
| 44 | let mut content_length = 0usize; | ||
| 45 | loop { | ||
| 46 | let mut line = String::new(); | ||
| 47 | if reader.read_line(&mut line).unwrap_or(0) == 0 { | ||
| 48 | break; | ||
| 49 | } | ||
| 50 | if line == "\r\n" || line == "\n" { | ||
| 51 | break; | ||
| 52 | } | ||
| 53 | if let Some(value) = line.to_ascii_lowercase().strip_prefix("content-length:") { | ||
| 54 | content_length = value.trim().parse().unwrap_or(0); | ||
| 55 | } | ||
| 56 | request.push_str(&line); | ||
| 57 | } | ||
| 58 | let mut body = vec![0u8; content_length]; | ||
| 59 | let _ = reader.read_exact(&mut body); | ||
| 60 | request.push_str(&String::from_utf8_lossy(&body)); | ||
| 61 | let _ = tx.send(request); | ||
| 62 | |||
| 63 | let _ = stream.write_all(response.as_bytes()); | ||
| 64 | let _ = stream.flush(); | ||
| 65 | }); | ||
| 66 | |||
| 67 | (format!("http://{addr}"), rx) | ||
| 68 | } | ||
| 69 | |||
| 70 | fn config(base_url: String) -> Config { | ||
| 71 | Config { | ||
| 72 | base_url, | ||
| 73 | api_key: "test-key".into(), | ||
| 74 | model: "test-model".into(), | ||
| 75 | session: "testsession".into(), | ||
| 76 | } | ||
| 77 | } | ||
| 78 | |||
| 79 | #[test] | ||
| 80 | fn streams_text_reasoning_and_usage() { | ||
| 81 | const SSE: &str = concat!( | ||
| 82 | "HTTP/1.1 200 OK\r\n", | ||
| 83 | "Content-Type: text/event-stream\r\n", | ||
| 84 | "Connection: close\r\n", | ||
| 85 | "\r\n", | ||
| 86 | "data: {\"choices\":[{\"delta\":{\"reasoning_content\":\"thinking\"}}]}\n\n", | ||
| 87 | "data: {\"choices\":[{\"delta\":{\"content\":\"Hello\"}}]}\n\n", | ||
| 88 | "data: {\"choices\":[{\"delta\":{\"content\":\" from mock\"},\"finish_reason\":\"stop\"}]}\n\n", | ||
| 89 | "data: {\"choices\":[],\"usage\":{\"prompt_tokens\":5,\"completion_tokens\":2}}\n\n", | ||
| 90 | "data: [DONE]\n\n", | ||
| 91 | ); | ||
| 92 | let (base, rx) = serve_once(SSE); | ||
| 93 | let mut sink = Collector::default(); | ||
| 94 | let outcome = provider::chat( | ||
| 95 | &config(base), | ||
| 96 | &[json!({ "role": "user", "content": "hi" })], | ||
| 97 | &AtomicBool::new(false), | ||
| 98 | &mut sink, | ||
| 99 | ) | ||
| 100 | .expect("chat should succeed"); | ||
| 101 | |||
| 102 | assert_eq!(outcome.content, "Hello from mock"); | ||
| 103 | assert_eq!(outcome.reasoning, "thinking"); | ||
| 104 | assert_eq!(sink.text, "Hello from mock"); | ||
| 105 | assert_eq!(sink.reasoning, "thinking"); | ||
| 106 | assert!(sink.finished); | ||
| 107 | assert_eq!(outcome.usage.unwrap()["completion_tokens"], 2); | ||
| 108 | |||
| 109 | let request = rx.recv().unwrap().to_ascii_lowercase(); | ||
| 110 | assert!( | ||
| 111 | request.contains("x-opencode-session: testsession"), | ||
| 112 | "session header missing from request:\n{request}" | ||
| 113 | ); | ||
| 114 | assert!(request.contains("user-agent: agent686/")); | ||
| 115 | assert!(request.contains("\"stream\":true")); | ||
| 116 | assert!(request.contains("\"include_usage\":true")); | ||
| 117 | } | ||
| 118 | |||
| 119 | #[test] | ||
| 120 | fn assembles_tool_call_arguments_byte_for_byte() { | ||
| 121 | const SSE: &str = concat!( | ||
| 122 | "HTTP/1.1 200 OK\r\n", | ||
| 123 | "Content-Type: text/event-stream\r\n", | ||
| 124 | "Connection: close\r\n", | ||
| 125 | "\r\n", | ||
| 126 | "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"call_1\",\"function\":{\"name\":\"read\",\"arguments\":\"{\\\"path\\\":\"}}]}}]}\n\n", | ||
| 127 | "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"\\\"a.txt\\\"}\"}}]}}]}\n\n", | ||
| 128 | "data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\n\n", | ||
| 129 | "data: [DONE]\n\n", | ||
| 130 | ); | ||
| 131 | let (base, _rx) = serve_once(SSE); | ||
| 132 | let mut sink = Collector::default(); | ||
| 133 | let outcome = provider::chat( | ||
| 134 | &config(base), | ||
| 135 | &[json!({ "role": "user", "content": "read a.txt" })], | ||
| 136 | &AtomicBool::new(false), | ||
| 137 | &mut sink, | ||
| 138 | ) | ||
| 139 | .expect("chat should succeed"); | ||
| 140 | |||
| 141 | assert_eq!(outcome.tool_calls.len(), 1); | ||
| 142 | let call = &outcome.tool_calls[0]; | ||
| 143 | assert_eq!(call.id, "call_1"); | ||
| 144 | assert_eq!(call.name, "read"); | ||
| 145 | assert_eq!(call.arguments, r#"{"path":"a.txt"}"#); | ||
| 146 | assert_eq!(outcome.finish.as_deref(), Some("tool_calls")); | ||
| 147 | } | ||
| 148 | |||
| 149 | #[test] | ||
| 150 | fn surfaces_provider_error_text() { | ||
| 151 | const RESPONSE: &str = concat!( | ||
| 152 | "HTTP/1.1 401 Unauthorized\r\n", | ||
| 153 | "Content-Type: application/json\r\n", | ||
| 154 | "Connection: close\r\n", | ||
| 155 | "\r\n", | ||
| 156 | "{\"error\":{\"type\":\"authentication_error\",\"code\":\"api_key_expired\",", | ||
| 157 | "\"message\":\"This API key has expired.\"}}", | ||
| 158 | ); | ||
| 159 | let (base, _rx) = serve_once(RESPONSE); | ||
| 160 | let mut sink = Collector::default(); | ||
| 161 | let error = provider::chat( | ||
| 162 | &config(base), | ||
| 163 | &[json!({ "role": "user", "content": "hi" })], | ||
| 164 | &AtomicBool::new(false), | ||
| 165 | &mut sink, | ||
| 166 | ) | ||
| 167 | .expect_err("should fail"); | ||
| 168 | |||
| 169 | match error { | ||
| 170 | Error::Status { code, message } => { | ||
| 171 | assert_eq!(code, 401); | ||
| 172 | assert!(message.contains("This API key has expired."), "{message}"); | ||
| 173 | assert!(message.contains("api_key_expired"), "{message}"); | ||
| 174 | } | ||
| 175 | other => panic!("unexpected error: {other:?}"), | ||
| 176 | } | ||
| 177 | } | ||
| 178 | |||
| 179 | #[test] | ||
| 180 | fn honours_a_cancelled_turn() { | ||
| 181 | const SSE: &str = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\ndata: {\"choices\":[{\"delta\":{\"content\":\"x\"}}]}\n\n"; | ||
| 182 | let (base, _rx) = serve_once(SSE); | ||
| 183 | let mut sink = Collector::default(); | ||
| 184 | let error = provider::chat( | ||
| 185 | &config(base), | ||
| 186 | &[json!({ "role": "user", "content": "hi" })], | ||
| 187 | &AtomicBool::new(true), | ||
| 188 | &mut sink, | ||
| 189 | ) | ||
| 190 | .expect_err("cancelled turn should abort"); | ||
| 191 | assert!(matches!(error, Error::Aborted)); | ||
| 192 | } | ||
diff --git a/tests/sse.rs b/tests/sse.rs new file mode 100644 index 0000000..7994a0a --- /dev/null +++ b/tests/sse.rs | |||
| @@ -0,0 +1,40 @@ | |||
| 1 | use agent686::provider::SseDecoder; | ||
| 2 | |||
| 3 | #[test] | ||
| 4 | fn reassembles_lines_split_at_every_byte() { | ||
| 5 | // Fed one byte at a time, so the decoder sees a split after every character, | ||
| 6 | // including in the middle of the multi-byte ones. | ||
| 7 | let wire = "data: {\"a\":\"café ✓\"}\n\ndata: [DONE]\n\n"; | ||
| 8 | let mut decoder = SseDecoder::new(); | ||
| 9 | let mut got = Vec::new(); | ||
| 10 | for byte in wire.as_bytes() { | ||
| 11 | got.extend(decoder.feed(std::slice::from_ref(byte))); | ||
| 12 | } | ||
| 13 | assert_eq!(got, vec!["{\"a\":\"café ✓\"}".to_string(), "[DONE]".to_string()]); | ||
| 14 | } | ||
| 15 | |||
| 16 | #[test] | ||
| 17 | fn handles_crlf_comments_and_event_lines() { | ||
| 18 | let wire = ": keep-alive\r\nevent: message\r\ndata:{\"x\":1}\r\n\r\n"; | ||
| 19 | let mut decoder = SseDecoder::new(); | ||
| 20 | let got = decoder.feed(wire.as_bytes()); | ||
| 21 | assert_eq!(got, vec!["{\"x\":1}".to_string()]); | ||
| 22 | } | ||
| 23 | |||
| 24 | #[test] | ||
| 25 | fn keeps_incomplete_line_until_finished() { | ||
| 26 | let mut decoder = SseDecoder::new(); | ||
| 27 | assert!(decoder.feed(b"data: {\"x\"").is_empty()); | ||
| 28 | assert!(decoder.feed(b":1}").is_empty()); | ||
| 29 | assert_eq!( | ||
| 30 | decoder.feed(b"\n"), | ||
| 31 | vec!["{\"x\":1}".to_string()] | ||
| 32 | ); | ||
| 33 | } | ||
| 34 | |||
| 35 | #[test] | ||
| 36 | fn ignores_non_data_lines() { | ||
| 37 | let mut decoder = SseDecoder::new(); | ||
| 38 | let got = decoder.feed(b"id: 1\nretry: 2000\n\n"); | ||
| 39 | assert!(got.is_empty()); | ||
| 40 | } | ||
