7 Commits
Author SHA1 Message Date
Erik Simon b6e94c67c7 harness-app + harness-tui: composition root and harness run -p debug command
App::init wires config loading, an in-memory Store, EventBus, PermissionService
with the M1 auto-approve stub frontend, the full built-in ToolRegistry, and a
ProviderRegistry populated with AnthropicProvider when an API key is available
(config or ANTHROPIC_API_KEY). App::run_prompt creates a root session, appends
the prompt as a user message, and drives engine::run_session to completion;
final_text reads back the concatenated text parts of the last message.

harness-tui's `harness` binary gains a `run -p "<prompt>" [-m provider/model]`
subcommand built on this. Manually verified end-to-end against the real
Anthropic API: an empty API key produced a genuine 401 that our SSE error
path correctly classified as ProviderError::Auth and surfaced as a clean
CLI error message (exit 1) -- confirming the full request/header/error-
handling pipeline works against the live service, not just fixtures.

This closes M1 (docs/10-milestones.md): headless core loop + Anthropic
provider, config loading, all six built-in tools, and the debug CLI.
131 tests passing across the workspace, clippy clean, fmt clean.
2026-07-08 17:28:37 +02:00
Erik Simon bbac60d744 harness-providers: Anthropic codec + provider
/v1/messages request builder (cache_control breakpoints on the first 2
system blocks + last 2 messages, tool schema -> input_schema, extended
thinking budget) and an SSE decoder built on eventsource-stream, mapping
content_block_start/delta/stop and message_delta into our normalized
LlmEvent stream (text, thinking+signature, streamed tool-call JSON
accumulated and parsed at content_block_stop, usage merged from
message_start + message_delta). AnthropicProvider wires this to reqwest
with x-api-key/anthropic-version/anthropic-beta headers and classifies
HTTP errors into RateLimited/Auth/Overloaded/Http. ProviderRegistry
resolves "provider/model" strings.

Also tightened processor::process_step's cancellation: the event loop now
selects the stream poll against ctx.cancel instead of only checking at the
top of the loop, so a blocked provider stream is actually interrupted by
abort (matches docs/02-engine.md's cancellation semantics).

127 tests passing, clippy clean.
2026-07-08 17:25:35 +02:00
Erik Simon bfb2dca7de harness-tools: edit tool with opencode's replacer chain, ported verbatim
Direct port of ~/repos/opencode/packages/opencode/src/tool/edit.ts: the
9-stage replacer chain (Simple, LineTrimmed, BlockAnchor, WhitespaceNormalized,
IndentationFlexible, EscapeNormalized, TrimmedBoundary, ContextAware,
MultiOccurrence), Levenshtein-based block-anchor similarity, and the
disproportionate-match guard that hard-stops rather than falling through to
the next candidate. Also ports edit.test.ts's scenarios: new-file creation,
BOM preservation, CRLF handling, replaceAll, directory/not-found/identical
errors, loose block-anchor rejection, and concurrent edits to the same file
serializing through a per-path tokio::Mutex without losing either change.

99 tests passing across the workspace, clippy clean. This lands the last
of the six M1 built-in tools (read/write/edit/bash/glob/grep).
2026-07-08 17:19:43 +02:00
Erik Simon 27ab6de4f5 harness-tools: read, write, bash, glob, grep
Five of the six M1 built-ins (edit's replacer chain is a separate port).
bash uses process_group(0) + SIGKILL-the-group on timeout/cancel; glob/grep
are gitignore-aware via ignore::WalkBuilder and don't ask permission
(read-only); read/write/bash ask through ctx.ask with opencode's coarser
"always" pattern (first word + wildcard for bash, path for edit/read).
Wired tool output through the central 30k-char truncate() in the processor
so every tool gets spill-to-disk behavior for free. 70 tests passing,
clippy clean.
2026-07-08 17:12:48 +02:00
Erik Simon a68ca02894 M1 core: tool trait, permission service, config, Provider trait, engine loop
harness-core now has everything the headless agent loop needs:
- Tool trait/ToolCtx/ToolRegistry + 30k-char head+tail output truncation
- PermissionService: async ask over a oneshot + AppEvent::PermissionAsked,
  Once/Always/Reject replies, an auto-approve stub for tests/headless runs
- Config: JSONC loading, bundled/global/project-chain/env precedence,
  {env:VAR} and {file:path} interpolation
- llm.rs: LlmEvent/LlmRequest/Provider trait, wire message/content types
- engine/: outer loop (run_session), inner stream processor (persists
  parts/messages as events arrive, executes tool calls inline), retry
  policy (retries only the pre-first-event window), doom-loop guard,
  system prompt assembly

Verified end-to-end against a scripted MockProvider: text -> tool call
(read) -> final text, with messages/parts persisted in the right shape,
plus a provider-error-before-any-event case surfacing as Errored (no
partial message left behind). 49 tests passing, clippy clean.
2026-07-08 17:05:37 +02:00
Erik Simon 5662b773b0 Remove GitHub Actions CI 2026-07-08 16:44:34 +02:00
Erik Simon 8b16348b4c M0: scaffold Cargo workspace, core types, event bus, permission engine, storage actor
Seven-crate workspace per docs/01-architecture.md. harness-core gets the
domain types (Session/Message/Part/ToolState), a broadcast EventBus, the
last-match-wins wildcard permission evaluator, and a SQLite storage actor
(dedicated thread + mpsc, JSON-blob rows) with roundtrip tests. All other
crates are compiling stubs. CI runs fmt/clippy -D warnings/test.
2026-07-08 16:28:42 +02:00
63 changed files with 115 additions and 8428 deletions
Generated
+4 -622
View File
@@ -29,18 +29,6 @@ dependencies = [
"memchr", "memchr",
] ]
[[package]]
name = "allocator-api2"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
[[package]]
name = "anyhow"
version = "1.0.103"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3"
[[package]] [[package]]
name = "async-compression" name = "async-compression"
version = "0.4.42" version = "0.4.42"
@@ -127,21 +115,6 @@ version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
[[package]]
name = "cassowary"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53"
[[package]]
name = "castaway"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a"
dependencies = [
"rustversion",
]
[[package]] [[package]]
name = "cc" name = "cc"
version = "1.2.66" version = "1.2.66"
@@ -175,20 +148,6 @@ dependencies = [
"rand_core 0.10.1", "rand_core 0.10.1",
] ]
[[package]]
name = "compact_str"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7fd622ebbb56a5b2ccb651b32b911cdeb2a9b4b11776b2473bf26a26a286244e"
dependencies = [
"castaway",
"cfg-if",
"itoa",
"rustversion",
"ryu",
"static_assertions",
]
[[package]] [[package]]
name = "compression-codecs" name = "compression-codecs"
version = "0.4.38" version = "0.4.38"
@@ -206,17 +165,6 @@ version = "0.4.32"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc14f565cf027a105f7a44ccf9e5b424348421a1d8952a8fc9d499d313107789" checksum = "cc14f565cf027a105f7a44ccf9e5b424348421a1d8952a8fc9d499d313107789"
[[package]]
name = "console"
version = "0.16.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4fe5f465a4f6fee88fad41b85d990f84c835335e85b5d9e6e63e0d06d28cba7c"
dependencies = [
"encode_unicode",
"libc",
"windows-sys 0.61.2",
]
[[package]] [[package]]
name = "cpufeatures" name = "cpufeatures"
version = "0.3.0" version = "0.3.0"
@@ -235,15 +183,6 @@ dependencies = [
"cfg-if", "cfg-if",
] ]
[[package]]
name = "crossbeam-channel"
version = "0.5.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d85363c37faeca707aef026efa9f3b34d077bce547e48f770770625c6013679e"
dependencies = [
"crossbeam-utils",
]
[[package]] [[package]]
name = "crossbeam-deque" name = "crossbeam-deque"
version = "0.8.7" version = "0.8.7"
@@ -269,72 +208,6 @@ version = "0.8.22"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17" checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17"
[[package]]
name = "crossterm"
version = "0.28.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6"
dependencies = [
"bitflags",
"crossterm_winapi",
"futures-core",
"mio",
"parking_lot",
"rustix 0.38.44",
"signal-hook",
"signal-hook-mio",
"winapi",
]
[[package]]
name = "crossterm_winapi"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b"
dependencies = [
"winapi",
]
[[package]]
name = "darling"
version = "0.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d"
dependencies = [
"darling_core",
"darling_macro",
]
[[package]]
name = "darling_core"
version = "0.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0"
dependencies = [
"ident_case",
"proc-macro2",
"quote",
"strsim",
"syn",
]
[[package]]
name = "darling_macro"
version = "0.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d"
dependencies = [
"darling_core",
"quote",
"syn",
]
[[package]]
name = "deranged"
version = "0.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
[[package]] [[package]]
name = "dirs" name = "dirs"
version = "5.0.1" version = "5.0.1"
@@ -373,18 +246,6 @@ version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
[[package]]
name = "either"
version = "1.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e"
[[package]]
name = "encode_unicode"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0"
[[package]] [[package]]
name = "encoding_rs" name = "encoding_rs"
version = "0.8.35" version = "0.8.35"
@@ -403,12 +264,6 @@ dependencies = [
"encoding_rs", "encoding_rs",
] ]
[[package]]
name = "equivalent"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
[[package]] [[package]]
name = "errno" name = "errno"
version = "0.3.14" version = "0.3.14"
@@ -464,12 +319,6 @@ dependencies = [
"miniz_oxide", "miniz_oxide",
] ]
[[package]]
name = "foldhash"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
[[package]] [[package]]
name = "form_urlencoded" name = "form_urlencoded"
version = "1.2.2" version = "1.2.2"
@@ -567,15 +416,6 @@ dependencies = [
"slab", "slab",
] ]
[[package]]
name = "getopts"
version = "0.2.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfe4fbac503b8d1f88e6676011885f34b7174f46e59956bba534ba83abded4df"
dependencies = [
"unicode-width 0.2.0",
]
[[package]] [[package]]
name = "getrandom" name = "getrandom"
version = "0.2.17" version = "0.2.17"
@@ -669,20 +509,16 @@ dependencies = [
name = "harness-app" name = "harness-app"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"async-trait",
"dirs", "dirs",
"futures",
"harness-core", "harness-core",
"harness-lsp", "harness-lsp",
"harness-mcp", "harness-mcp",
"harness-providers", "harness-providers",
"harness-tools", "harness-tools",
"serde_json",
"tempfile", "tempfile",
"thiserror 2.0.18", "thiserror 2.0.18",
"tokio", "tokio",
"tokio-util", "tokio-util",
"tracing",
] ]
[[package]] [[package]]
@@ -698,7 +534,6 @@ dependencies = [
"schemars", "schemars",
"serde", "serde",
"serde_json", "serde_json",
"serde_yaml_ng",
"tempfile", "tempfile",
"thiserror 2.0.18", "thiserror 2.0.18",
"tokio", "tokio",
@@ -728,14 +563,12 @@ dependencies = [
"async-stream", "async-stream",
"async-trait", "async-trait",
"bytes", "bytes",
"dirs",
"eventsource-stream", "eventsource-stream",
"futures", "futures",
"harness-core", "harness-core",
"reqwest", "reqwest",
"serde", "serde",
"serde_json", "serde_json",
"tempfile",
"thiserror 2.0.18", "thiserror 2.0.18",
"tokio", "tokio",
"tokio-util", "tokio-util",
@@ -769,22 +602,9 @@ dependencies = [
name = "harness-tui" name = "harness-tui"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"anyhow",
"crossterm",
"dirs",
"futures",
"harness-app", "harness-app",
"harness-core", "harness-core",
"insta",
"pulldown-cmark",
"ratatui",
"serde_json",
"tokio", "tokio",
"tokio-util",
"tracing",
"tracing-appender",
"tracing-subscriber",
"tui-textarea",
] ]
[[package]] [[package]]
@@ -796,38 +616,15 @@ dependencies = [
"ahash", "ahash",
] ]
[[package]]
name = "hashbrown"
version = "0.15.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
dependencies = [
"allocator-api2",
"equivalent",
"foldhash",
]
[[package]]
name = "hashbrown"
version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
[[package]] [[package]]
name = "hashlink" name = "hashlink"
version = "0.9.1" version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af" checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af"
dependencies = [ dependencies = [
"hashbrown 0.14.5", "hashbrown",
] ]
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]] [[package]]
name = "http" name = "http"
version = "1.4.2" version = "1.4.2"
@@ -1008,12 +805,6 @@ dependencies = [
"zerovec", "zerovec",
] ]
[[package]]
name = "ident_case"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
[[package]] [[package]]
name = "idna" name = "idna"
version = "1.1.0" version = "1.1.0"
@@ -1051,65 +842,12 @@ dependencies = [
"winapi-util", "winapi-util",
] ]
[[package]]
name = "indexmap"
version = "2.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
dependencies = [
"equivalent",
"hashbrown 0.17.1",
]
[[package]]
name = "indoc"
version = "2.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706"
dependencies = [
"rustversion",
]
[[package]]
name = "insta"
version = "1.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86f0f8fee8c926415c58d6ae43a08523a26faccb2323f5e6b644fe7dd4ef6b82"
dependencies = [
"console",
"once_cell",
"similar",
"tempfile",
]
[[package]]
name = "instability"
version = "0.3.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5eb2d60ef19920a3a9193c3e371f726ec1dafc045dac788d0fb3704272458971"
dependencies = [
"darling",
"indoc",
"proc-macro2",
"quote",
"syn",
]
[[package]] [[package]]
name = "ipnet" name = "ipnet"
version = "2.12.0" version = "2.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2"
[[package]]
name = "itertools"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
dependencies = [
"either",
]
[[package]] [[package]]
name = "itoa" name = "itoa"
version = "1.0.18" version = "1.0.18"
@@ -1136,12 +874,6 @@ dependencies = [
"serde_json", "serde_json",
] ]
[[package]]
name = "lazy_static"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
[[package]] [[package]]
name = "libc" name = "libc"
version = "0.2.186" version = "0.2.186"
@@ -1168,12 +900,6 @@ dependencies = [
"vcpkg", "vcpkg",
] ]
[[package]]
name = "linux-raw-sys"
version = "0.4.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"
[[package]] [[package]]
name = "linux-raw-sys" name = "linux-raw-sys"
version = "0.12.1" version = "0.12.1"
@@ -1201,30 +927,12 @@ version = "0.4.33"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
[[package]]
name = "lru"
version = "0.12.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38"
dependencies = [
"hashbrown 0.15.5",
]
[[package]] [[package]]
name = "lru-slab" name = "lru-slab"
version = "0.1.2" version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
[[package]]
name = "matchers"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"
dependencies = [
"regex-automata",
]
[[package]] [[package]]
name = "memchr" name = "memchr"
version = "2.8.3" version = "2.8.3"
@@ -1263,7 +971,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02bd0af71c67b473010cbbc60715ee815645a4dc942899111f494b4b737d6fda" checksum = "02bd0af71c67b473010cbbc60715ee815645a4dc942899111f494b4b737d6fda"
dependencies = [ dependencies = [
"libc", "libc",
"log",
"wasi", "wasi",
"windows-sys 0.61.2", "windows-sys 0.61.2",
] ]
@@ -1278,21 +985,6 @@ dependencies = [
"minimal-lexical", "minimal-lexical",
] ]
[[package]]
name = "nu-ansi-term"
version = "0.50.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "num-conv"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
[[package]] [[package]]
name = "once_cell" name = "once_cell"
version = "1.21.4" version = "1.21.4"
@@ -1328,12 +1020,6 @@ dependencies = [
"windows-link", "windows-link",
] ]
[[package]]
name = "paste"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
[[package]] [[package]]
name = "percent-encoding" name = "percent-encoding"
version = "2.3.2" version = "2.3.2"
@@ -1361,12 +1047,6 @@ dependencies = [
"zerovec", "zerovec",
] ]
[[package]]
name = "powerfmt"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
[[package]] [[package]]
name = "ppv-lite86" name = "ppv-lite86"
version = "0.2.21" version = "0.2.21"
@@ -1385,25 +1065,6 @@ dependencies = [
"unicode-ident", "unicode-ident",
] ]
[[package]]
name = "pulldown-cmark"
version = "0.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f86ba2052aebccc42cbbb3ed234b8b13ce76f75c3551a303cb2bcffcff12bb14"
dependencies = [
"bitflags",
"getopts",
"memchr",
"pulldown-cmark-escape",
"unicase",
]
[[package]]
name = "pulldown-cmark-escape"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae"
[[package]] [[package]]
name = "quinn" name = "quinn"
version = "0.11.11" version = "0.11.11"
@@ -1536,27 +1197,6 @@ dependencies = [
"rand_core 0.10.1", "rand_core 0.10.1",
] ]
[[package]]
name = "ratatui"
version = "0.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eabd94c2f37801c20583fc49dd5cd6b0ba68c716787c2dd6ed18571e1e63117b"
dependencies = [
"bitflags",
"cassowary",
"compact_str",
"crossterm",
"indoc",
"instability",
"itertools",
"lru",
"paste",
"strum",
"unicode-segmentation",
"unicode-truncate",
"unicode-width 0.2.0",
]
[[package]] [[package]]
name = "redox_syscall" name = "redox_syscall"
version = "0.5.18" version = "0.5.18"
@@ -1669,19 +1309,6 @@ version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
[[package]]
name = "rustix"
version = "0.38.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"
dependencies = [
"bitflags",
"errno",
"libc",
"linux-raw-sys 0.4.15",
"windows-sys 0.52.0",
]
[[package]] [[package]]
name = "rustix" name = "rustix"
version = "1.1.4" version = "1.1.4"
@@ -1691,7 +1318,7 @@ dependencies = [
"bitflags", "bitflags",
"errno", "errno",
"libc", "libc",
"linux-raw-sys 0.12.1", "linux-raw-sys",
"windows-sys 0.61.2", "windows-sys 0.61.2",
] ]
@@ -1847,28 +1474,6 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "serde_yaml_ng"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b4db627b98b36d4203a7b458cf3573730f2bb591b28871d916dfa9efabfd41f"
dependencies = [
"indexmap",
"itoa",
"ryu",
"serde",
"unsafe-libyaml",
]
[[package]]
name = "sharded-slab"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"
dependencies = [
"lazy_static",
]
[[package]] [[package]]
name = "shell-words" name = "shell-words"
version = "1.1.1" version = "1.1.1"
@@ -1881,27 +1486,6 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "signal-hook"
version = "0.3.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2"
dependencies = [
"libc",
"signal-hook-registry",
]
[[package]]
name = "signal-hook-mio"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc"
dependencies = [
"libc",
"mio",
"signal-hook",
]
[[package]] [[package]]
name = "signal-hook-registry" name = "signal-hook-registry"
version = "1.4.8" version = "1.4.8"
@@ -1952,52 +1536,12 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
[[package]]
name = "static_assertions"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "strum"
version = "0.26.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06"
dependencies = [
"strum_macros",
]
[[package]]
name = "strum_macros"
version = "0.26.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be"
dependencies = [
"heck",
"proc-macro2",
"quote",
"rustversion",
"syn",
]
[[package]] [[package]]
name = "subtle" name = "subtle"
version = "2.6.1" version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "symlink"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7973cce6668464ea31f176d85b13c7ab3bba2cb3b77a2ed26abd7801688010a"
[[package]] [[package]]
name = "syn" name = "syn"
version = "2.0.118" version = "2.0.118"
@@ -2036,9 +1580,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [ dependencies = [
"fastrand", "fastrand",
"getrandom 0.4.3", "getrandom 0.3.4",
"once_cell", "once_cell",
"rustix 1.1.4", "rustix",
"windows-sys 0.61.2", "windows-sys 0.61.2",
] ]
@@ -2082,45 +1626,6 @@ dependencies = [
"syn", "syn",
] ]
[[package]]
name = "thread_local"
version = "1.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185"
dependencies = [
"cfg-if",
]
[[package]]
name = "time"
version = "0.3.53"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "18dfaaeddcb932337b5e7866ee7d0ce9b76d2fd092997146f187ec09b4558a50"
dependencies = [
"deranged",
"num-conv",
"powerfmt",
"serde_core",
"time-core",
"time-macros",
]
[[package]]
name = "time-core"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"
[[package]]
name = "time-macros"
version = "0.2.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c431b87111666e491a90baa837f914fb45cd5dc3c268591b0220ff5057f2085f"
dependencies = [
"num-conv",
"time-core",
]
[[package]] [[package]]
name = "tinystr" name = "tinystr"
version = "0.8.3" version = "0.8.3"
@@ -2258,19 +1763,6 @@ dependencies = [
"tracing-core", "tracing-core",
] ]
[[package]]
name = "tracing-appender"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "050686193eb999b4bb3bc2acfa891a13da00f79734704c4b8b4ef1a10b368a3c"
dependencies = [
"crossbeam-channel",
"symlink",
"thiserror 2.0.18",
"time",
"tracing-subscriber",
]
[[package]] [[package]]
name = "tracing-attributes" name = "tracing-attributes"
version = "0.1.31" version = "0.1.31"
@@ -2289,36 +1781,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
dependencies = [ dependencies = [
"once_cell", "once_cell",
"valuable",
]
[[package]]
name = "tracing-log"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"
dependencies = [
"log",
"once_cell",
"tracing-core",
]
[[package]]
name = "tracing-subscriber"
version = "0.3.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319"
dependencies = [
"matchers",
"nu-ansi-term",
"once_cell",
"regex-automata",
"sharded-slab",
"smallvec",
"thread_local",
"tracing",
"tracing-core",
"tracing-log",
] ]
[[package]] [[package]]
@@ -2327,17 +1789,6 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
[[package]]
name = "tui-textarea"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0a5318dd619ed73c52a9417ad19046724effc1287fb75cdcc4eca1d6ac1acbae"
dependencies = [
"crossterm",
"ratatui",
"unicode-width 0.2.0",
]
[[package]] [[package]]
name = "ulid" name = "ulid"
version = "1.2.1" version = "1.2.1"
@@ -2349,53 +1800,12 @@ dependencies = [
"web-time", "web-time",
] ]
[[package]]
name = "unicase"
version = "2.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142"
[[package]] [[package]]
name = "unicode-ident" name = "unicode-ident"
version = "1.0.24" version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "unicode-segmentation"
version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
[[package]]
name = "unicode-truncate"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b3644627a5af5fa321c95b9b235a72fd24cd29c648c2c379431e6628655627bf"
dependencies = [
"itertools",
"unicode-segmentation",
"unicode-width 0.1.14",
]
[[package]]
name = "unicode-width"
version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af"
[[package]]
name = "unicode-width"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd"
[[package]]
name = "unsafe-libyaml"
version = "0.2.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861"
[[package]] [[package]]
name = "untrusted" name = "untrusted"
version = "0.9.0" version = "0.9.0"
@@ -2420,12 +1830,6 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
[[package]]
name = "valuable"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
[[package]] [[package]]
name = "vcpkg" name = "vcpkg"
version = "0.2.15" version = "0.2.15"
@@ -2569,22 +1973,6 @@ dependencies = [
"rustls-pki-types", "rustls-pki-types",
] ]
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]] [[package]]
name = "winapi-util" name = "winapi-util"
version = "0.1.11" version = "0.1.11"
@@ -2594,12 +1982,6 @@ dependencies = [
"windows-sys 0.61.2", "windows-sys 0.61.2",
] ]
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]] [[package]]
name = "windows-link" name = "windows-link"
version = "0.2.1" version = "0.2.1"
-4
View File
@@ -12,15 +12,11 @@ harness-mcp = { workspace = true }
harness-lsp = { workspace = true } harness-lsp = { workspace = true }
tokio = { workspace = true } tokio = { workspace = true }
tokio-util = { workspace = true } tokio-util = { workspace = true }
async-trait = { workspace = true }
dirs = { workspace = true } dirs = { workspace = true }
thiserror = { workspace = true } thiserror = { workspace = true }
tracing = { workspace = true }
[dev-dependencies] [dev-dependencies]
tempfile = { workspace = true } tempfile = { workspace = true }
futures = { workspace = true }
serde_json = { workspace = true }
[lints] [lints]
workspace = true workspace = true
File diff suppressed because it is too large Load Diff
-1
View File
@@ -11,7 +11,6 @@ futures = { workspace = true }
async-trait = { workspace = true } async-trait = { workspace = true }
serde = { workspace = true } serde = { workspace = true }
serde_json = { workspace = true } serde_json = { workspace = true }
serde_yaml_ng = { workspace = true }
schemars = { workspace = true } schemars = { workspace = true }
rusqlite = { workspace = true } rusqlite = { workspace = true }
globset = { workspace = true } globset = { workspace = true }
@@ -1,12 +0,0 @@
---
description: UI and interaction design specialist for user-facing surfaces
mode: subagent
temperature: 0.4
tools: { task: false }
---
You are Designer, a UI and interaction design specialist. You handle user-facing surfaces:
layout, component structure, styling, and interaction details.
- Understand the existing design language before proposing changes; stay consistent with it.
- When implementing, make focused edits and describe the visual/interaction effect.
- Call out accessibility and responsive concerns relevant to the change.
@@ -1,16 +0,0 @@
---
description: Read-only reconnaissance specialist for mapping code and finding relevant files
mode: subagent
temperature: 0.1
tools: { write: false, edit: false, task: false }
permission:
- { permission: "edit", pattern: "*", action: deny }
- { permission: "write", pattern: "*", action: deny }
---
You are Explorer, a read-only reconnaissance specialist. You locate the code, files, and
facts the orchestrator needs and report back concisely.
- Use read, glob, grep, and bash (read-only commands) to investigate.
- Never modify files. Return a focused summary with concrete `path:line` references, not
file dumps.
- State what you found and, briefly, what you could not find.
@@ -1,13 +0,0 @@
---
description: Implementation specialist that makes focused code changes and verifies them
mode: subagent
temperature: 0.2
tools: { task: false }
---
You are Fixer, an implementation specialist. You take a well-scoped change, implement it,
and verify it compiles/tests.
- Make the smallest change that satisfies the request; match the surrounding code's style.
- Use read/grep to understand context before editing; use bash to build and run tests.
- Report exactly what you changed (files and the essence of the diff) and the result of any
verification you ran.
@@ -1,15 +0,0 @@
---
description: Documentation and knowledge lookup specialist
mode: subagent
temperature: 0.1
tools: { write: false, edit: false, task: false }
permission:
- { permission: "edit", pattern: "*", action: deny }
- { permission: "write", pattern: "*", action: deny }
---
You are Librarian. You find and summarize documentation, comments, READMEs, config, and
other in-repo knowledge on request.
- Search docs and source for the relevant material with read, glob, and grep.
- Quote the authoritative source with its `path:line`; do not invent details.
- Return a concise, well-organized summary with pointers back to the sources.
@@ -1,15 +0,0 @@
---
description: Deep-reasoning analyst for architecture, debugging, and design trade-offs
mode: subagent
temperature: 0.3
tools: { write: false, edit: false, task: false }
permission:
- { permission: "edit", pattern: "*", action: deny }
- { permission: "write", pattern: "*", action: deny }
---
You are Oracle, a deep-reasoning analyst. You are consulted for hard questions:
root-causing bugs, weighing architectural trade-offs, and reviewing designs.
- Read whatever code and context you need, but do not modify anything.
- Reason carefully and explicitly; state assumptions and the evidence behind conclusions.
- Return a decisive recommendation with the reasoning that supports it.
@@ -1,19 +0,0 @@
---
description: Primary coordinator that plans work and delegates to specialists
mode: primary
temperature: 0.2
---
You are the orchestrator. You plan the work, delegate focused pieces to specialist
subagents via the `task` tool, and synthesize their results into a final answer.
Guidelines:
- Break the request into concrete, independently-verifiable pieces.
- Prefer delegating reconnaissance and analysis to subagents so your own context stays
focused; do the integration and final write-up yourself.
- Launch background tasks for long-running independent work, then continue planning.
Do not poll running jobs — wait for completion and reconcile terminal jobs before your
final response.
- Reuse a completed specialist session (by its job alias) when following up on the same
thread of work.
{{SUBAGENTS}}
-496
View File
@@ -1,496 +0,0 @@
//! Agent definitions and registry.
//!
//! All agent *behavior* lives in markdown + config — the engine only understands `mode`, tool
//! filters, permissions, model, and depth. Definitions are layered (bundled → global → project
//! → config patch); later layers win by name. See `docs/04-multiagent.md`.
use std::collections::HashMap;
use std::path::Path;
use serde::Deserialize;
use crate::config::AgentPatch;
use crate::permission::{Rule, Ruleset};
use crate::types::ModelRef;
/// Marker in a primary agent's prompt replaced at load time with the routing list of enabled
/// subagents (name + description). Keeps routing text in sync with the enabled agent set.
const SUBAGENTS_MARKER: &str = "{{SUBAGENTS}}";
const BUNDLED: &[(&str, &str)] = &[
(
"orchestrator",
include_str!("../../assets/agents/orchestrator.md"),
),
("explorer", include_str!("../../assets/agents/explorer.md")),
("oracle", include_str!("../../assets/agents/oracle.md")),
(
"librarian",
include_str!("../../assets/agents/librarian.md"),
),
("fixer", include_str!("../../assets/agents/fixer.md")),
("designer", include_str!("../../assets/agents/designer.md")),
];
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AgentMode {
Primary,
#[default]
Subagent,
All,
}
impl AgentMode {
fn parse(s: &str) -> Option<Self> {
match s.trim().to_ascii_lowercase().as_str() {
"primary" => Some(Self::Primary),
"subagent" => Some(Self::Subagent),
"all" => Some(Self::All),
_ => None,
}
}
/// Whether this agent can be invoked as a subagent via the `task` tool.
pub fn is_subagent(self) -> bool {
matches!(self, Self::Subagent | Self::All)
}
/// Whether this agent can drive a top-level (primary) session.
pub fn is_primary(self) -> bool {
matches!(self, Self::Primary | Self::All)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AgentSource {
Bundled,
Global,
Project,
Config,
}
#[derive(Debug, Clone)]
pub struct AgentDef {
pub name: String,
pub description: String,
pub mode: AgentMode,
/// `None` = follow the session model.
pub model: Option<ModelRef>,
pub temperature: Option<f32>,
pub prompt: String,
pub permissions: Ruleset,
/// Tool enable/disable overrides (wildcard keys allowed); absent = inherit default.
pub tools: HashMap<String, bool>,
pub max_steps: Option<u32>,
pub source: AgentSource,
}
#[derive(Debug, thiserror::Error)]
pub enum AgentError {
#[error("agent {0}: {1}")]
Frontmatter(String, String),
}
/// YAML frontmatter shape (opencode-compatible).
#[derive(Debug, Default, Deserialize)]
#[serde(default)]
struct Frontmatter {
description: Option<String>,
mode: Option<String>,
model: Option<String>,
temperature: Option<f32>,
tools: Option<HashMap<String, bool>>,
permission: Option<Vec<Rule>>,
max_steps: Option<u32>,
disable: Option<bool>,
}
fn parse_model_ref(s: &str) -> Option<ModelRef> {
s.split_once('/')
.map(|(p, m)| ModelRef::new(p.trim(), m.trim()))
}
/// Splits a markdown agent file into (frontmatter, body). A file without a leading `---`
/// fence is treated as an all-body prompt with empty frontmatter.
fn split_frontmatter(content: &str) -> (&str, &str) {
let rest = match content
.strip_prefix("---\n")
.or_else(|| content.strip_prefix("---\r\n"))
{
Some(r) => r,
None => return ("", content),
};
// Find the closing fence line.
for delim in ["\n---\n", "\n---\r\n"] {
if let Some(idx) = rest.find(delim) {
let body_start = idx + delim.len();
return (&rest[..idx], &rest[body_start..]);
}
}
// Trailing fence with no body / no trailing newline.
if let Some(fm) = rest.strip_suffix("\n---").or(Some(rest)) {
if rest.ends_with("\n---") {
return (fm, "");
}
}
("", content)
}
/// Parses one markdown agent definition. Returns `Ok(None)` when the file marks itself
/// `disable: true`.
fn parse_agent(
name: &str,
source: AgentSource,
content: &str,
) -> Result<Option<AgentDef>, AgentError> {
let (fm_raw, body) = split_frontmatter(content);
let fm: Frontmatter = if fm_raw.trim().is_empty() {
Frontmatter::default()
} else {
serde_yaml_ng::from_str(fm_raw)
.map_err(|e| AgentError::Frontmatter(name.to_string(), e.to_string()))?
};
if fm.disable == Some(true) {
return Ok(None);
}
Ok(Some(AgentDef {
name: name.to_string(),
description: fm.description.unwrap_or_default(),
mode: fm
.mode
.as_deref()
.and_then(AgentMode::parse)
.unwrap_or_default(),
model: fm.model.as_deref().and_then(parse_model_ref),
temperature: fm.temperature,
prompt: body.trim_end().to_string(),
permissions: fm.permission.unwrap_or_default(),
tools: fm.tools.unwrap_or_default(),
max_steps: fm.max_steps,
source,
}))
}
/// Applies a config `AgentPatch` onto an existing definition (only set fields override).
fn apply_patch(def: &mut AgentDef, patch: &AgentPatch) {
if let Some(mode) = patch.mode.as_deref().and_then(AgentMode::parse) {
def.mode = mode;
}
if let Some(model) = patch.model.as_deref().and_then(parse_model_ref) {
def.model = Some(model);
}
if let Some(temp) = patch.temperature {
def.temperature = Some(temp);
}
if let Some(prompt) = &patch.prompt {
def.prompt = prompt.clone();
}
if let Some(tools) = &patch.tools {
def.tools.extend(tools.clone());
}
if let Some(permission) = &patch.permission {
def.permissions = permission.clone();
}
}
#[derive(Debug, Clone, Default)]
pub struct AgentRegistry {
agents: HashMap<String, AgentDef>,
}
impl AgentRegistry {
pub fn get(&self, name: &str) -> Option<&AgentDef> {
self.agents.get(name)
}
pub fn all(&self) -> Vec<&AgentDef> {
self.agents.values().collect()
}
pub fn len(&self) -> usize {
self.agents.len()
}
pub fn is_empty(&self) -> bool {
self.agents.is_empty()
}
/// Just the bundled agents — the default when no overrides are configured (tests, headless).
pub fn bundled() -> Self {
let mut reg = Self::default();
reg.load_markdown_layer(
BUNDLED.iter().map(|(n, c)| (n.to_string(), *c)),
AgentSource::Bundled,
);
reg.generate_routing();
reg
}
/// Full layered load: bundled → global dir → project dir → config patches.
pub fn load(
config_agents: &HashMap<String, AgentPatch>,
global_dir: Option<&Path>,
project_dir: Option<&Path>,
) -> Self {
let mut reg = Self::default();
reg.load_markdown_layer(
BUNDLED.iter().map(|(n, c)| (n.to_string(), *c)),
AgentSource::Bundled,
);
if let Some(dir) = global_dir {
reg.load_dir(dir, AgentSource::Global);
}
if let Some(dir) = project_dir {
reg.load_dir(dir, AgentSource::Project);
}
reg.apply_config(config_agents);
reg.generate_routing();
reg
}
fn load_markdown_layer<I, S>(&mut self, files: I, source: AgentSource)
where
I: IntoIterator<Item = (String, S)>,
S: AsRef<str>,
{
for (name, content) in files {
match parse_agent(&name, source, content.as_ref()) {
Ok(Some(def)) => {
self.agents.insert(name, def);
}
Ok(None) => {
self.agents.remove(&name); // disable: true removes an earlier layer
}
Err(e) => tracing::warn!(error = %e, "skipping malformed agent"),
}
}
}
fn load_dir(&mut self, dir: &Path, source: AgentSource) {
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
let mut files: Vec<(String, String)> = Vec::new();
for entry in entries.flatten() {
let path = entry.path();
if path.extension().and_then(|e| e.to_str()) != Some("md") {
continue;
}
let Some(name) = path.file_stem().and_then(|s| s.to_str()) else {
continue;
};
if let Ok(content) = std::fs::read_to_string(&path) {
files.push((name.to_string(), content));
}
}
files.sort();
self.load_markdown_layer(files, source);
}
fn apply_config(&mut self, config_agents: &HashMap<String, AgentPatch>) {
for (name, patch) in config_agents {
if patch.disable == Some(true) {
self.agents.remove(name);
continue;
}
if let Some(def) = self.agents.get_mut(name) {
apply_patch(def, patch);
} else if patch.model.is_some() || patch.prompt.is_some() {
// Unknown name with enough to stand on its own → custom agent.
let mut def = AgentDef {
name: name.clone(),
description: String::new(),
mode: AgentMode::default(),
model: None,
temperature: None,
prompt: String::new(),
permissions: Vec::new(),
tools: HashMap::new(),
max_steps: None,
source: AgentSource::Config,
};
apply_patch(&mut def, patch);
self.agents.insert(name.clone(), def);
}
}
}
/// Replaces `{{SUBAGENTS}}` in every primary agent's prompt with a generated routing list
/// of the enabled subagents (so disabling an agent removes it from routing text).
fn generate_routing(&mut self) {
let mut subagents: Vec<(String, String)> = self
.agents
.values()
.filter(|a| a.mode.is_subagent())
.map(|a| (a.name.clone(), a.description.clone()))
.collect();
subagents.sort();
let routing = if subagents.is_empty() {
"## Agents\n\nNo specialist subagents are available.".to_string()
} else {
let mut s = String::from("## Agents\n\nDelegate to these specialists via `task`:\n");
for (name, desc) in &subagents {
s.push_str(&format!("- **{name}** — {desc}\n"));
}
s
};
for agent in self.agents.values_mut() {
if agent.prompt.contains(SUBAGENTS_MARKER) {
agent.prompt = agent.prompt.replace(SUBAGENTS_MARKER, routing.trim_end());
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::permission::Action;
#[test]
fn bundled_loads_all_six_agents() {
let reg = AgentRegistry::bundled();
for name in [
"orchestrator",
"explorer",
"oracle",
"librarian",
"fixer",
"designer",
] {
assert!(reg.get(name).is_some(), "missing {name}");
}
assert_eq!(reg.len(), 6);
}
#[test]
fn parses_mode_model_temperature_tools_and_permissions() {
let md = "---\n\
description: test agent\n\
mode: subagent\n\
model: anthropic/claude-haiku-4-5\n\
temperature: 0.1\n\
tools: { write: false, bash: true }\n\
permission:\n\
\x20 - { permission: \"edit\", pattern: \"*\", action: deny }\n\
---\n\
You are a test agent.\n";
let def = parse_agent("tester", AgentSource::Bundled, md)
.unwrap()
.unwrap();
assert_eq!(def.description, "test agent");
assert_eq!(def.mode, AgentMode::Subagent);
assert_eq!(
def.model,
Some(ModelRef::new("anthropic", "claude-haiku-4-5"))
);
assert_eq!(def.temperature, Some(0.1));
assert_eq!(def.tools.get("write"), Some(&false));
assert_eq!(def.tools.get("bash"), Some(&true));
assert_eq!(def.permissions.len(), 1);
assert_eq!(def.permissions[0].action, Action::Deny);
assert_eq!(def.prompt, "You are a test agent.");
}
#[test]
fn body_without_frontmatter_is_all_prompt() {
let def = parse_agent("x", AgentSource::Global, "just a prompt")
.unwrap()
.unwrap();
assert_eq!(def.prompt, "just a prompt");
assert_eq!(def.mode, AgentMode::Subagent); // default
}
#[test]
fn disable_true_removes_agent() {
assert!(
parse_agent("x", AgentSource::Config, "---\ndisable: true\n---\nbody")
.unwrap()
.is_none()
);
}
#[test]
fn explorer_denies_writes_and_disables_edit_tool() {
let reg = AgentRegistry::bundled();
let explorer = reg.get("explorer").unwrap();
assert_eq!(explorer.mode, AgentMode::Subagent);
assert_eq!(explorer.tools.get("edit"), Some(&false));
assert!(explorer
.permissions
.iter()
.any(|r| r.permission == "write" && r.action == Action::Deny));
}
#[test]
fn orchestrator_routing_lists_subagents_and_drops_marker() {
let reg = AgentRegistry::bundled();
let prompt = &reg.get("orchestrator").unwrap().prompt;
assert!(!prompt.contains("{{SUBAGENTS}}"));
assert!(prompt.contains("explorer"));
assert!(prompt.contains("fixer"));
// The orchestrator itself is primary and must not list itself.
assert!(!prompt.contains("- **orchestrator**"));
}
#[test]
fn config_patch_overrides_only_set_fields() {
let mut patches = HashMap::new();
patches.insert(
"explorer".to_string(),
AgentPatch {
temperature: Some(0.9),
..Default::default()
},
);
let reg = AgentRegistry::load(&patches, None, None);
let explorer = reg.get("explorer").unwrap();
assert_eq!(explorer.temperature, Some(0.9)); // overridden
assert_eq!(explorer.mode, AgentMode::Subagent); // untouched
assert_eq!(explorer.tools.get("edit"), Some(&false)); // untouched
}
#[test]
fn config_disable_removes_and_unknown_with_model_creates() {
let mut patches = HashMap::new();
patches.insert(
"designer".to_string(),
AgentPatch {
disable: Some(true),
..Default::default()
},
);
patches.insert(
"custom".to_string(),
AgentPatch {
model: Some("openai/gpt-5".into()),
prompt: Some("custom prompt".into()),
..Default::default()
},
);
let reg = AgentRegistry::load(&patches, None, None);
assert!(reg.get("designer").is_none());
let custom = reg.get("custom").unwrap();
assert_eq!(custom.source, AgentSource::Config);
assert_eq!(custom.model, Some(ModelRef::new("openai", "gpt-5")));
assert_eq!(custom.prompt, "custom prompt");
}
#[test]
fn unknown_config_agent_without_model_or_prompt_is_ignored() {
let mut patches = HashMap::new();
patches.insert(
"ghost".to_string(),
AgentPatch {
temperature: Some(0.5),
..Default::default()
},
);
let reg = AgentRegistry::load(&patches, None, None);
assert!(reg.get("ghost").is_none());
}
}
-1
View File
@@ -29,7 +29,6 @@ const ENV_CONFIG_PATH: &str = "AI_HARNESS_CONFIG";
const PROVIDER_ENV_KEYS: &[(&str, &str)] = &[ const PROVIDER_ENV_KEYS: &[(&str, &str)] = &[
("anthropic", "ANTHROPIC_API_KEY"), ("anthropic", "ANTHROPIC_API_KEY"),
("openai", "OPENAI_API_KEY"), ("openai", "OPENAI_API_KEY"),
("opencode", "OPENCODE_API_KEY"),
]; ];
fn read_jsonc(path: &Path) -> Result<Value, ConfigError> { fn read_jsonc(path: &Path) -> Result<Value, ConfigError> {
-579
View File
@@ -1,579 +0,0 @@
//! Background job board — tracks subagent tasks spawned via the `task` tool so the
//! orchestrator can see running work, reconcile terminal results, and reuse completed
//! child sessions by alias. Simplified native port of oh-my-opencode-slim's
//! `background-job-board.ts`. See `docs/04-multiagent.md`.
//!
//! The board is an in-memory `RwLock<HashMap>` mirrored to the `job` table so it survives a
//! resume. All mutations persist through the passed-in `Store`.
use std::collections::HashMap;
use std::sync::RwLock;
use serde::{Deserialize, Serialize};
use crate::event::{AppEvent, EventBus, JobRecordEvent};
use crate::store::{Store, StoreError};
use crate::types::SessionId;
/// A file a child session read, surfaced on the board so the orchestrator knows what a
/// completed specialist already looked at.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ContextFile {
pub path: String,
pub lines: u32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum JobState {
Running,
Completed,
Error,
Cancelled,
}
impl JobState {
/// Terminal jobs are candidates for reconciliation; a completed one is reusable.
pub fn is_terminal(self) -> bool {
!matches!(self, JobState::Running)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JobRecord {
pub task_id: String,
/// Human-friendly handle: first 3 chars of the agent name + a per-agent counter (`exp-1`).
pub alias: String,
pub parent_session: SessionId,
pub child_session: SessionId,
pub agent: String,
pub description: String,
pub objective: Option<String>,
pub state: JobState,
/// Whether the orchestrator has already seen this job's terminal result.
pub reconciled: bool,
pub result_summary: Option<String>,
pub context_files: Vec<ContextFile>,
pub launched_at: i64,
pub updated_at: i64,
pub last_used_at: i64,
}
/// Parameters for registering a newly launched task on the board.
pub struct LaunchSpec {
pub task_id: String,
pub parent_session: SessionId,
pub child_session: SessionId,
pub agent: String,
pub description: String,
pub objective: Option<String>,
}
/// Result summaries are truncated to this many chars on the board.
const SUMMARY_MAX: usize = 2000;
/// Context files shown per job in the prompt injection.
const CONTEXT_FILES_SHOWN: usize = 8;
/// A read must cover at least this many lines to be worth reporting to the board.
pub const MIN_REPORTED_LINES: u32 = 10;
pub struct JobBoard {
store: Store,
bus: EventBus,
jobs: RwLock<HashMap<String, JobRecord>>,
max_reusable_per_agent: u32,
}
impl JobBoard {
/// Builds a board and loads any persisted jobs for `parent_session`'s tree from the store.
pub async fn load(
store: Store,
bus: EventBus,
parent_session: &SessionId,
max_reusable_per_agent: u32,
) -> Result<Self, StoreError> {
let existing = store.jobs_for_parent(parent_session.clone()).await?;
let mut jobs = HashMap::new();
for job in existing {
jobs.insert(job.task_id.clone(), job);
}
Ok(Self {
store,
bus,
jobs: RwLock::new(jobs),
max_reusable_per_agent,
})
}
/// Assigns the next alias for `agent` under this board: `<3-char-prefix>-<n>`.
fn next_alias(&self, agent: &str) -> String {
let prefix: String = agent.chars().take(3).collect();
let prefix = if prefix.is_empty() {
"job".to_string()
} else {
prefix.to_ascii_lowercase()
};
let n = self
.jobs
.read()
.unwrap()
.values()
.filter(|j| j.agent == agent)
.count()
+ 1;
format!("{prefix}-{n}")
}
/// Registers a freshly launched task and returns its assigned alias.
pub async fn register_launch(&self, spec: LaunchSpec, now: i64) -> Result<String, StoreError> {
let alias = self.next_alias(&spec.agent);
let record = JobRecord {
task_id: spec.task_id,
alias: alias.clone(),
parent_session: spec.parent_session,
child_session: spec.child_session,
agent: spec.agent,
description: spec.description,
objective: spec.objective,
state: JobState::Running,
reconciled: false,
result_summary: None,
context_files: Vec::new(),
launched_at: now,
updated_at: now,
last_used_at: now,
};
self.upsert(record).await?;
Ok(alias)
}
/// Marks a job terminal with an optional result summary (truncated).
pub async fn finish(
&self,
task_id: &str,
state: JobState,
result_summary: Option<String>,
now: i64,
) -> Result<(), StoreError> {
let Some(mut record) = self.get(task_id) else {
return Ok(());
};
record.state = state;
record.result_summary = result_summary.map(|s| truncate_summary(&s));
record.updated_at = now;
record.last_used_at = now;
self.upsert(record).await?;
if state == JobState::Completed {
self.trim_reusable(now).await?;
}
Ok(())
}
/// Records a file a child session read (deduping by path, keeping the largest read).
pub async fn report_context_file(
&self,
task_id: &str,
path: String,
lines: u32,
now: i64,
) -> Result<(), StoreError> {
if lines < MIN_REPORTED_LINES {
return Ok(());
}
let Some(mut record) = self.get(task_id) else {
return Ok(());
};
match record.context_files.iter_mut().find(|f| f.path == path) {
Some(existing) => existing.lines = existing.lines.max(lines),
None => record.context_files.push(ContextFile { path, lines }),
}
record.updated_at = now;
self.upsert(record).await
}
/// Resolves an alias or task id to a job for the given parent (reuse lookup). Only
/// completed (reusable) jobs match.
pub fn resolve_reusable(&self, parent: &SessionId, alias_or_id: &str) -> Option<JobRecord> {
self.jobs
.read()
.unwrap()
.values()
.find(|j| {
&j.parent_session == parent
&& j.state == JobState::Completed
&& (j.alias == alias_or_id || j.task_id == alias_or_id)
})
.cloned()
}
/// Bumps `last_used_at` when a completed session is reused, keeping it fresh in the LRU.
pub async fn touch(&self, task_id: &str, now: i64) -> Result<(), StoreError> {
let Some(mut record) = self.get(task_id) else {
return Ok(());
};
record.last_used_at = now;
self.upsert(record).await
}
/// Marks all terminal jobs `reconciled` — the orchestrator has now seen them.
pub async fn reconcile_terminal(&self, now: i64) -> Result<(), StoreError> {
let to_update: Vec<JobRecord> = {
let jobs = self.jobs.read().unwrap();
jobs.values()
.filter(|j| j.state.is_terminal() && !j.reconciled)
.cloned()
.collect()
};
for mut record in to_update {
record.reconciled = true;
record.updated_at = now;
self.upsert(record).await?;
}
Ok(())
}
pub fn is_empty(&self) -> bool {
self.jobs.read().unwrap().is_empty()
}
pub fn snapshot(&self) -> Vec<JobRecord> {
self.jobs.read().unwrap().values().cloned().collect()
}
/// Renders the board as a synthetic prompt block, or `None` when there is nothing to show.
/// Mirrors slim's `formatForPrompt`.
pub fn format_for_prompt(&self) -> Option<String> {
let jobs = self.jobs.read().unwrap();
if jobs.is_empty() {
return None;
}
let mut active: Vec<&JobRecord> = jobs
.values()
.filter(|j| !j.state.is_terminal() || !j.reconciled)
.collect();
let mut reusable: Vec<&JobRecord> = jobs
.values()
.filter(|j| j.state == JobState::Completed && j.reconciled)
.collect();
active.sort_by(|a, b| a.alias.cmp(&b.alias));
reusable.sort_by(|a, b| a.alias.cmp(&b.alias));
if active.is_empty() && reusable.is_empty() {
return None;
}
let mut out = String::from(
"### Background Job Board\n\
Do not poll running jobs; wait for completion. Reconcile terminal jobs before your \
final response.\nCompleted sessions are reusable by alias for the same specialist.\n",
);
if !active.is_empty() {
out.push_str("\n#### Active / Unreconciled\n");
for job in &active {
let state = state_label(job.state);
out.push_str(&format!(
"- {} / {} / {} / {state}",
job.alias, job.child_session, job.agent
));
if let Some(obj) = &job.objective {
out.push_str(&format!(" — Objective: {obj}"));
}
out.push('\n');
if let Some(summary) = &job.result_summary {
out.push_str(&format!(" Result: {summary}\n"));
}
}
}
if !reusable.is_empty() {
out.push_str("\n#### Reusable Sessions\n");
for job in &reusable {
out.push_str(&format!(
"- {} / {} / {} / completed\n",
job.alias, job.child_session, job.agent
));
if let Some(obj) = &job.objective {
out.push_str(&format!(" Objective: {obj}\n"));
}
if !job.context_files.is_empty() {
let files: Vec<&str> = job
.context_files
.iter()
.take(CONTEXT_FILES_SHOWN)
.map(|f| f.path.as_str())
.collect();
out.push_str(&format!(" Context read: {}\n", files.join(", ")));
}
}
}
Some(out)
}
fn get(&self, task_id: &str) -> Option<JobRecord> {
self.jobs.read().unwrap().get(task_id).cloned()
}
async fn upsert(&self, record: JobRecord) -> Result<(), StoreError> {
self.store.upsert_job(record.clone()).await?;
self.jobs
.write()
.unwrap()
.insert(record.task_id.clone(), record.clone());
self.bus.publish(AppEvent::JobUpdated {
job: JobRecordEvent(serde_json::to_value(&record).unwrap_or(serde_json::Value::Null)),
});
Ok(())
}
/// Keeps at most `max_reusable_per_agent` completed jobs per agent (LRU by `last_used_at`);
/// older completed jobs are dropped from the board and the store.
async fn trim_reusable(&self, _now: i64) -> Result<(), StoreError> {
let to_remove: Vec<String> = {
let jobs = self.jobs.read().unwrap();
let mut by_agent: HashMap<&str, Vec<&JobRecord>> = HashMap::new();
for job in jobs.values().filter(|j| j.state == JobState::Completed) {
by_agent.entry(job.agent.as_str()).or_default().push(job);
}
let mut remove = Vec::new();
for group in by_agent.values_mut() {
if group.len() as u32 <= self.max_reusable_per_agent {
continue;
}
// Oldest last_used_at first; drop the excess from the front.
group.sort_by_key(|j| j.last_used_at);
let excess = group.len() - self.max_reusable_per_agent as usize;
for job in group.iter().take(excess) {
remove.push(job.task_id.clone());
}
}
remove
};
for task_id in to_remove {
self.store.delete_job(task_id.clone()).await?;
self.jobs.write().unwrap().remove(&task_id);
}
Ok(())
}
}
fn state_label(state: JobState) -> &'static str {
match state {
JobState::Running => "running",
JobState::Completed => "completed",
JobState::Error => "error",
JobState::Cancelled => "cancelled",
}
}
fn truncate_summary(s: &str) -> String {
if s.len() <= SUMMARY_MAX {
return s.to_string();
}
let mut end = SUMMARY_MAX;
while !s.is_char_boundary(end) {
end -= 1;
}
format!("{}", &s[..end])
}
#[cfg(test)]
mod tests {
use super::*;
async fn board(max_reusable: u32) -> (Store, JobBoard, SessionId) {
let store = Store::open_in_memory().unwrap();
let bus = EventBus::new();
let parent = SessionId::new();
let board = JobBoard::load(store.clone(), bus, &parent, max_reusable)
.await
.unwrap();
(store, board, parent)
}
fn spec(
task_id: &str,
parent: SessionId,
child: SessionId,
agent: &str,
objective: Option<&str>,
) -> LaunchSpec {
LaunchSpec {
task_id: task_id.into(),
parent_session: parent,
child_session: child,
agent: agent.into(),
description: "d".into(),
objective: objective.map(Into::into),
}
}
#[tokio::test]
async fn alias_increments_per_agent() {
let (_store, board, parent) = board(2).await;
let a1 = board
.register_launch(
spec("t1", parent.clone(), SessionId::new(), "explorer", None),
1,
)
.await
.unwrap();
let a2 = board
.register_launch(
spec("t2", parent.clone(), SessionId::new(), "explorer", None),
2,
)
.await
.unwrap();
let f1 = board
.register_launch(
spec("t3", parent.clone(), SessionId::new(), "fixer", None),
3,
)
.await
.unwrap();
assert_eq!(a1, "exp-1");
assert_eq!(a2, "exp-2");
assert_eq!(f1, "fix-1");
}
#[tokio::test]
async fn finish_makes_job_reusable_and_resolvable_by_alias() {
let (_store, board, parent) = board(2).await;
let child = SessionId::new();
let alias = board
.register_launch(
spec(
"t1",
parent.clone(),
child.clone(),
"explorer",
Some("map the auth flow"),
),
1,
)
.await
.unwrap();
// Running jobs are not reusable.
assert!(board.resolve_reusable(&parent, &alias).is_none());
board
.finish("t1", JobState::Completed, Some("done".into()), 2)
.await
.unwrap();
let resolved = board.resolve_reusable(&parent, &alias).unwrap();
assert_eq!(resolved.child_session, child);
assert_eq!(resolved.result_summary.as_deref(), Some("done"));
// Also resolvable by task id.
assert!(board.resolve_reusable(&parent, "t1").is_some());
}
#[tokio::test]
async fn context_files_dedupe_and_respect_min_lines() {
let (_store, board, parent) = board(2).await;
board
.register_launch(spec("t1", parent, SessionId::new(), "explorer", None), 1)
.await
.unwrap();
// Below threshold — ignored.
board
.report_context_file("t1", "small.rs".into(), 3, 2)
.await
.unwrap();
board
.report_context_file("t1", "a.rs".into(), 20, 2)
.await
.unwrap();
// Same file again with a larger read keeps the max.
board
.report_context_file("t1", "a.rs".into(), 50, 3)
.await
.unwrap();
let job = board.snapshot().into_iter().next().unwrap();
assert_eq!(job.context_files.len(), 1);
assert_eq!(job.context_files[0].path, "a.rs");
assert_eq!(job.context_files[0].lines, 50);
}
#[tokio::test]
async fn trim_reusable_keeps_lru_within_limit() {
let (_store, board, parent) = board(2).await;
for (i, ts) in [(1, 10), (2, 20), (3, 30)] {
board
.register_launch(
spec(
&format!("t{i}"),
parent.clone(),
SessionId::new(),
"explorer",
None,
),
ts,
)
.await
.unwrap();
board
.finish(&format!("t{i}"), JobState::Completed, None, ts)
.await
.unwrap();
}
// max_reusable = 2, so the oldest (t1, last_used 10) is dropped.
let ids: Vec<String> = board.snapshot().into_iter().map(|j| j.task_id).collect();
assert_eq!(ids.len(), 2);
assert!(!ids.contains(&"t1".to_string()));
assert!(ids.contains(&"t2".to_string()));
assert!(ids.contains(&"t3".to_string()));
}
#[tokio::test]
async fn reconcile_flips_terminal_jobs_and_moves_them_to_reusable_section() {
let (_store, board, parent) = board(2).await;
board
.register_launch(
spec("t1", parent, SessionId::new(), "explorer", Some("obj")),
1,
)
.await
.unwrap();
board
.finish("t1", JobState::Completed, Some("res".into()), 2)
.await
.unwrap();
// Before reconcile: appears under Active/Unreconciled.
let prompt = board.format_for_prompt().unwrap();
assert!(prompt.contains("Active / Unreconciled"));
board.reconcile_terminal(3).await.unwrap();
let prompt = board.format_for_prompt().unwrap();
assert!(prompt.contains("Reusable Sessions"));
assert!(prompt.contains("exp-1"));
}
#[tokio::test]
async fn board_reloads_persisted_jobs() {
let store = Store::open_in_memory().unwrap();
let bus = EventBus::new();
let parent = SessionId::new();
{
let board = JobBoard::load(store.clone(), bus.clone(), &parent, 2)
.await
.unwrap();
board
.register_launch(
spec("t1", parent.clone(), SessionId::new(), "explorer", None),
1,
)
.await
.unwrap();
}
// Fresh board over the same store sees the persisted job.
let board = JobBoard::load(store, bus, &parent, 2).await.unwrap();
assert!(!board.is_empty());
assert_eq!(board.snapshot().len(), 1);
}
#[tokio::test]
async fn empty_board_formats_to_none() {
let (_store, board, _parent) = board(2).await;
assert!(board.format_for_prompt().is_none());
}
}
+6 -302
View File
@@ -20,39 +20,6 @@ pub struct RunConfig {
pub temperature: Option<f32>, pub temperature: Option<f32>,
pub max_steps: u32, pub max_steps: u32,
pub instructions: Vec<String>, pub instructions: Vec<String>,
/// Pricing for `model`, from models.dev metadata. `None` leaves cost at 0.
pub cost: Option<crate::types::ModelCost>,
/// Whether to append the background job board to requests (primary/delegating agents).
pub inject_job_board: bool,
/// Optional user-provided reminder injected at the start of every turn (off by default).
pub reminder_turn_start: Option<String>,
/// Optional user-provided reminder injected on the turn after a file tool ran.
pub reminder_after_file_tool: Option<String>,
}
/// Adds a step's usage/cost onto the persisted session and republishes it. Cost accounting is
/// best-effort: a store error here is logged, not surfaced as a run failure.
async fn accumulate_session_usage(
ctx: &StepContext,
usage: &crate::types::TokenUsage,
cost: f64,
now: i64,
) {
match ctx.store.session(ctx.session_id.clone()).await {
Ok(Some(mut session)) => {
session.usage.add(usage);
session.cost += cost;
session.updated_at = now;
if let Err(e) = ctx.store.upsert_session(session.clone()).await {
tracing::warn!(error = %e, "failed to persist session usage");
return;
}
ctx.bus
.publish(crate::event::AppEvent::SessionUpdated { session });
}
Ok(None) => {}
Err(e) => tracing::warn!(error = %e, "failed to load session for usage accounting"),
}
} }
/// opencode's exit condition: keep stepping while the last assistant turn asked for more /// opencode's exit condition: keep stepping while the last assistant turn asked for more
@@ -166,8 +133,6 @@ pub async fn run_session(
) -> RunOutcome { ) -> RunOutcome {
let mut doomloop = DoomLoopGuard::new(); let mut doomloop = DoomLoopGuard::new();
let mut steps = 0u32; let mut steps = 0u32;
// Whether the previous step ran a file tool, gating the `after_file_tool` reminder.
let mut prev_used_file_tool = false;
loop { loop {
match should_continue(&ctx.store, &ctx.session_id).await { match should_continue(&ctx.store, &ctx.session_id).await {
@@ -206,37 +171,6 @@ pub async fn run_session(
wire_messages.extend(convert_message(message, &parts)); wire_messages.extend(convert_message(message, &parts));
} }
// Collect synthetic (non-persisted) blocks to append to the last user message this
// turn: the optional turn-start reminder, the job board, and — if the previous step
// ran a file tool — the optional after-file-tool reminder. docs/04-multiagent.md.
let mut synthetic: Vec<String> = Vec::new();
if let Some(reminder) = &run_config.reminder_turn_start {
synthetic.push(reminder.clone());
}
if run_config.inject_job_board {
if let Some(board) = &ctx.job_board {
if let Some(block) = board.format_for_prompt() {
synthetic.push(block);
}
}
}
if prev_used_file_tool {
if let Some(reminder) = &run_config.reminder_after_file_tool {
synthetic.push(reminder.clone());
}
}
if !synthetic.is_empty() {
if let Some(last_user) = wire_messages
.iter_mut()
.rev()
.find(|m| m.role == WireRole::User)
{
for text in synthetic {
last_user.content.push(WireContent::Text { text });
}
}
}
let system_blocks = system::assemble( let system_blocks = system::assemble(
system::env_header(&ctx.cwd), system::env_header(&ctx.cwd),
&run_config.agent_prompt, &run_config.agent_prompt,
@@ -287,34 +221,17 @@ pub async fn run_session(
&ctx, &ctx,
run_config.model.clone(), run_config.model.clone(),
&run_config.agent_name, &run_config.agent_name,
run_config.cost,
&mut doomloop, &mut doomloop,
) )
.await; .await;
match step { match step {
Ok(outcome) if outcome.aborted => { Ok(outcome) if outcome.aborted => return RunOutcome::Aborted,
accumulate_session_usage(&ctx, &outcome.usage, outcome.cost, now_fn()).await; Ok(outcome) => match outcome.result {
return RunOutcome::Aborted; StepResult::Continue => continue,
} StepResult::Stop => return RunOutcome::Stopped,
Ok(outcome) => { StepResult::Compact => return RunOutcome::Stopped, // stub until M6
accumulate_session_usage(&ctx, &outcome.usage, outcome.cost, now_fn()).await; },
prev_used_file_tool = outcome.used_file_tool;
// A completed step means the orchestrator has now seen any terminal jobs
// that were on the board this turn; mark them reconciled.
if run_config.inject_job_board {
if let Some(board) = &ctx.job_board {
if let Err(e) = board.reconcile_terminal(now_fn()).await {
tracing::warn!(error = %e, "failed to reconcile job board");
}
}
}
match outcome.result {
StepResult::Continue => continue,
StepResult::Stop => return RunOutcome::Stopped,
StepResult::Compact => return RunOutcome::Stopped, // stub until M6
}
}
Err(step_err) if matches!(step_err.source, ProviderError::Cancelled) => { Err(step_err) if matches!(step_err.source, ProviderError::Cancelled) => {
return RunOutcome::Aborted; return RunOutcome::Aborted;
} }
@@ -425,15 +342,11 @@ mod tests {
permissions, permissions,
static_rules: Vec::new(), static_rules: Vec::new(),
extra_rules: Arc::new(std::sync::Mutex::new(Vec::new())), extra_rules: Arc::new(std::sync::Mutex::new(Vec::new())),
parent_rules: Vec::new(),
session_id, session_id,
cwd: cwd.clone(), cwd: cwd.clone(),
data_dir: cwd.join("tool-output"), data_dir: cwd.join("tool-output"),
cancel: CancellationToken::new(), cancel: CancellationToken::new(),
now: 1, now: 1,
spawner: None,
job_board: None,
context_reporter: None,
} }
} }
@@ -509,31 +422,11 @@ mod tests {
temperature: None, temperature: None,
max_steps: 10, max_steps: 10,
instructions: Vec::new(), instructions: Vec::new(),
// $3/1M input, $15/1M output.
cost: Some(crate::types::ModelCost {
input: 3.0,
output: 15.0,
..Default::default()
}),
inject_job_board: false,
reminder_turn_start: None,
reminder_after_file_tool: None,
}; };
let outcome = run_session(Arc::new(provider), ctx, &run_config, || 2).await; let outcome = run_session(Arc::new(provider), ctx, &run_config, || 2).await;
assert!(matches!(outcome, RunOutcome::Stopped)); assert!(matches!(outcome, RunOutcome::Stopped));
// Both steps' usage and cost accumulate onto the session.
let session = store.session(session_id.clone()).await.unwrap().unwrap();
assert_eq!(session.usage.input, 30);
assert_eq!(session.usage.output, 13);
// (10*3 + 5*15)/1e6 + (20*3 + 8*15)/1e6 = 0.000105 + 0.00018
assert!(
(session.cost - 0.000_285).abs() < 1e-9,
"cost = {}",
session.cost
);
let messages = store.messages(session_id.clone()).await.unwrap(); let messages = store.messages(session_id.clone()).await.unwrap();
assert_eq!( assert_eq!(
messages.len(), messages.len(),
@@ -624,10 +517,6 @@ mod tests {
temperature: None, temperature: None,
max_steps: 10, max_steps: 10,
instructions: Vec::new(), instructions: Vec::new(),
cost: None,
inject_job_board: false,
reminder_turn_start: None,
reminder_after_file_tool: None,
}; };
let outcome = run_session(Arc::new(provider), ctx, &run_config, || 2).await; let outcome = run_session(Arc::new(provider), ctx, &run_config, || 2).await;
@@ -637,189 +526,4 @@ mod tests {
let messages = store.messages(session_id).await.unwrap(); let messages = store.messages(session_id).await.unwrap();
assert_eq!(messages.len(), 1); assert_eq!(messages.len(), 1);
} }
/// Records the last request it was asked to stream so tests can assert on prompt content.
struct CapturingProvider {
last: StdMutex<Option<LlmRequest>>,
}
#[async_trait]
impl Provider for CapturingProvider {
fn id(&self) -> &str {
"mock"
}
async fn list_models(&self) -> Result<Vec<ModelInfo>, ProviderError> {
Ok(vec![])
}
async fn stream(
&self,
req: LlmRequest,
_cancel: CancellationToken,
) -> Result<LlmEventStream, ProviderError> {
*self.last.lock().unwrap() = Some(req);
let events = vec![
Ok(LlmEvent::TextStart { id: "t".into() }),
Ok(LlmEvent::TextDelta {
id: "t".into(),
text: "ok".into(),
}),
Ok(LlmEvent::TextEnd { id: "t".into() }),
Ok(LlmEvent::Finish {
reason: FinishReason::Stop,
usage: usage(1, 1),
}),
];
Ok(Box::pin(futures::stream::iter(events)))
}
}
#[tokio::test]
async fn job_board_is_injected_into_the_last_user_message() {
use crate::engine::jobs::{JobBoard, LaunchSpec};
let store = Store::open_in_memory().unwrap();
let bus = EventBus::new();
let model = ModelRef::new("mock", "mock-model");
let session = Session::new_root("orchestrator", model.clone(), 1);
let session_id = session.id.clone();
store.upsert_session(session).await.unwrap();
let user_message = Message::new_user(session_id.clone(), 1);
store.upsert_message(user_message.clone()).await.unwrap();
store
.upsert_part(Part {
id: crate::types::PartId::new(),
message_id: user_message.id.clone(),
session_id: session_id.clone(),
idx: 0,
body: PartBody::Text {
text: "carry on".into(),
synthetic: false,
},
})
.await
.unwrap();
// A board with one running job for this session.
let board = std::sync::Arc::new(
JobBoard::load(store.clone(), bus.clone(), &session_id, 2)
.await
.unwrap(),
);
board
.register_launch(
LaunchSpec {
task_id: "t1".into(),
parent_session: session_id.clone(),
child_session: SessionId::new(),
agent: "explorer".into(),
description: "map auth".into(),
objective: Some("map the auth flow".into()),
},
1,
)
.await
.unwrap();
let cwd = tempfile::tempdir().unwrap();
let mut ctx = make_ctx(store, bus, session_id, cwd.path().to_path_buf()).await;
ctx.job_board = Some(board);
let run_config = RunConfig {
agent_name: "orchestrator".into(),
agent_prompt: "You orchestrate.".into(),
model,
temperature: None,
max_steps: 1,
instructions: Vec::new(),
cost: None,
inject_job_board: true,
reminder_turn_start: None,
reminder_after_file_tool: None,
};
let provider = std::sync::Arc::new(CapturingProvider {
last: StdMutex::new(None),
});
let outcome = run_session(provider.clone(), ctx, &run_config, || 2).await;
assert!(matches!(outcome, RunOutcome::Stopped));
let req = provider.last.lock().unwrap().clone().expect("a request");
let last_user = req
.messages
.iter()
.rev()
.find(|m| m.role == WireRole::User)
.expect("a user message");
let text: String = last_user
.content
.iter()
.filter_map(|c| match c {
WireContent::Text { text } => Some(text.as_str()),
_ => None,
})
.collect::<Vec<_>>()
.join("\n");
assert!(text.contains("Background Job Board"), "got: {text}");
assert!(text.contains("exp-1"), "got: {text}");
assert!(text.contains("map the auth flow"), "got: {text}");
}
#[tokio::test]
async fn turn_start_reminder_is_injected_into_the_request() {
let store = Store::open_in_memory().unwrap();
let bus = EventBus::new();
let model = ModelRef::new("mock", "mock-model");
let session = Session::new_root("orchestrator", model.clone(), 1);
let session_id = session.id.clone();
store.upsert_session(session).await.unwrap();
let user_message = Message::new_user(session_id.clone(), 1);
store.upsert_message(user_message.clone()).await.unwrap();
store
.upsert_part(Part {
id: crate::types::PartId::new(),
message_id: user_message.id.clone(),
session_id: session_id.clone(),
idx: 0,
body: PartBody::Text {
text: "do the thing".into(),
synthetic: false,
},
})
.await
.unwrap();
let cwd = tempfile::tempdir().unwrap();
let ctx = make_ctx(store, bus, session_id, cwd.path().to_path_buf()).await;
let run_config = RunConfig {
agent_name: "orchestrator".into(),
agent_prompt: "You orchestrate.".into(),
model,
temperature: None,
max_steps: 1,
instructions: Vec::new(),
cost: None,
inject_job_board: false,
reminder_turn_start: Some("REMEMBER: stay on task.".into()),
reminder_after_file_tool: None,
};
let provider = std::sync::Arc::new(CapturingProvider {
last: StdMutex::new(None),
});
let outcome = run_session(provider.clone(), ctx, &run_config, || 2).await;
assert!(matches!(outcome, RunOutcome::Stopped));
let req = provider.last.lock().unwrap().clone().expect("a request");
let last_user = req
.messages
.iter()
.rev()
.find(|m| m.role == WireRole::User)
.expect("a user message");
let has_reminder = last_user.content.iter().any(
|c| matches!(c, WireContent::Text { text } if text.contains("REMEMBER: stay on task.")),
);
assert!(has_reminder, "turn-start reminder should be injected");
}
} }
-2
View File
@@ -1,5 +1,4 @@
pub mod doomloop; pub mod doomloop;
pub mod jobs;
pub mod processor; pub mod processor;
pub mod retry; pub mod retry;
#[path = "loop.rs"] #[path = "loop.rs"]
@@ -7,6 +6,5 @@ pub mod session_loop;
pub mod system; pub mod system;
pub use doomloop::DoomLoopGuard; pub use doomloop::DoomLoopGuard;
pub use jobs::{ContextFile, JobBoard, JobRecord, JobState};
pub use processor::{process_step, StepContext, StepError, StepOutcome, StepResult}; pub use processor::{process_step, StepContext, StepError, StepOutcome, StepResult};
pub use session_loop::{run_session, RunConfig}; pub use session_loop::{run_session, RunConfig};
+4 -43
View File
@@ -10,14 +10,10 @@ use crate::event::{AppEvent, EventBus};
use crate::llm::{FinishReason, LlmEvent, LlmEventStream, ProviderError}; use crate::llm::{FinishReason, LlmEvent, LlmEventStream, ProviderError};
use crate::permission::{PermissionService, Ruleset}; use crate::permission::{PermissionService, Ruleset};
use crate::store::Store; use crate::store::Store;
use crate::tool::{ use crate::tool::{MetadataSink, PermissionHandle, Tool, ToolCtx, ToolError, ToolRegistry};
ContextReporter, MetadataSink, PermissionHandle, SubagentSpawner, Tool, ToolCtx, ToolError,
ToolRegistry,
};
use crate::types::{Message, MessageId, Part, PartBody, PartId, SessionId, TokenUsage, ToolState}; use crate::types::{Message, MessageId, Part, PartBody, PartId, SessionId, TokenUsage, ToolState};
use super::doomloop::DoomLoopGuard; use super::doomloop::DoomLoopGuard;
use super::jobs::JobBoard;
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StepResult { pub enum StepResult {
@@ -30,12 +26,7 @@ pub struct StepOutcome {
pub result: StepResult, pub result: StepResult,
pub message_id: Option<MessageId>, pub message_id: Option<MessageId>,
pub usage: TokenUsage, pub usage: TokenUsage,
/// Dollar cost of this step's usage (0.0 when no pricing is available).
pub cost: f64,
pub aborted: bool, pub aborted: bool,
/// Whether a file-mutating tool (`edit`/`write`) ran this step — drives the optional
/// `after_file_tool` reminder injection on the next turn.
pub used_file_tool: bool,
} }
pub struct StepError { pub struct StepError {
@@ -54,9 +45,6 @@ pub struct StepContext {
pub permissions: Arc<PermissionService>, pub permissions: Arc<PermissionService>,
pub static_rules: Ruleset, pub static_rules: Ruleset,
pub extra_rules: Arc<Mutex<Ruleset>>, pub extra_rules: Arc<Mutex<Ruleset>>,
/// Parent-effective ruleset for a subagent session; empty for a root session. Enables
/// permission intersection on this session's tool calls.
pub parent_rules: Ruleset,
pub session_id: SessionId, pub session_id: SessionId,
pub cwd: PathBuf, pub cwd: PathBuf,
/// Session's `tool-output` spill directory (see `tool::truncate`). /// Session's `tool-output` spill directory (see `tool::truncate`).
@@ -64,14 +52,6 @@ pub struct StepContext {
pub cancel: CancellationToken, pub cancel: CancellationToken,
/// Wall-clock for `created_at` stamps — passed in so tests stay deterministic. /// Wall-clock for `created_at` stamps — passed in so tests stay deterministic.
pub now: i64, pub now: i64,
/// Lets the `task` tool spawn subagents. `None` disables delegation (headless/tests).
pub spawner: Option<Arc<dyn SubagentSpawner>>,
/// This session's background job board (as a parent). Injected into requests when the
/// running agent can delegate; `None` disables the board.
pub job_board: Option<Arc<JobBoard>>,
/// Present in subagent sessions: reports read files to this session's job on the parent
/// board. `None` for root sessions (nothing to report to).
pub context_reporter: Option<Arc<dyn ContextReporter>>,
} }
struct FlushTracker { struct FlushTracker {
@@ -101,13 +81,9 @@ impl FlushTracker {
} }
} }
/// Tool names that mutate files — after one runs, the optional `after_file_tool` reminder fires.
const FILE_TOOLS: &[&str] = &["edit", "write"];
struct Run<'a> { struct Run<'a> {
ctx: &'a StepContext, ctx: &'a StepContext,
assistant: Option<Message>, assistant: Option<Message>,
used_file_tool: bool,
next_idx: u32, next_idx: u32,
active_text: Option<PartId>, active_text: Option<PartId>,
active_reasoning: Option<PartId>, active_reasoning: Option<PartId>,
@@ -124,7 +100,6 @@ impl<'a> Run<'a> {
Self { Self {
ctx, ctx,
assistant: None, assistant: None,
used_file_tool: false,
next_idx: 0, next_idx: 0,
active_text: None, active_text: None,
active_reasoning: None, active_reasoning: None,
@@ -394,9 +369,6 @@ impl<'a> Run<'a> {
input: serde_json::Value, input: serde_json::Value,
doomloop: &mut DoomLoopGuard, doomloop: &mut DoomLoopGuard,
) -> Result<(), ProviderError> { ) -> Result<(), ProviderError> {
if FILE_TOOLS.contains(&name.as_str()) {
self.used_file_tool = true;
}
let part_id = self.pending_tools.remove(&call_id).unwrap_or_default(); let part_id = self.pending_tools.remove(&call_id).unwrap_or_default();
let running = Part { let running = Part {
id: part_id.clone(), id: part_id.clone(),
@@ -509,8 +481,7 @@ impl<'a> Run<'a> {
self.ctx.static_rules.clone(), self.ctx.static_rules.clone(),
self.ctx.extra_rules.clone(), self.ctx.extra_rules.clone(),
call_cancel.clone(), call_cancel.clone(),
) );
.with_parent_rules(self.ctx.parent_rules.clone());
let tool_ctx = ToolCtx { let tool_ctx = ToolCtx {
session_id: self.ctx.session_id.clone(), session_id: self.ctx.session_id.clone(),
message_id: self.message_id(), message_id: self.message_id(),
@@ -520,8 +491,6 @@ impl<'a> Run<'a> {
cancel: call_cancel.clone(), cancel: call_cancel.clone(),
ask, ask,
metadata: metadata_sink, metadata: metadata_sink,
spawner: self.ctx.spawner.clone(),
context_reporter: self.ctx.context_reporter.clone(),
}; };
let result = tokio::select! { let result = tokio::select! {
@@ -544,7 +513,6 @@ impl<'a> Run<'a> {
&mut self, &mut self,
reason: FinishReason, reason: FinishReason,
usage: TokenUsage, usage: TokenUsage,
cost: f64,
) -> Result<StepResult, ProviderError> { ) -> Result<StepResult, ProviderError> {
let part = Part { let part = Part {
id: PartId::new(), id: PartId::new(),
@@ -553,7 +521,7 @@ impl<'a> Run<'a> {
idx: self.next_idx, idx: self.next_idx,
body: PartBody::StepFinish { body: PartBody::StepFinish {
usage, usage,
cost, cost: 0.0,
reason: reason.clone(), reason: reason.clone(),
}, },
}; };
@@ -599,12 +567,10 @@ pub async fn process_step(
ctx: &StepContext, ctx: &StepContext,
model: crate::types::ModelRef, model: crate::types::ModelRef,
agent: &str, agent: &str,
cost: Option<crate::types::ModelCost>,
doomloop: &mut DoomLoopGuard, doomloop: &mut DoomLoopGuard,
) -> Result<StepOutcome, StepError> { ) -> Result<StepOutcome, StepError> {
let mut run = Run::new(ctx); let mut run = Run::new(ctx);
let mut usage = TokenUsage::default(); let mut usage = TokenUsage::default();
let mut step_cost = 0.0;
let mut result = StepResult::Stop; let mut result = StepResult::Stop;
loop { loop {
@@ -616,9 +582,7 @@ pub async fn process_step(
result: StepResult::Stop, result: StepResult::Stop,
message_id: run.assistant.as_ref().map(|m| m.id.clone()), message_id: run.assistant.as_ref().map(|m| m.id.clone()),
usage, usage,
cost: step_cost,
aborted: true, aborted: true,
used_file_tool: run.used_file_tool,
}); });
} }
}; };
@@ -666,8 +630,7 @@ pub async fn process_step(
usage: finish_usage, usage: finish_usage,
} => { } => {
usage = finish_usage; usage = finish_usage;
step_cost = cost.map(|c| c.cost_of(&finish_usage)).unwrap_or(0.0); match run.on_finish(reason, finish_usage).await {
match run.on_finish(reason, finish_usage, step_cost).await {
Ok(r) => { Ok(r) => {
result = r; result = r;
Ok(()) Ok(())
@@ -689,8 +652,6 @@ pub async fn process_step(
result, result,
message_id: run.assistant.as_ref().map(|m| m.id.clone()), message_id: run.assistant.as_ref().map(|m| m.id.clone()),
usage, usage,
cost: step_cost,
aborted: false, aborted: false,
used_file_tool: run.used_file_tool,
}) })
} }
-1
View File
@@ -1,4 +1,3 @@
pub mod agent;
pub mod config; pub mod config;
pub mod engine; pub mod engine;
pub mod event; pub mod event;
+1 -1
View File
@@ -1,7 +1,7 @@
pub mod rule; pub mod rule;
pub mod service; pub mod service;
pub use rule::{evaluate, evaluate_intersected, Action, Rule, Ruleset}; pub use rule::{evaluate, Action, Rule, Ruleset};
pub use service::{ pub use service::{
spawn_auto_approve, AskDecision, AskError, AskInput, PermissionReply, PermissionService, spawn_auto_approve, AskDecision, AskError, AskInput, PermissionReply, PermissionService,
}; };
@@ -44,37 +44,6 @@ pub fn evaluate(stack: &[&Ruleset], permission: &str, pattern: &str) -> Action {
result result
} }
impl Action {
/// How restrictive this verdict is: `Deny` > `Ask` > `Allow`. Used to intersect a
/// parent and child verdict when a subagent runs (docs/04-multiagent.md).
fn restrictiveness(self) -> u8 {
match self {
Action::Allow => 0,
Action::Ask => 1,
Action::Deny => 2,
}
}
}
/// Evaluate `permission`/`pattern` against a parent-effective stack and a child stack
/// independently, returning the **more restrictive** of the two verdicts
/// (`deny > ask > allow`). A subagent's tool call must satisfy both the rules it inherits
/// from its spawning chain and its own agent ruleset.
pub fn evaluate_intersected(
parent_stack: &[&Ruleset],
child_stack: &[&Ruleset],
permission: &str,
pattern: &str,
) -> Action {
let parent = evaluate(parent_stack, permission, pattern);
let child = evaluate(child_stack, permission, pattern);
if child.restrictiveness() >= parent.restrictiveness() {
child
} else {
parent
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -143,49 +112,4 @@ mod tests {
fn empty_stack_defaults_to_ask() { fn empty_stack_defaults_to_ask() {
assert_eq!(evaluate(&[], "bash", "ls"), Action::Ask); assert_eq!(evaluate(&[], "bash", "ls"), Action::Ask);
} }
#[test]
fn intersected_takes_the_more_restrictive_verdict() {
let parent_allow: Ruleset = vec![rule("edit", "*", Action::Allow)];
let child_deny: Ruleset = vec![rule("edit", "*", Action::Deny)];
// Child denies what the parent would allow → deny wins.
assert_eq!(
evaluate_intersected(&[&parent_allow], &[&child_deny], "edit", "main.rs"),
Action::Deny
);
// Symmetric: parent denies what the child would allow → deny still wins.
assert_eq!(
evaluate_intersected(&[&child_deny], &[&parent_allow], "edit", "main.rs"),
Action::Deny
);
}
#[test]
fn intersected_ask_beats_allow_but_loses_to_deny() {
let allow: Ruleset = vec![rule("bash", "*", Action::Allow)];
let ask: Ruleset = vec![rule("bash", "*", Action::Ask)];
let deny: Ruleset = vec![rule("bash", "*", Action::Deny)];
assert_eq!(
evaluate_intersected(&[&allow], &[&ask], "bash", "ls"),
Action::Ask
);
assert_eq!(
evaluate_intersected(&[&ask], &[&deny], "bash", "ls"),
Action::Deny
);
}
#[test]
fn intersected_allows_only_when_both_allow() {
let allow: Ruleset = vec![rule("read", "*", Action::Allow)];
assert_eq!(
evaluate_intersected(&[&allow], &[&allow], "read", "src/a.rs"),
Action::Allow
);
// Empty child stack defaults to Ask, which is more restrictive than parent Allow.
assert_eq!(
evaluate_intersected(&[&allow], &[], "read", "src/a.rs"),
Action::Ask
);
}
} }
+1 -19
View File
@@ -8,7 +8,7 @@ use ulid::Ulid;
use crate::event::{AppEvent, EventBus, PermissionRequest}; use crate::event::{AppEvent, EventBus, PermissionRequest};
use crate::types::SessionId; use crate::types::SessionId;
use super::rule::{evaluate, evaluate_intersected, Action, Rule, Ruleset}; use super::rule::{evaluate, Action, Rule, Ruleset};
pub struct AskInput { pub struct AskInput {
pub permission: String, pub permission: String,
@@ -73,24 +73,6 @@ impl PermissionService {
} }
} }
/// Like [`ask`](Self::ask), but for a subagent: the verdict is the more restrictive of
/// the `parent_stack` (rules inherited from the spawning chain) and `child_stack` (the
/// subagent's own rules). Used so a child can never widen what its parent forbids.
pub async fn ask_intersected(
&self,
session_id: &SessionId,
parent_stack: &[&Ruleset],
child_stack: &[&Ruleset],
input: AskInput,
cancel: &CancellationToken,
) -> Result<AskDecision, AskError> {
match evaluate_intersected(parent_stack, child_stack, &input.permission, &input.pattern) {
Action::Allow => Ok(AskDecision::Allowed),
Action::Deny => Err(AskError::Denied),
Action::Ask => self.ask_user(session_id, input, cancel).await,
}
}
/// Bypasses ruleset evaluation entirely — used by the doom-loop guard, which must ask /// Bypasses ruleset evaluation entirely — used by the doom-loop guard, which must ask
/// regardless of any `Allow` rule. /// regardless of any `Allow` rule.
pub async fn force_ask( pub async fn force_ask(
-54
View File
@@ -1,7 +1,6 @@
use rusqlite::{params, Connection}; use rusqlite::{params, Connection};
use tokio::sync::oneshot; use tokio::sync::oneshot;
use crate::engine::jobs::JobRecord;
use crate::types::{Message, MessageId, Part, Session, SessionId}; use crate::types::{Message, MessageId, Part, Session, SessionId};
use super::api::StoreError; use super::api::StoreError;
@@ -14,13 +13,9 @@ pub enum StoreCmd {
UpsertSession(Session, Reply<()>), UpsertSession(Session, Reply<()>),
UpsertMessage(Message, Reply<()>), UpsertMessage(Message, Reply<()>),
UpsertPart(Part, Reply<()>), UpsertPart(Part, Reply<()>),
Session(SessionId, Reply<Option<Session>>),
Sessions(Reply<Vec<Session>>), Sessions(Reply<Vec<Session>>),
Messages(SessionId, Reply<Vec<Message>>), Messages(SessionId, Reply<Vec<Message>>),
Parts(MessageId, Reply<Vec<Part>>), Parts(MessageId, Reply<Vec<Part>>),
UpsertJob(JobRecord, Reply<()>),
DeleteJob(String, Reply<()>),
JobsForParent(SessionId, Reply<Vec<JobRecord>>),
} }
fn init_schema(conn: &Connection) -> rusqlite::Result<()> { fn init_schema(conn: &Connection) -> rusqlite::Result<()> {
@@ -74,15 +69,6 @@ fn upsert_part(conn: &Connection, part: &Part) -> Result<(), StoreError> {
Ok(()) Ok(())
} }
fn get_session(conn: &Connection, id: &SessionId) -> Result<Option<Session>, StoreError> {
let mut stmt = conn.prepare("SELECT data FROM session WHERE id = ?1")?;
let mut rows = stmt.query_map(params![id.as_ref()], |row| row.get::<_, String>(0))?;
match rows.next() {
Some(data) => Ok(Some(serde_json::from_str(&data?)?)),
None => Ok(None),
}
}
fn list_sessions(conn: &Connection) -> Result<Vec<Session>, StoreError> { fn list_sessions(conn: &Connection) -> Result<Vec<Session>, StoreError> {
let mut stmt = conn.prepare("SELECT data FROM session ORDER BY id")?; let mut stmt = conn.prepare("SELECT data FROM session ORDER BY id")?;
let rows = stmt let rows = stmt
@@ -113,34 +99,6 @@ fn list_parts(conn: &Connection, message_id: &MessageId) -> Result<Vec<Part>, St
.collect() .collect()
} }
fn upsert_job(conn: &Connection, job: &JobRecord) -> Result<(), StoreError> {
let data = serde_json::to_string(job)?;
conn.execute(
"INSERT INTO job (task_id, parent_session_id, data) VALUES (?1, ?2, ?3)
ON CONFLICT(task_id) DO UPDATE SET data = ?3",
params![job.task_id, job.parent_session.as_ref(), data],
)?;
Ok(())
}
fn delete_job(conn: &Connection, task_id: &str) -> Result<(), StoreError> {
conn.execute("DELETE FROM job WHERE task_id = ?1", params![task_id])?;
Ok(())
}
fn list_jobs_for_parent(
conn: &Connection,
parent: &SessionId,
) -> Result<Vec<JobRecord>, StoreError> {
let mut stmt = conn.prepare("SELECT data FROM job WHERE parent_session_id = ?1")?;
let rows = stmt
.query_map(params![parent.as_ref()], |row| row.get::<_, String>(0))?
.collect::<Result<Vec<_>, _>>()?;
rows.iter()
.map(|data| serde_json::from_str(data).map_err(StoreError::from))
.collect()
}
/// Runs on a dedicated OS thread; the async facade in `api.rs` talks to it over `mpsc`. /// Runs on a dedicated OS thread; the async facade in `api.rs` talks to it over `mpsc`.
pub fn run(conn: Connection, mut rx: tokio::sync::mpsc::Receiver<StoreCmd>) { pub fn run(conn: Connection, mut rx: tokio::sync::mpsc::Receiver<StoreCmd>) {
if let Err(e) = init_schema(&conn) { if let Err(e) = init_schema(&conn) {
@@ -158,9 +116,6 @@ pub fn run(conn: Connection, mut rx: tokio::sync::mpsc::Receiver<StoreCmd>) {
StoreCmd::UpsertPart(part, reply) => { StoreCmd::UpsertPart(part, reply) => {
let _ = reply.send(upsert_part(&conn, &part)); let _ = reply.send(upsert_part(&conn, &part));
} }
StoreCmd::Session(id, reply) => {
let _ = reply.send(get_session(&conn, &id));
}
StoreCmd::Sessions(reply) => { StoreCmd::Sessions(reply) => {
let _ = reply.send(list_sessions(&conn)); let _ = reply.send(list_sessions(&conn));
} }
@@ -170,15 +125,6 @@ pub fn run(conn: Connection, mut rx: tokio::sync::mpsc::Receiver<StoreCmd>) {
StoreCmd::Parts(message_id, reply) => { StoreCmd::Parts(message_id, reply) => {
let _ = reply.send(list_parts(&conn, &message_id)); let _ = reply.send(list_parts(&conn, &message_id));
} }
StoreCmd::UpsertJob(job, reply) => {
let _ = reply.send(upsert_job(&conn, &job));
}
StoreCmd::DeleteJob(task_id, reply) => {
let _ = reply.send(delete_job(&conn, &task_id));
}
StoreCmd::JobsForParent(parent, reply) => {
let _ = reply.send(list_jobs_for_parent(&conn, &parent));
}
} }
} }
} }
-19
View File
@@ -3,7 +3,6 @@ use std::path::Path;
use rusqlite::Connection; use rusqlite::Connection;
use tokio::sync::{mpsc, oneshot}; use tokio::sync::{mpsc, oneshot};
use crate::engine::jobs::JobRecord;
use crate::types::{Message, MessageId, Part, Session, SessionId}; use crate::types::{Message, MessageId, Part, Session, SessionId};
use super::actor::{self, StoreCmd}; use super::actor::{self, StoreCmd};
@@ -78,11 +77,6 @@ impl Store {
self.call(|reply| StoreCmd::UpsertPart(part, reply)).await self.call(|reply| StoreCmd::UpsertPart(part, reply)).await
} }
pub async fn session(&self, session_id: SessionId) -> Result<Option<Session>, StoreError> {
self.call(|reply| StoreCmd::Session(session_id, reply))
.await
}
pub async fn sessions(&self) -> Result<Vec<Session>, StoreError> { pub async fn sessions(&self) -> Result<Vec<Session>, StoreError> {
self.call(StoreCmd::Sessions).await self.call(StoreCmd::Sessions).await
} }
@@ -95,19 +89,6 @@ impl Store {
pub async fn parts(&self, message_id: MessageId) -> Result<Vec<Part>, StoreError> { pub async fn parts(&self, message_id: MessageId) -> Result<Vec<Part>, StoreError> {
self.call(|reply| StoreCmd::Parts(message_id, reply)).await self.call(|reply| StoreCmd::Parts(message_id, reply)).await
} }
pub async fn upsert_job(&self, job: JobRecord) -> Result<(), StoreError> {
self.call(|reply| StoreCmd::UpsertJob(job, reply)).await
}
pub async fn delete_job(&self, task_id: String) -> Result<(), StoreError> {
self.call(|reply| StoreCmd::DeleteJob(task_id, reply)).await
}
pub async fn jobs_for_parent(&self, parent: SessionId) -> Result<Vec<JobRecord>, StoreError> {
self.call(|reply| StoreCmd::JobsForParent(parent, reply))
.await
}
} }
#[cfg(test)] #[cfg(test)]
+15 -90
View File
@@ -10,58 +10,6 @@ use tokio_util::sync::CancellationToken;
use crate::permission::{AskDecision, AskError, AskInput, PermissionService, Ruleset}; use crate::permission::{AskDecision, AskError, AskInput, PermissionService, Ruleset};
use crate::types::{MessageId, SessionId}; use crate::types::{MessageId, SessionId};
/// A request from the `task` tool to run a subagent. The spawner (owned by the composition
/// root) resolves the agent, enforces the depth limit, applies permission intersection, and
/// runs the child session foreground or background. See `docs/04-multiagent.md`.
pub struct SpawnRequest {
pub parent_session_id: SessionId,
pub parent_message_id: MessageId,
pub agent: String,
pub description: String,
pub prompt: String,
/// Alias or task id of a completed job to reuse (continue its child session).
pub reuse_task_id: Option<String>,
pub background: bool,
/// The tool call's cancellation token — used for foreground child runs. Background runs
/// are childed from the parent session's run token by the spawner instead.
pub cancel: CancellationToken,
}
#[derive(Debug)]
pub struct SpawnOutcome {
pub child_session_id: SessionId,
pub background: bool,
/// Board alias assigned to a background launch.
pub alias: Option<String>,
/// Final assistant text of a foreground run.
pub final_text: Option<String>,
}
#[derive(Debug, thiserror::Error)]
pub enum SpawnError {
#[error("unknown subagent {0:?}, or it is not usable as a subagent")]
InvalidAgent(String),
#[error("subagent depth limit reached — do this work yourself instead of delegating further")]
DepthExceeded,
#[error("cannot reuse {0:?}: no completed job with that alias for this session")]
ReuseNotFound(String),
#[error("{0}")]
Other(String),
}
#[async_trait]
pub trait SubagentSpawner: Send + Sync {
async fn spawn(&self, req: SpawnRequest) -> Result<SpawnOutcome, SpawnError>;
}
/// Lets a child session report the files it read to its job board entry, so a completed
/// specialist advertises what it already looked at (docs/04-multiagent.md). Present only in
/// subagent sessions; the spawner wires it to the right board + job.
#[async_trait]
pub trait ContextReporter: Send + Sync {
async fn report_file(&self, path: String, lines: u32);
}
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
pub enum ToolError { pub enum ToolError {
#[error("permission denied")] #[error("permission denied")]
@@ -112,9 +60,6 @@ pub struct PermissionHandle {
session_id: SessionId, session_id: SessionId,
static_rules: Ruleset, static_rules: Ruleset,
extra_rules: Arc<Mutex<Ruleset>>, extra_rules: Arc<Mutex<Ruleset>>,
/// Parent-effective ruleset for a subagent session; empty for a root session. When
/// non-empty, verdicts are intersected so a child can only ever be *more* restricted.
parent_rules: Ruleset,
cancel: CancellationToken, cancel: CancellationToken,
} }
@@ -131,17 +76,10 @@ impl PermissionHandle {
session_id, session_id,
static_rules, static_rules,
extra_rules, extra_rules,
parent_rules: Vec::new(),
cancel, cancel,
} }
} }
/// Sets the parent-effective ruleset so this handle intersects verdicts (subagent runs).
pub fn with_parent_rules(mut self, parent_rules: Ruleset) -> Self {
self.parent_rules = parent_rules;
self
}
pub async fn ask( pub async fn ask(
&self, &self,
permission: impl Into<String>, permission: impl Into<String>,
@@ -150,29 +88,21 @@ impl PermissionHandle {
metadata: serde_json::Value, metadata: serde_json::Value,
) -> Result<(), ToolError> { ) -> Result<(), ToolError> {
let extra_snapshot = self.extra_rules.lock().unwrap().clone(); let extra_snapshot = self.extra_rules.lock().unwrap().clone();
let child_stack: [&Ruleset; 2] = [&self.static_rules, &extra_snapshot]; let stack: [&Ruleset; 2] = [&self.static_rules, &extra_snapshot];
let input = AskInput { let decision = self
permission: permission.into(), .service
pattern: pattern.into(), .ask(
always_pattern: always_pattern.into(), &self.session_id,
metadata, &stack,
}; AskInput {
let decision = if self.parent_rules.is_empty() { permission: permission.into(),
self.service pattern: pattern.into(),
.ask(&self.session_id, &child_stack, input, &self.cancel) always_pattern: always_pattern.into(),
.await? metadata,
} else { },
let parent_stack: [&Ruleset; 1] = [&self.parent_rules]; &self.cancel,
self.service )
.ask_intersected( .await?;
&self.session_id,
&parent_stack,
&child_stack,
input,
&self.cancel,
)
.await?
};
if let AskDecision::AllowedAlways(rule) = decision { if let AskDecision::AllowedAlways(rule) = decision {
self.extra_rules.lock().unwrap().push(rule); self.extra_rules.lock().unwrap().push(rule);
} }
@@ -190,11 +120,6 @@ pub struct ToolCtx {
pub cancel: CancellationToken, pub cancel: CancellationToken,
pub ask: PermissionHandle, pub ask: PermissionHandle,
pub metadata: MetadataSink, pub metadata: MetadataSink,
/// Present when the engine can spawn subagents (the `task` tool's capability). `None`
/// in headless/test contexts with no orchestration wired in.
pub spawner: Option<Arc<dyn SubagentSpawner>>,
/// Present in subagent sessions: lets the read tool report files to the job board.
pub context_reporter: Option<Arc<dyn ContextReporter>>,
} }
#[derive(Debug)] #[derive(Debug)]
+1 -1
View File
@@ -6,6 +6,6 @@ pub mod session;
pub use ids::{MessageId, PartId, SessionId}; pub use ids::{MessageId, PartId, SessionId};
pub use message::{Message, MessageError, Role}; pub use message::{Message, MessageError, Role};
pub use model::{ModelCost, ModelInfo, ModelRef, TokenUsage}; pub use model::{ModelInfo, ModelRef, TokenUsage};
pub use part::{Part, PartBody, ToolState}; pub use part::{Part, PartBody, ToolState};
pub use session::Session; pub use session::Session;
+2 -62
View File
@@ -34,71 +34,11 @@ impl TokenUsage {
} }
} }
/// Per-model pricing in USD per **one million** tokens. Populated from models.dev metadata // Full cost/context-limit metadata is populated by harness-providers (models.dev) in M1/M3;
/// by `harness-providers`. // this placeholder only carries what harness-core needs to key on.
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct ModelCost {
pub input: f64,
pub output: f64,
pub cache_read: f64,
pub cache_write: f64,
}
impl ModelCost {
/// Dollar cost of a usage sample. Reasoning tokens are billed within `output` by the
/// providers we support (OpenAI reports them as a subset of `output_tokens`; Anthropic
/// counts thinking in output), so they are intentionally not charged separately here.
pub fn cost_of(&self, usage: &TokenUsage) -> f64 {
let per_million = |tokens: u64, rate: f64| (tokens as f64) * rate / 1_000_000.0;
per_million(usage.input, self.input)
+ per_million(usage.output, self.output)
+ per_million(usage.cache_read, self.cache_read)
+ per_million(usage.cache_write, self.cache_write)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cost_of_sums_components_per_million_excluding_reasoning() {
let cost = ModelCost {
input: 3.0,
output: 15.0,
cache_read: 0.30,
cache_write: 3.75,
};
let usage = TokenUsage {
input: 1_000_000,
output: 1_000_000,
reasoning: 500_000, // billed within output — must not add extra cost
cache_read: 1_000_000,
cache_write: 1_000_000,
};
// 3 + 15 + 0.30 + 3.75, with reasoning contributing nothing.
assert!((cost.cost_of(&usage) - 22.05).abs() < 1e-9);
}
#[test]
fn default_cost_is_zero() {
assert_eq!(ModelCost::default().cost_of(&TokenUsage::default()), 0.0);
}
}
/// Model metadata, keyed on `model`. Cost/limits are populated from models.dev by
/// `harness-providers`; `reasoning`/`tool_call`/`attachment` are capability flags.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ModelInfo { pub struct ModelInfo {
pub model: ModelRef, pub model: ModelRef,
pub context_limit: u64, pub context_limit: u64,
pub output_limit: u64, pub output_limit: u64,
#[serde(default)]
pub cost: ModelCost,
#[serde(default)]
pub reasoning: bool,
#[serde(default)]
pub tool_call: bool,
#[serde(default)]
pub attachment: bool,
} }
-2
View File
@@ -18,11 +18,9 @@ serde = { workspace = true }
serde_json = { workspace = true } serde_json = { workspace = true }
thiserror = { workspace = true } thiserror = { workspace = true }
tracing = { workspace = true } tracing = { workspace = true }
dirs = { workspace = true }
[dev-dependencies] [dev-dependencies]
tokio = { workspace = true, features = ["test-util", "macros"] } tokio = { workspace = true, features = ["test-util", "macros"] }
tempfile = { workspace = true }
[lints] [lints]
workspace = true workspace = true
@@ -1,67 +0,0 @@
{
"anthropic": {
"id": "anthropic",
"name": "Anthropic",
"models": {
"claude-sonnet-4-5": {
"id": "claude-sonnet-4-5",
"reasoning": true,
"tool_call": true,
"attachment": true,
"cost": { "input": 3, "output": 15, "cache_read": 0.3, "cache_write": 3.75 },
"limit": { "context": 200000, "output": 64000 }
},
"claude-opus-4-1": {
"id": "claude-opus-4-1",
"reasoning": true,
"tool_call": true,
"attachment": true,
"cost": { "input": 15, "output": 75, "cache_read": 1.5, "cache_write": 18.75 },
"limit": { "context": 200000, "output": 32000 }
},
"claude-haiku-4-5": {
"id": "claude-haiku-4-5",
"reasoning": true,
"tool_call": true,
"attachment": true,
"cost": { "input": 1, "output": 5, "cache_read": 0.1, "cache_write": 1.25 },
"limit": { "context": 200000, "output": 64000 }
}
}
},
"openai": {
"id": "openai",
"name": "OpenAI",
"models": {
"gpt-4o": {
"id": "gpt-4o",
"tool_call": true,
"attachment": true,
"cost": { "input": 2.5, "output": 10, "cache_read": 1.25 },
"limit": { "context": 128000, "output": 16384 }
},
"gpt-4o-mini": {
"id": "gpt-4o-mini",
"tool_call": true,
"attachment": true,
"cost": { "input": 0.15, "output": 0.6, "cache_read": 0.075 },
"limit": { "context": 128000, "output": 16384 }
},
"gpt-5": {
"id": "gpt-5",
"reasoning": true,
"tool_call": true,
"attachment": true,
"cost": { "input": 1.25, "output": 10, "cache_read": 0.125 },
"limit": { "context": 400000, "output": 128000 }
},
"o3": {
"id": "o3",
"reasoning": true,
"tool_call": true,
"cost": { "input": 2, "output": 8, "cache_read": 0.5 },
"limit": { "context": 200000, "output": 100000 }
}
}
}
}
-228
View File
@@ -1,228 +0,0 @@
//! Credential storage for providers that authenticate outside the config file.
//!
//! A single JSON file (`~/.local/share/ai-harness/auth.json`, mode `0600`) keyed by provider
//! id. OAuth providers (Copilot) store the token triple and refresh it in place; API-key
//! providers store the bare key. Config-supplied keys take precedence over this file — this
//! is only for interactively-obtained credentials.
use std::collections::HashMap;
use std::io;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum AuthRecord {
/// OAuth credentials. `expires` is a unix-ms timestamp; `0` means the token never expires
/// (opencode's direct-Bearer Copilot mode).
OAuth {
access: String,
refresh: String,
expires: i64,
},
Api {
key: String,
},
}
impl AuthRecord {
/// True when an OAuth token is at or past `expires` (with a safety skew), given `now_ms`.
/// API keys and never-expiring OAuth tokens (`expires == 0`) are never considered expired.
pub fn is_expired(&self, now_ms: i64, skew_ms: i64) -> bool {
match self {
AuthRecord::OAuth { expires, .. } if *expires > 0 => now_ms + skew_ms >= *expires,
_ => false,
}
}
}
/// Read/modify/write access to the auth file. Cheap to construct; every operation reloads so
/// concurrent writers (a refresh in one provider, a login in another) don't clobber each other.
#[derive(Debug, Clone)]
pub struct AuthStorage {
path: PathBuf,
}
impl AuthStorage {
pub fn new(path: PathBuf) -> Self {
Self { path }
}
/// `~/.local/share/ai-harness/auth.json` (falling back to the temp dir if there is no
/// data directory).
pub fn default_path() -> PathBuf {
dirs::data_dir()
.unwrap_or_else(std::env::temp_dir)
.join("ai-harness")
.join("auth.json")
}
pub fn with_default_path() -> Self {
Self::new(Self::default_path())
}
/// Loads all records. A missing file yields an empty map; a corrupt file is an error.
pub fn load(&self) -> io::Result<HashMap<String, AuthRecord>> {
match std::fs::read(&self.path) {
Ok(bytes) => serde_json::from_slice(&bytes)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(HashMap::new()),
Err(e) => Err(e),
}
}
pub fn get(&self, provider: &str) -> io::Result<Option<AuthRecord>> {
Ok(self.load()?.remove(provider))
}
pub fn set(&self, provider: &str, record: AuthRecord) -> io::Result<()> {
let mut records = self.load()?;
records.insert(provider.to_string(), record);
self.write(&records)
}
pub fn remove(&self, provider: &str) -> io::Result<()> {
let mut records = self.load()?;
if records.remove(provider).is_some() {
self.write(&records)?;
}
Ok(())
}
/// Serializes `records` and writes them with `0600` permissions via a temp-file rename so
/// a partial write can never leave a truncated auth file behind.
fn write(&self, records: &HashMap<String, AuthRecord>) -> io::Result<()> {
if let Some(parent) = self.path.parent() {
std::fs::create_dir_all(parent)?;
}
let json = serde_json::to_vec_pretty(records)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
let tmp = self.path.with_extension("json.tmp");
std::fs::write(&tmp, &json)?;
set_owner_only(&tmp)?;
std::fs::rename(&tmp, &self.path)?;
Ok(())
}
}
#[cfg(unix)]
fn set_owner_only(path: &Path) -> io::Result<()> {
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))
}
#[cfg(not(unix))]
fn set_owner_only(_path: &Path) -> io::Result<()> {
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn storage() -> (tempfile::TempDir, AuthStorage) {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("nested").join("auth.json");
(dir, AuthStorage::new(path))
}
#[test]
fn missing_file_loads_empty() {
let (_dir, store) = storage();
assert!(store.load().unwrap().is_empty());
assert_eq!(store.get("anthropic").unwrap(), None);
}
#[test]
fn set_get_roundtrip_and_overwrite() {
let (_dir, store) = storage();
store
.set("anthropic", AuthRecord::Api { key: "k1".into() })
.unwrap();
assert_eq!(
store.get("anthropic").unwrap(),
Some(AuthRecord::Api { key: "k1".into() })
);
store
.set("anthropic", AuthRecord::Api { key: "k2".into() })
.unwrap();
assert_eq!(
store.get("anthropic").unwrap(),
Some(AuthRecord::Api { key: "k2".into() })
);
}
#[test]
fn multiple_providers_coexist() {
let (_dir, store) = storage();
store
.set("openai", AuthRecord::Api { key: "sk".into() })
.unwrap();
store
.set(
"github-copilot",
AuthRecord::OAuth {
access: "a".into(),
refresh: "r".into(),
expires: 0,
},
)
.unwrap();
let all = store.load().unwrap();
assert_eq!(all.len(), 2);
assert!(all.contains_key("openai"));
assert!(all.contains_key("github-copilot"));
}
#[test]
fn remove_deletes_only_named_provider() {
let (_dir, store) = storage();
store
.set("openai", AuthRecord::Api { key: "sk".into() })
.unwrap();
store
.set("anthropic", AuthRecord::Api { key: "an".into() })
.unwrap();
store.remove("openai").unwrap();
assert_eq!(store.get("openai").unwrap(), None);
assert!(store.get("anthropic").unwrap().is_some());
// Removing an absent provider is a no-op, not an error.
store.remove("openai").unwrap();
}
#[test]
fn oauth_expiry_respects_skew_and_never_expires() {
let never = AuthRecord::OAuth {
access: "a".into(),
refresh: "r".into(),
expires: 0,
};
assert!(!never.is_expired(i64::MAX, 0));
let expiring = AuthRecord::OAuth {
access: "a".into(),
refresh: "r".into(),
expires: 1_000,
};
assert!(!expiring.is_expired(800, 120));
assert!(expiring.is_expired(880, 120)); // within skew window
assert!(expiring.is_expired(1_000, 0));
assert!(!AuthRecord::Api { key: "k".into() }.is_expired(i64::MAX, 0));
}
#[cfg(unix)]
#[test]
fn file_is_written_owner_only() {
use std::os::unix::fs::PermissionsExt;
let (_dir, store) = storage();
store
.set("openai", AuthRecord::Api { key: "sk".into() })
.unwrap();
let mode = std::fs::metadata(&store.path).unwrap().permissions().mode();
assert_eq!(mode & 0o777, 0o600);
}
}
@@ -1,3 +1 @@
pub mod anthropic; pub mod anthropic;
pub mod openai_chat;
pub mod openai_responses;
@@ -1,502 +0,0 @@
//! Request builder + SSE decoder for OpenAI's `/chat/completions` streaming API.
//!
//! Also used as the fallback codec for OpenAI-compatible endpoints (including Copilot models
//! whose `supported_endpoints` list `/chat/completions`).
use std::collections::HashMap;
use async_stream::try_stream;
use eventsource_stream::Eventsource;
use futures::Stream;
use harness_core::llm::{
FinishReason, LlmEvent, LlmEventStream, LlmRequest, ProviderError, ReasoningEffort, Role,
WireContent,
};
use harness_core::types::TokenUsage;
use serde_json::{json, Value};
fn effort_str(effort: ReasoningEffort) -> &'static str {
match effort {
ReasoningEffort::Low => "low",
ReasoningEffort::Medium => "medium",
ReasoningEffort::High => "high",
}
}
fn role_str(role: Role) -> &'static str {
match role {
Role::System => "system",
Role::User => "user",
Role::Assistant => "assistant",
Role::Tool => "tool",
}
}
/// Flattens our grouped `WireMessage`s into the flat chat-completions message list. Tool
/// results become their own `role: "tool"` messages (one per result), which is what the API
/// expects regardless of how the engine grouped them.
fn build_messages(system: &[String], messages: &[harness_core::llm::WireMessage]) -> Vec<Value> {
let mut out: Vec<Value> = Vec::new();
if !system.is_empty() {
out.push(json!({"role": "system", "content": system.join("\n\n")}));
}
for m in messages {
// Tool results are always emitted as standalone `tool` messages.
for c in &m.content {
if let WireContent::ToolResult {
call_id, output, ..
} = c
{
out.push(json!({
"role": "tool",
"tool_call_id": call_id,
"content": output,
}));
}
}
let mut text = String::new();
let mut images: Vec<Value> = Vec::new();
let mut tool_calls: Vec<Value> = Vec::new();
for c in &m.content {
match c {
WireContent::Text { text: t } => {
if !text.is_empty() {
text.push('\n');
}
text.push_str(t);
}
WireContent::ToolCall {
call_id,
name,
input,
} => tool_calls.push(json!({
"id": call_id,
"type": "function",
"function": {"name": name, "arguments": input.to_string()},
})),
WireContent::Image { mime_type, data } => images.push(json!({
"type": "image_url",
"image_url": {"url": format!("data:{mime_type};base64,{data}")},
})),
WireContent::ToolResult { .. } => {} // handled above
}
}
// A message that carried nothing but tool results contributes no further entry.
if text.is_empty() && images.is_empty() && tool_calls.is_empty() {
continue;
}
let mut msg = json!({"role": role_str(m.role)});
if images.is_empty() {
msg["content"] = json!(text);
} else {
let mut parts = vec![json!({"type": "text", "text": text})];
parts.extend(images);
msg["content"] = json!(parts);
}
if !tool_calls.is_empty() {
msg["tool_calls"] = json!(tool_calls);
}
out.push(msg);
}
out
}
pub fn build_request(req: &LlmRequest) -> Value {
let mut body = json!({
"model": req.model,
"messages": build_messages(&req.system, &req.messages),
"stream": true,
"stream_options": {"include_usage": true},
});
if !req.tools.is_empty() {
body["tools"] = Value::Array(
req.tools
.iter()
.map(|t| {
json!({
"type": "function",
"function": {
"name": t.name,
"description": t.description,
"parameters": t.parameters,
},
})
})
.collect(),
);
}
if let Some(temp) = req.temperature {
body["temperature"] = json!(temp);
}
if let Some(max) = req.max_tokens {
body["max_completion_tokens"] = json!(max);
}
if let Some(effort) = req.reasoning.as_ref().and_then(|r| r.effort) {
body["reasoning_effort"] = json!(effort_str(effort));
}
body
}
fn map_finish_reason(reason: &str) -> FinishReason {
match reason {
"stop" => FinishReason::Stop,
"tool_calls" | "function_call" => FinishReason::ToolCalls,
"length" => FinishReason::Length,
"content_filter" => FinishReason::ContentFilter,
other => FinishReason::Unknown(other.to_string()),
}
}
#[derive(Default)]
struct ToolAccum {
call_id: String,
name: String,
args: String,
}
/// Decodes a chat-completions SSE byte stream into normalized `LlmEvent`s. Tool-call deltas
/// are accumulated by their `index` and flushed as `ToolCall`s once the stream ends.
pub fn decode<S, E>(byte_stream: S) -> LlmEventStream
where
S: Stream<Item = Result<bytes::Bytes, E>> + Send + 'static,
E: std::error::Error + Send + Sync + 'static,
{
let events = byte_stream.eventsource();
Box::pin(try_stream! {
futures::pin_mut!(events);
let mut usage = TokenUsage::default();
let mut reason = FinishReason::Stop;
let mut text_open = false;
let mut reasoning_open = false;
let mut tools: HashMap<u64, ToolAccum> = HashMap::new();
let mut tool_order: Vec<u64> = Vec::new();
while let Some(item) = futures::StreamExt::next(&mut events).await {
let event = item.map_err(|e| ProviderError::Decode(e.to_string()))?;
let data = event.data.trim();
if data.is_empty() {
continue;
}
if data == "[DONE]" {
break;
}
let value: Value = serde_json::from_str(data)
.map_err(|e| ProviderError::Decode(format!("{e}: {data}")))?;
if let Some(u) = value.get("usage").filter(|u| u.is_object()) {
usage.input = u["prompt_tokens"].as_u64().unwrap_or(usage.input);
usage.output = u["completion_tokens"].as_u64().unwrap_or(usage.output);
usage.reasoning = u["completion_tokens_details"]["reasoning_tokens"]
.as_u64()
.unwrap_or(usage.reasoning);
usage.cache_read = u["prompt_tokens_details"]["cached_tokens"]
.as_u64()
.unwrap_or(usage.cache_read);
}
let choice = &value["choices"][0];
let delta = &choice["delta"];
if let Some(rc) = delta["reasoning_content"].as_str().filter(|s| !s.is_empty()) {
if !reasoning_open {
reasoning_open = true;
yield LlmEvent::ReasoningStart { id: "reasoning".into() };
}
yield LlmEvent::ReasoningDelta { id: "reasoning".into(), text: rc.to_string() };
}
if let Some(text) = delta["content"].as_str().filter(|s| !s.is_empty()) {
if reasoning_open {
reasoning_open = false;
yield LlmEvent::ReasoningEnd { id: "reasoning".into(), signature: None };
}
if !text_open {
text_open = true;
yield LlmEvent::TextStart { id: "0".into() };
}
yield LlmEvent::TextDelta { id: "0".into(), text: text.to_string() };
}
if let Some(calls) = delta["tool_calls"].as_array() {
for call in calls {
let index = call["index"].as_u64().unwrap_or(0);
let entry = tools.entry(index).or_insert_with(|| {
tool_order.push(index);
ToolAccum::default()
});
if let Some(id) = call["id"].as_str().filter(|s| !s.is_empty()) {
entry.call_id = id.to_string();
}
if let Some(name) = call["function"]["name"].as_str().filter(|s| !s.is_empty()) {
entry.name = name.to_string();
yield LlmEvent::ToolInputStart {
call_id: entry.call_id.clone(),
name: entry.name.clone(),
};
}
if let Some(args) = call["function"]["arguments"].as_str().filter(|s| !s.is_empty()) {
entry.args.push_str(args);
yield LlmEvent::ToolInputDelta {
call_id: entry.call_id.clone(),
json: args.to_string(),
};
}
}
}
if let Some(fr) = choice["finish_reason"].as_str() {
reason = map_finish_reason(fr);
}
}
if reasoning_open {
yield LlmEvent::ReasoningEnd { id: "reasoning".into(), signature: None };
}
if text_open {
yield LlmEvent::TextEnd { id: "0".into() };
}
for index in tool_order {
if let Some(entry) = tools.remove(&index) {
let input: Value = if entry.args.trim().is_empty() {
json!({})
} else {
serde_json::from_str(&entry.args).unwrap_or(Value::Null)
};
yield LlmEvent::ToolCall { call_id: entry.call_id, name: entry.name, input };
}
}
yield LlmEvent::Finish { reason, usage };
})
}
#[cfg(test)]
mod tests {
use super::*;
use futures::StreamExt;
use harness_core::llm::{Initiator, ReasoningOpts, ToolSchema, WireMessage};
fn sse_stream(raw: &'static str) -> LlmEventStream {
let chunks: Vec<Result<bytes::Bytes, std::io::Error>> =
vec![Ok(bytes::Bytes::from_static(raw.as_bytes()))];
decode(futures::stream::iter(chunks))
}
fn req(model: &str) -> LlmRequest {
LlmRequest {
model: model.into(),
system: vec![],
messages: vec![],
tools: vec![],
temperature: None,
max_tokens: None,
reasoning: None,
initiator: Initiator::User,
}
}
#[tokio::test]
async fn decodes_text_only_response() {
let raw = concat!(
"data: {\"choices\":[{\"delta\":{\"content\":\"Hel\"},\"finish_reason\":null}]}\n\n",
"data: {\"choices\":[{\"delta\":{\"content\":\"lo\"},\"finish_reason\":null}]}\n\n",
"data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"stop\"}]}\n\n",
"data: {\"choices\":[],\"usage\":{\"prompt_tokens\":10,\"completion_tokens\":5}}\n\n",
"data: [DONE]\n\n",
);
let events: Vec<LlmEvent> = sse_stream(raw).map(|e| e.unwrap()).collect().await;
assert_eq!(
events,
vec![
LlmEvent::TextStart { id: "0".into() },
LlmEvent::TextDelta {
id: "0".into(),
text: "Hel".into()
},
LlmEvent::TextDelta {
id: "0".into(),
text: "lo".into()
},
LlmEvent::TextEnd { id: "0".into() },
LlmEvent::Finish {
reason: FinishReason::Stop,
usage: TokenUsage {
input: 10,
output: 5,
..Default::default()
},
},
]
);
}
#[tokio::test]
async fn decodes_tool_call_accumulated_by_index() {
let raw = concat!(
"data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"call_1\",\"function\":{\"name\":\"read\",\"arguments\":\"\"}}]}}]}\n\n",
"data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"{\\\"file\\\"\"}}]}}]}\n\n",
"data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\":\\\"a.txt\\\"}\"}}]}}]}\n\n",
"data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"tool_calls\"}],\"usage\":{\"prompt_tokens\":1,\"completion_tokens\":8}}\n\n",
"data: [DONE]\n\n",
);
let events: Vec<LlmEvent> = sse_stream(raw).map(|e| e.unwrap()).collect().await;
assert_eq!(
events,
vec![
LlmEvent::ToolInputStart {
call_id: "call_1".into(),
name: "read".into()
},
LlmEvent::ToolInputDelta {
call_id: "call_1".into(),
json: "{\"file\"".into()
},
LlmEvent::ToolInputDelta {
call_id: "call_1".into(),
json: ":\"a.txt\"}".into()
},
LlmEvent::ToolCall {
call_id: "call_1".into(),
name: "read".into(),
input: json!({"file": "a.txt"}),
},
LlmEvent::Finish {
reason: FinishReason::ToolCalls,
usage: TokenUsage {
input: 1,
output: 8,
..Default::default()
},
},
]
);
}
#[tokio::test]
async fn decodes_reasoning_content_before_text() {
let raw = concat!(
"data: {\"choices\":[{\"delta\":{\"reasoning_content\":\"hmm\"}}]}\n\n",
"data: {\"choices\":[{\"delta\":{\"content\":\"answer\"}}]}\n\n",
"data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"stop\"}]}\n\n",
"data: [DONE]\n\n",
);
let events: Vec<LlmEvent> = sse_stream(raw).map(|e| e.unwrap()).collect().await;
assert_eq!(
events,
vec![
LlmEvent::ReasoningStart {
id: "reasoning".into()
},
LlmEvent::ReasoningDelta {
id: "reasoning".into(),
text: "hmm".into()
},
LlmEvent::ReasoningEnd {
id: "reasoning".into(),
signature: None
},
LlmEvent::TextStart { id: "0".into() },
LlmEvent::TextDelta {
id: "0".into(),
text: "answer".into()
},
LlmEvent::TextEnd { id: "0".into() },
LlmEvent::Finish {
reason: FinishReason::Stop,
usage: TokenUsage::default()
},
]
);
}
#[test]
fn build_request_wraps_tools_in_function_envelope() {
let mut r = req("gpt-4o");
r.tools = vec![ToolSchema {
name: "read".into(),
description: "reads a file".into(),
parameters: json!({"type": "object"}),
}];
let body = build_request(&r);
assert_eq!(body["tools"][0]["type"], "function");
assert_eq!(body["tools"][0]["function"]["name"], "read");
assert_eq!(
body["tools"][0]["function"]["parameters"],
json!({"type": "object"})
);
assert_eq!(body["stream_options"]["include_usage"], true);
}
#[test]
fn build_request_prepends_system_message() {
let mut r = req("gpt-4o");
r.system = vec!["env".into(), "agent".into()];
r.messages = vec![WireMessage {
role: Role::User,
content: vec![WireContent::Text { text: "hi".into() }],
}];
let body = build_request(&r);
let msgs = body["messages"].as_array().unwrap();
assert_eq!(msgs[0]["role"], "system");
assert_eq!(msgs[0]["content"], "env\n\nagent");
assert_eq!(msgs[1]["role"], "user");
assert_eq!(msgs[1]["content"], "hi");
}
#[test]
fn build_request_expands_tool_results_to_tool_messages() {
let mut r = req("gpt-4o");
r.messages = vec![WireMessage {
role: Role::Tool,
content: vec![WireContent::ToolResult {
call_id: "call_1".into(),
output: "contents".into(),
is_error: false,
}],
}];
let body = build_request(&r);
let msgs = body["messages"].as_array().unwrap();
assert_eq!(msgs.len(), 1);
assert_eq!(msgs[0]["role"], "tool");
assert_eq!(msgs[0]["tool_call_id"], "call_1");
assert_eq!(msgs[0]["content"], "contents");
}
#[test]
fn build_request_emits_assistant_tool_calls() {
let mut r = req("gpt-4o");
r.messages = vec![WireMessage {
role: Role::Assistant,
content: vec![WireContent::ToolCall {
call_id: "call_1".into(),
name: "read".into(),
input: json!({"file": "a.txt"}),
}],
}];
let body = build_request(&r);
let msgs = body["messages"].as_array().unwrap();
assert_eq!(msgs[0]["tool_calls"][0]["id"], "call_1");
assert_eq!(msgs[0]["tool_calls"][0]["function"]["name"], "read");
assert_eq!(
msgs[0]["tool_calls"][0]["function"]["arguments"],
"{\"file\":\"a.txt\"}"
);
}
#[test]
fn build_request_sets_reasoning_effort() {
let mut r = req("o3");
r.reasoning = Some(ReasoningOpts {
effort: Some(ReasoningEffort::High),
budget_tokens: None,
});
let body = build_request(&r);
assert_eq!(body["reasoning_effort"], "high");
}
}
@@ -1,402 +0,0 @@
//! Request builder + SSE decoder for OpenAI's `/responses` streaming API.
//!
//! The responses API is the preferred surface for `gpt-*` / `o-*` models: it carries
//! reasoning items natively and reports reasoning-token usage separately.
use std::collections::HashMap;
use async_stream::try_stream;
use eventsource_stream::Eventsource;
use futures::Stream;
use harness_core::llm::{
FinishReason, LlmEvent, LlmEventStream, LlmRequest, ProviderError, ReasoningEffort, Role,
WireContent,
};
use harness_core::types::TokenUsage;
use serde_json::{json, Value};
fn effort_str(effort: ReasoningEffort) -> &'static str {
match effort {
ReasoningEffort::Low => "low",
ReasoningEffort::Medium => "medium",
ReasoningEffort::High => "high",
}
}
/// Builds the `input` item list. Text/image content become `message` items; tool calls and
/// their results become `function_call` / `function_call_output` items (the responses API
/// keeps these as top-level items rather than nesting them inside messages).
fn build_input(messages: &[harness_core::llm::WireMessage]) -> Vec<Value> {
let mut out: Vec<Value> = Vec::new();
for m in messages {
let (role, text_type) = match m.role {
Role::Assistant => ("assistant", "output_text"),
_ => ("user", "input_text"),
};
let mut content_parts: Vec<Value> = Vec::new();
for c in &m.content {
match c {
WireContent::Text { text } => {
content_parts.push(json!({"type": text_type, "text": text}));
}
WireContent::Image { mime_type, data } => {
content_parts.push(json!({
"type": "input_image",
"image_url": format!("data:{mime_type};base64,{data}"),
}));
}
WireContent::ToolCall {
call_id,
name,
input,
} => out.push(json!({
"type": "function_call",
"call_id": call_id,
"name": name,
"arguments": input.to_string(),
})),
WireContent::ToolResult {
call_id, output, ..
} => out.push(json!({
"type": "function_call_output",
"call_id": call_id,
"output": output,
})),
}
}
if !content_parts.is_empty() {
out.push(json!({"type": "message", "role": role, "content": content_parts}));
}
}
out
}
pub fn build_request(req: &LlmRequest) -> Value {
let mut body = json!({
"model": req.model,
"input": build_input(&req.messages),
"stream": true,
"store": false,
});
if !req.system.is_empty() {
body["instructions"] = json!(req.system.join("\n\n"));
}
if !req.tools.is_empty() {
body["tools"] = Value::Array(
req.tools
.iter()
.map(|t| {
json!({
"type": "function",
"name": t.name,
"description": t.description,
"parameters": t.parameters,
})
})
.collect(),
);
}
if let Some(temp) = req.temperature {
body["temperature"] = json!(temp);
}
if let Some(max) = req.max_tokens {
body["max_output_tokens"] = json!(max);
}
if let Some(effort) = req.reasoning.as_ref().and_then(|r| r.effort) {
body["reasoning"] = json!({"effort": effort_str(effort), "summary": "auto"});
}
body
}
fn map_status(status: Option<&str>, had_tool_call: bool) -> FinishReason {
match status {
Some("completed") if had_tool_call => FinishReason::ToolCalls,
Some("completed") => FinishReason::Stop,
Some("incomplete") => FinishReason::Length,
Some(other) => FinishReason::Unknown(other.to_string()),
None if had_tool_call => FinishReason::ToolCalls,
None => FinishReason::Stop,
}
}
/// Tracks which normalized stream an `item_id` belongs to so deltas route correctly.
enum ItemKind {
Text,
Reasoning,
FunctionCall { call_id: String, name: String },
}
/// Decodes a `/responses` SSE byte stream into normalized `LlmEvent`s.
pub fn decode<S, E>(byte_stream: S) -> LlmEventStream
where
S: Stream<Item = Result<bytes::Bytes, E>> + Send + 'static,
E: std::error::Error + Send + Sync + 'static,
{
let events = byte_stream.eventsource();
Box::pin(try_stream! {
futures::pin_mut!(events);
let mut items: HashMap<String, ItemKind> = HashMap::new();
let mut fn_args: HashMap<String, String> = HashMap::new();
let mut usage = TokenUsage::default();
let mut had_tool_call = false;
while let Some(item) = futures::StreamExt::next(&mut events).await {
let event = item.map_err(|e| ProviderError::Decode(e.to_string()))?;
if event.data.trim().is_empty() {
continue;
}
let value: Value = serde_json::from_str(&event.data)
.map_err(|e| ProviderError::Decode(format!("{e}: {}", event.data)))?;
let kind = value["type"].as_str().unwrap_or_default();
match kind {
"response.output_item.added" => {
let item = &value["item"];
let id = item["id"].as_str().unwrap_or_default().to_string();
match item["type"].as_str().unwrap_or_default() {
"message" => {
items.insert(id.clone(), ItemKind::Text);
yield LlmEvent::TextStart { id };
}
"reasoning" => {
items.insert(id.clone(), ItemKind::Reasoning);
yield LlmEvent::ReasoningStart { id };
}
"function_call" => {
let call_id = item["call_id"].as_str().unwrap_or_default().to_string();
let name = item["name"].as_str().unwrap_or_default().to_string();
fn_args.insert(id.clone(), String::new());
items.insert(id, ItemKind::FunctionCall { call_id: call_id.clone(), name: name.clone() });
had_tool_call = true;
yield LlmEvent::ToolInputStart { call_id, name };
}
_ => {}
}
}
"response.output_text.delta" => {
let id = value["item_id"].as_str().unwrap_or_default().to_string();
let text = value["delta"].as_str().unwrap_or_default().to_string();
yield LlmEvent::TextDelta { id, text };
}
"response.reasoning_summary_text.delta" => {
let id = value["item_id"].as_str().unwrap_or_default().to_string();
let text = value["delta"].as_str().unwrap_or_default().to_string();
yield LlmEvent::ReasoningDelta { id, text };
}
"response.function_call_arguments.delta" => {
let id = value["item_id"].as_str().unwrap_or_default().to_string();
let delta = value["delta"].as_str().unwrap_or_default();
if let (Some(buf), Some(ItemKind::FunctionCall { call_id, .. })) =
(fn_args.get_mut(&id), items.get(&id))
{
buf.push_str(delta);
yield LlmEvent::ToolInputDelta { call_id: call_id.clone(), json: delta.to_string() };
}
}
"response.output_item.done" => {
let id = value["item"]["id"].as_str().unwrap_or_default().to_string();
match items.remove(&id) {
Some(ItemKind::Text) => yield LlmEvent::TextEnd { id },
Some(ItemKind::Reasoning) => yield LlmEvent::ReasoningEnd { id, signature: None },
Some(ItemKind::FunctionCall { call_id, name }) => {
let raw = fn_args.remove(&id).unwrap_or_default();
let input: Value = if raw.trim().is_empty() {
json!({})
} else {
serde_json::from_str(&raw).unwrap_or(Value::Null)
};
yield LlmEvent::ToolCall { call_id, name, input };
}
None => {}
}
}
"response.completed" | "response.incomplete" => {
let response = &value["response"];
let u = &response["usage"];
usage.input = u["input_tokens"].as_u64().unwrap_or(0);
usage.output = u["output_tokens"].as_u64().unwrap_or(0);
usage.reasoning = u["output_tokens_details"]["reasoning_tokens"].as_u64().unwrap_or(0);
usage.cache_read = u["input_tokens_details"]["cached_tokens"].as_u64().unwrap_or(0);
let status = response["status"].as_str();
yield LlmEvent::Finish { reason: map_status(status, had_tool_call), usage };
}
"error" | "response.failed" => {
let message = value["response"]["error"]["message"]
.as_str()
.or_else(|| value["message"].as_str())
.unwrap_or("unknown error")
.to_string();
Err(ProviderError::Http { status: 0, body: message })?;
}
_ => {}
}
}
})
}
#[cfg(test)]
mod tests {
use super::*;
use futures::StreamExt;
use harness_core::llm::{Initiator, ReasoningOpts, ToolSchema, WireMessage};
fn sse_stream(raw: &'static str) -> LlmEventStream {
let chunks: Vec<Result<bytes::Bytes, std::io::Error>> =
vec![Ok(bytes::Bytes::from_static(raw.as_bytes()))];
decode(futures::stream::iter(chunks))
}
fn req(model: &str) -> LlmRequest {
LlmRequest {
model: model.into(),
system: vec![],
messages: vec![],
tools: vec![],
temperature: None,
max_tokens: None,
reasoning: None,
initiator: Initiator::User,
}
}
#[tokio::test]
async fn decodes_text_response() {
let raw = concat!(
"data: {\"type\":\"response.output_item.added\",\"item\":{\"id\":\"msg_1\",\"type\":\"message\"}}\n\n",
"data: {\"type\":\"response.output_text.delta\",\"item_id\":\"msg_1\",\"delta\":\"Hello\"}\n\n",
"data: {\"type\":\"response.output_item.done\",\"item\":{\"id\":\"msg_1\"}}\n\n",
"data: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\",\"usage\":{\"input_tokens\":10,\"output_tokens\":5}}}\n\n",
);
let events: Vec<LlmEvent> = sse_stream(raw).map(|e| e.unwrap()).collect().await;
assert_eq!(
events,
vec![
LlmEvent::TextStart { id: "msg_1".into() },
LlmEvent::TextDelta {
id: "msg_1".into(),
text: "Hello".into()
},
LlmEvent::TextEnd { id: "msg_1".into() },
LlmEvent::Finish {
reason: FinishReason::Stop,
usage: TokenUsage {
input: 10,
output: 5,
..Default::default()
},
},
]
);
}
#[tokio::test]
async fn decodes_function_call_with_reasoning_tokens() {
let raw = concat!(
"data: {\"type\":\"response.output_item.added\",\"item\":{\"id\":\"fc_1\",\"type\":\"function_call\",\"call_id\":\"call_1\",\"name\":\"read\"}}\n\n",
"data: {\"type\":\"response.function_call_arguments.delta\",\"item_id\":\"fc_1\",\"delta\":\"{\\\"file\\\":\"}\n\n",
"data: {\"type\":\"response.function_call_arguments.delta\",\"item_id\":\"fc_1\",\"delta\":\"\\\"a.txt\\\"}\"}\n\n",
"data: {\"type\":\"response.output_item.done\",\"item\":{\"id\":\"fc_1\"}}\n\n",
"data: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\",\"usage\":{\"input_tokens\":3,\"output_tokens\":9,\"output_tokens_details\":{\"reasoning_tokens\":4}}}}\n\n",
);
let events: Vec<LlmEvent> = sse_stream(raw).map(|e| e.unwrap()).collect().await;
assert_eq!(
events,
vec![
LlmEvent::ToolInputStart {
call_id: "call_1".into(),
name: "read".into()
},
LlmEvent::ToolInputDelta {
call_id: "call_1".into(),
json: "{\"file\":".into()
},
LlmEvent::ToolInputDelta {
call_id: "call_1".into(),
json: "\"a.txt\"}".into()
},
LlmEvent::ToolCall {
call_id: "call_1".into(),
name: "read".into(),
input: json!({"file": "a.txt"}),
},
LlmEvent::Finish {
reason: FinishReason::ToolCalls,
usage: TokenUsage {
input: 3,
output: 9,
reasoning: 4,
..Default::default()
},
},
]
);
}
#[tokio::test]
async fn failed_response_surfaces_as_err() {
let raw = "data: {\"type\":\"response.failed\",\"response\":{\"error\":{\"message\":\"boom\"}}}\n\n";
let events: Vec<Result<LlmEvent, ProviderError>> = sse_stream(raw).collect().await;
assert!(
matches!(events.last(), Some(Err(ProviderError::Http { body, .. })) if body == "boom")
);
}
#[test]
fn build_request_puts_system_in_instructions() {
let mut r = req("gpt-5");
r.system = vec!["env".into(), "agent".into()];
let body = build_request(&r);
assert_eq!(body["instructions"], "env\n\nagent");
assert!(body.get("messages").is_none());
}
#[test]
fn build_request_flattens_tool_calls_and_results_to_items() {
let mut r = req("gpt-5");
r.messages = vec![
WireMessage {
role: Role::Assistant,
content: vec![WireContent::ToolCall {
call_id: "call_1".into(),
name: "read".into(),
input: json!({"file": "a.txt"}),
}],
},
WireMessage {
role: Role::Tool,
content: vec![WireContent::ToolResult {
call_id: "call_1".into(),
output: "contents".into(),
is_error: false,
}],
},
];
let body = build_request(&r);
let input = body["input"].as_array().unwrap();
assert_eq!(input[0]["type"], "function_call");
assert_eq!(input[0]["call_id"], "call_1");
assert_eq!(input[0]["arguments"], "{\"file\":\"a.txt\"}");
assert_eq!(input[1]["type"], "function_call_output");
assert_eq!(input[1]["output"], "contents");
}
#[test]
fn build_request_uses_flat_function_tool_shape_and_reasoning() {
let mut r = req("o3");
r.tools = vec![ToolSchema {
name: "read".into(),
description: "reads a file".into(),
parameters: json!({"type": "object"}),
}];
r.reasoning = Some(ReasoningOpts {
effort: Some(ReasoningEffort::Medium),
budget_tokens: None,
});
let body = build_request(&r);
assert_eq!(body["tools"][0]["type"], "function");
assert_eq!(body["tools"][0]["name"], "read");
assert_eq!(body["reasoning"]["effort"], "medium");
assert_eq!(body["reasoning"]["summary"], "auto");
}
}
@@ -1,209 +0,0 @@
//! GitHub OAuth device flow (RFC 8628) for Copilot login.
//!
//! ai-harness must register its own GitHub OAuth app and supply its client id (we do not
//! hardcode opencode's). The client id is passed in by the caller — see [`request_device_code`].
use std::time::Duration;
use serde::Deserialize;
use serde_json::Value;
const DEVICE_CODE_URL: &str = "https://github.com/login/device/code";
const ACCESS_TOKEN_URL: &str = "https://github.com/login/oauth/access_token";
const GRANT_TYPE: &str = "urn:ietf:params:oauth:grant-type:device_code";
/// Minimum scope needed to call the Copilot token-exchange endpoint.
pub const SCOPE: &str = "read:user";
#[derive(Debug, Clone, Deserialize)]
pub struct DeviceCode {
pub device_code: String,
pub user_code: String,
pub verification_uri: String,
/// Seconds between polls; GitHub requires honoring this and any `slow_down` bumps.
#[serde(default = "default_interval")]
pub interval: u64,
#[serde(default)]
pub expires_in: u64,
}
fn default_interval() -> u64 {
5
}
/// Result of one poll of the access-token endpoint.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PollOutcome {
/// The user hasn't authorized yet; keep polling at the current interval.
Pending,
/// GitHub asked us to slow down; add 5s to the interval (RFC 8628).
SlowDown,
/// Authorization complete.
Success { access_token: String },
/// Terminal failure (expired code, denied, unknown error) with a human-readable reason.
Failed(String),
}
#[derive(Debug, thiserror::Error)]
pub enum DeviceFlowError {
#[error("network: {0}")]
Network(String),
#[error("unexpected response: {0}")]
Unexpected(String),
}
/// Pure mapping of an access-token poll response body to a [`PollOutcome`], so the state
/// machine is testable without a live GitHub.
pub fn parse_poll_response(body: &Value) -> PollOutcome {
if let Some(token) = body["access_token"].as_str() {
return PollOutcome::Success {
access_token: token.to_string(),
};
}
match body["error"].as_str() {
Some("authorization_pending") => PollOutcome::Pending,
Some("slow_down") => PollOutcome::SlowDown,
Some(other) => {
let desc = body["error_description"].as_str().unwrap_or(other);
PollOutcome::Failed(desc.to_string())
}
None => PollOutcome::Failed("no access_token and no error in response".to_string()),
}
}
/// Applies a `slow_down` to a poll interval per RFC 8628 (+5s).
pub fn bump_interval(interval: u64) -> u64 {
interval + 5
}
/// Step 1: request a device + user code for `client_id`.
pub async fn request_device_code(
client: &reqwest::Client,
client_id: &str,
) -> Result<DeviceCode, DeviceFlowError> {
let resp = client
.post(DEVICE_CODE_URL)
.header("accept", "application/json")
.json(&serde_json::json!({"client_id": client_id, "scope": SCOPE}))
.send()
.await
.map_err(|e| DeviceFlowError::Network(e.to_string()))?;
let value: Value = resp
.json()
.await
.map_err(|e| DeviceFlowError::Network(e.to_string()))?;
serde_json::from_value(value.clone())
.map_err(|_| DeviceFlowError::Unexpected(value.to_string()))
}
/// Step 2 (single poll): exchange the device code for an access token, once.
pub async fn poll_once(
client: &reqwest::Client,
client_id: &str,
device_code: &str,
) -> Result<PollOutcome, DeviceFlowError> {
let resp = client
.post(ACCESS_TOKEN_URL)
.header("accept", "application/json")
.json(&serde_json::json!({
"client_id": client_id,
"device_code": device_code,
"grant_type": GRANT_TYPE,
}))
.send()
.await
.map_err(|e| DeviceFlowError::Network(e.to_string()))?;
let value: Value = resp
.json()
.await
.map_err(|e| DeviceFlowError::Network(e.to_string()))?;
Ok(parse_poll_response(&value))
}
/// Step 2 (full loop): polls until success or terminal failure, honoring `interval` and
/// `slow_down`. `sleep` is injected so tests can drive it without real time.
pub async fn poll_for_token<S, Fut>(
client: &reqwest::Client,
client_id: &str,
device: &DeviceCode,
sleep: S,
) -> Result<String, DeviceFlowError>
where
S: Fn(Duration) -> Fut,
Fut: std::future::Future<Output = ()>,
{
let mut interval = device.interval;
loop {
sleep(Duration::from_secs(interval)).await;
match poll_once(client, client_id, &device.device_code).await? {
PollOutcome::Pending => {}
PollOutcome::SlowDown => interval = bump_interval(interval),
PollOutcome::Success { access_token } => return Ok(access_token),
PollOutcome::Failed(reason) => return Err(DeviceFlowError::Unexpected(reason)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn parses_success() {
let outcome =
parse_poll_response(&json!({"access_token": "gho_abc", "token_type": "bearer"}));
assert_eq!(
outcome,
PollOutcome::Success {
access_token: "gho_abc".into()
}
);
}
#[test]
fn parses_pending_and_slow_down() {
assert_eq!(
parse_poll_response(&json!({"error": "authorization_pending"})),
PollOutcome::Pending
);
assert_eq!(
parse_poll_response(&json!({"error": "slow_down", "interval": 10})),
PollOutcome::SlowDown
);
}
#[test]
fn parses_terminal_errors_with_description() {
match parse_poll_response(
&json!({"error": "expired_token", "error_description": "code expired"}),
) {
PollOutcome::Failed(msg) => assert_eq!(msg, "code expired"),
other => panic!("expected Failed, got {other:?}"),
}
assert!(matches!(
parse_poll_response(&json!({"error": "access_denied"})),
PollOutcome::Failed(_)
));
assert!(matches!(
parse_poll_response(&json!({})),
PollOutcome::Failed(_)
));
}
#[test]
fn slow_down_adds_five_seconds() {
assert_eq!(bump_interval(5), 10);
assert_eq!(bump_interval(10), 15);
}
#[test]
fn device_code_defaults_interval() {
let dc: DeviceCode = serde_json::from_value(json!({
"device_code": "d",
"user_code": "WXYZ-1234",
"verification_uri": "https://github.com/login/device"
}))
.unwrap();
assert_eq!(dc.interval, 5);
}
}
@@ -1,10 +0,0 @@
//! GitHub Copilot: OAuth device-flow login, token exchange, and a provider that multiplexes
//! the chat/responses/anthropic codecs behind `api.githubcopilot.com`.
pub mod device_flow;
pub mod provider;
pub mod token;
pub use device_flow::{DeviceCode, PollOutcome};
pub use provider::{CopilotCodec, CopilotModel, CopilotProvider};
pub use token::{CopilotToken, TokenProvider};
@@ -1,296 +0,0 @@
//! Copilot provider: multiplexes all three wire codecs behind `api.githubcopilot.com`.
//!
//! Each model's `supported_endpoints` (from `GET /models`) decides which codec/endpoint to
//! use. The token comes from [`super::token::TokenProvider`]. Network paths here are the
//! flagged live-verification risk — the routing/header logic is unit-tested; end-to-end
//! streaming must be checked against the live API.
use std::collections::HashMap;
use std::time::{SystemTime, UNIX_EPOCH};
use async_trait::async_trait;
use harness_core::llm::{
Initiator, LlmEventStream, LlmRequest, Provider, ProviderError, WireContent,
};
use harness_core::types::ModelInfo;
use serde_json::Value;
use tokio_util::sync::CancellationToken;
use crate::codec::{anthropic, openai_chat, openai_responses};
use super::token::TokenProvider;
pub const DEFAULT_BASE_URL: &str = "https://api.githubcopilot.com";
const API_VERSION: &str = "2026-06-01";
const ANTHROPIC_BETA: &str = "interleaved-thinking-2025-05-14";
const USER_AGENT: &str = concat!("ai-harness/", env!("CARGO_PKG_VERSION"));
/// Which wire codec a Copilot model speaks.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CopilotCodec {
Chat,
Responses,
Anthropic,
}
impl CopilotCodec {
fn path(self) -> &'static str {
match self {
CopilotCodec::Chat => "/chat/completions",
CopilotCodec::Responses => "/responses",
CopilotCodec::Anthropic => "/v1/messages",
}
}
fn build_request(self, req: &LlmRequest) -> Value {
match self {
CopilotCodec::Chat => openai_chat::build_request(req),
CopilotCodec::Responses => openai_responses::build_request(req),
CopilotCodec::Anthropic => anthropic::build_request(req),
}
}
fn decode(
self,
stream: impl futures::Stream<Item = reqwest::Result<bytes::Bytes>> + Send + 'static,
) -> LlmEventStream {
match self {
CopilotCodec::Chat => openai_chat::decode(stream),
CopilotCodec::Responses => openai_responses::decode(stream),
CopilotCodec::Anthropic => anthropic::decode(stream),
}
}
}
/// A single model as advertised by `GET /models`.
#[derive(Debug, Clone)]
pub struct CopilotModel {
pub id: String,
pub codec: CopilotCodec,
/// Only `model_picker_enabled` models are offered in the UI picker.
pub picker_enabled: bool,
}
/// Picks a codec from a model's `supported_endpoints`, preferring the responses API, then the
/// Anthropic messages API, then chat completions.
pub fn codec_for_endpoints(endpoints: &[String]) -> CopilotCodec {
let has = |needle: &str| endpoints.iter().any(|e| e.contains(needle));
if has("/responses") {
CopilotCodec::Responses
} else if has("/v1/messages") || has("/messages") {
CopilotCodec::Anthropic
} else {
CopilotCodec::Chat
}
}
/// Parses a Copilot `GET /models` response body.
pub fn parse_models(body: &Value) -> Vec<CopilotModel> {
body["data"]
.as_array()
.map(|arr| {
arr.iter()
.filter_map(|m| {
let id = m["id"].as_str()?.to_string();
let endpoints: Vec<String> = m["supported_endpoints"]
.as_array()
.map(|a| {
a.iter()
.filter_map(|e| e.as_str().map(String::from))
.collect()
})
.unwrap_or_default();
Some(CopilotModel {
id,
codec: codec_for_endpoints(&endpoints),
picker_enabled: m["model_picker_enabled"].as_bool().unwrap_or(false),
})
})
.collect()
})
.unwrap_or_default()
}
fn has_images(req: &LlmRequest) -> bool {
req.messages
.iter()
.flat_map(|m| &m.content)
.any(|c| matches!(c, WireContent::Image { .. }))
}
fn initiator_header(initiator: Initiator) -> &'static str {
match initiator {
Initiator::User => "user",
Initiator::Agent => "agent",
}
}
pub struct CopilotProvider {
tokens: TokenProvider,
base_url: String,
client: reqwest::Client,
/// model id → codec, from `GET /models`. Unknown models default to chat completions.
codecs: HashMap<String, CopilotCodec>,
}
impl CopilotProvider {
pub fn new(oauth_token: impl Into<String>, models: Vec<CopilotModel>) -> Self {
Self::with_base_url(oauth_token, DEFAULT_BASE_URL, models)
}
pub fn with_base_url(
oauth_token: impl Into<String>,
base_url: impl Into<String>,
models: Vec<CopilotModel>,
) -> Self {
let client = reqwest::Client::new();
let codecs = models.into_iter().map(|m| (m.id, m.codec)).collect();
Self {
tokens: TokenProvider::new(oauth_token, client.clone()),
base_url: base_url.into(),
client,
codecs,
}
}
fn codec_for(&self, model: &str) -> CopilotCodec {
self.codecs
.get(model)
.copied()
.unwrap_or(CopilotCodec::Chat)
}
fn classify_error(status: reqwest::StatusCode, body: String) -> ProviderError {
match status.as_u16() {
401 | 403 => ProviderError::Auth(body),
429 => ProviderError::RateLimited { retry_after: None },
s if (500..600).contains(&s) => ProviderError::Overloaded,
s => ProviderError::Http { status: s, body },
}
}
}
#[async_trait]
impl Provider for CopilotProvider {
fn id(&self) -> &str {
"github-copilot"
}
async fn list_models(&self) -> Result<Vec<ModelInfo>, ProviderError> {
// Cost/limit metadata is layered on by models.dev; routing metadata lives in `codecs`.
Ok(Vec::new())
}
async fn stream(
&self,
req: LlmRequest,
cancel: CancellationToken,
) -> Result<LlmEventStream, ProviderError> {
let codec = self.codec_for(&req.model);
let body = codec.build_request(&req);
let url = format!("{}{}", self.base_url, codec.path());
let now_secs = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as i64;
let token = self.tokens.token(now_secs).await;
let mut builder = self
.client
.post(&url)
.header("authorization", format!("Bearer {}", token.token))
.header("user-agent", USER_AGENT)
.header("x-github-api-version", API_VERSION)
.header("openai-intent", "conversation-edits")
.header("x-initiator", initiator_header(req.initiator));
if has_images(&req) {
builder = builder.header("copilot-vision-request", "true");
}
if codec == CopilotCodec::Anthropic {
builder = builder.header("anthropic-beta", ANTHROPIC_BETA);
}
let send = builder.json(&body).send();
let response = tokio::select! {
result = send => result.map_err(|e| ProviderError::Network(e.to_string()))?,
_ = cancel.cancelled() => return Err(ProviderError::Cancelled),
};
if !response.status().is_success() {
let status = response.status();
let body = response.text().await.unwrap_or_default();
return Err(Self::classify_error(status, body));
}
Ok(codec.decode(response.bytes_stream()))
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn codec_routing_prefers_responses_then_anthropic_then_chat() {
assert_eq!(
codec_for_endpoints(&["/chat/completions".into(), "/responses".into()]),
CopilotCodec::Responses
);
assert_eq!(
codec_for_endpoints(&["/v1/messages".into()]),
CopilotCodec::Anthropic
);
assert_eq!(
codec_for_endpoints(&["/chat/completions".into()]),
CopilotCodec::Chat
);
assert_eq!(codec_for_endpoints(&[]), CopilotCodec::Chat);
}
#[test]
fn parses_models_with_endpoints_and_picker_flag() {
let body = json!({
"data": [
{"id": "gpt-4o", "supported_endpoints": ["/chat/completions"], "model_picker_enabled": true},
{"id": "claude-sonnet-4-5", "supported_endpoints": ["/v1/messages"], "model_picker_enabled": true},
{"id": "o3", "supported_endpoints": ["/responses"], "model_picker_enabled": false},
{"id": "no-endpoints"}
]
});
let models = parse_models(&body);
assert_eq!(models.len(), 4);
assert_eq!(models[0].codec, CopilotCodec::Chat);
assert!(models[0].picker_enabled);
assert_eq!(models[1].codec, CopilotCodec::Anthropic);
assert_eq!(models[2].codec, CopilotCodec::Responses);
assert!(!models[2].picker_enabled);
// Missing supported_endpoints → default chat, picker false.
assert_eq!(models[3].codec, CopilotCodec::Chat);
assert!(!models[3].picker_enabled);
}
#[test]
fn unknown_model_defaults_to_chat_codec() {
let provider = CopilotProvider::new("oauth", vec![]);
assert_eq!(provider.codec_for("whatever"), CopilotCodec::Chat);
assert_eq!(provider.id(), "github-copilot");
}
#[test]
fn known_model_uses_mapped_codec() {
let provider = CopilotProvider::new(
"oauth",
vec![CopilotModel {
id: "claude-sonnet-4-5".into(),
codec: CopilotCodec::Anthropic,
picker_enabled: true,
}],
);
assert_eq!(
provider.codec_for("claude-sonnet-4-5"),
CopilotCodec::Anthropic
);
}
}
@@ -1,144 +0,0 @@
//! Copilot API token strategy (flagged-risk area — verify against the live API).
//!
//! opencode sends the GitHub OAuth token directly as the Bearer (`expires: 0`). The classic
//! Copilot API instead wants a short-lived token from `copilot_internal/v2/token`. We try the
//! exchange first and cache it until shortly before expiry; if the endpoint rejects us, we fall
//! back to the direct-Bearer behavior. Refresh is single-flight under a `tokio::Mutex`.
use serde::Deserialize;
use tokio::sync::Mutex;
const EXCHANGE_URL: &str = "https://api.github.com/copilot_internal/v2/token";
/// Refresh this many seconds before the reported expiry.
const EXPIRY_SKEW_SECS: i64 = 120;
const USER_AGENT: &str = concat!("ai-harness/", env!("CARGO_PKG_VERSION"));
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CopilotToken {
pub token: String,
/// Unix seconds; `0` means "never expires" (direct-Bearer fallback).
pub expires_at: i64,
}
impl CopilotToken {
/// True when the token should be refreshed at `now_secs` (never, for `expires_at == 0`).
pub fn needs_refresh(&self, now_secs: i64) -> bool {
self.expires_at != 0 && now_secs + EXPIRY_SKEW_SECS >= self.expires_at
}
}
#[derive(Debug, thiserror::Error)]
pub enum TokenError {
#[error("network: {0}")]
Network(String),
/// The exchange endpoint is unavailable/unauthorized — the caller should fall back to the
/// direct-Bearer strategy.
#[error("exchange unsupported (status {0})")]
ExchangeUnsupported(u16),
#[error("unexpected response: {0}")]
Unexpected(String),
}
#[derive(Deserialize)]
struct ExchangeResponse {
token: String,
#[serde(default)]
expires_at: i64,
}
/// Performs the token exchange once. `ExchangeUnsupported` signals the caller to fall back.
pub async fn exchange(
client: &reqwest::Client,
oauth_token: &str,
) -> Result<CopilotToken, TokenError> {
let resp = client
.get(EXCHANGE_URL)
.header("authorization", format!("token {oauth_token}"))
.header("accept", "application/json")
.header("user-agent", USER_AGENT)
.send()
.await
.map_err(|e| TokenError::Network(e.to_string()))?;
let status = resp.status();
if !status.is_success() {
// 401/403/404 → this deployment doesn't support the exchange; fall back to direct Bearer.
if matches!(status.as_u16(), 401 | 403 | 404) {
return Err(TokenError::ExchangeUnsupported(status.as_u16()));
}
return Err(TokenError::Network(format!("status {}", status.as_u16())));
}
let parsed: ExchangeResponse = resp
.json()
.await
.map_err(|e| TokenError::Unexpected(e.to_string()))?;
Ok(CopilotToken {
token: parsed.token,
expires_at: parsed.expires_at,
})
}
/// Caches the exchanged Copilot token and refreshes it single-flight. Falls back to using the
/// OAuth token directly (never-expiring) when the exchange endpoint rejects the request.
pub struct TokenProvider {
oauth_token: String,
client: reqwest::Client,
cached: Mutex<Option<CopilotToken>>,
}
impl TokenProvider {
pub fn new(oauth_token: impl Into<String>, client: reqwest::Client) -> Self {
Self {
oauth_token: oauth_token.into(),
client,
cached: Mutex::new(None),
}
}
/// Returns a usable Bearer token, refreshing/exchanging as needed. `now_secs` is injected
/// for testability.
pub async fn token(&self, now_secs: i64) -> CopilotToken {
let mut guard = self.cached.lock().await;
if let Some(tok) = guard.as_ref() {
if !tok.needs_refresh(now_secs) {
return tok.clone();
}
}
let fresh = match exchange(&self.client, &self.oauth_token).await {
Ok(tok) => tok,
Err(_) => CopilotToken {
// Direct-Bearer fallback: use the OAuth token itself, never expiring.
token: self.oauth_token.clone(),
expires_at: 0,
},
};
*guard = Some(fresh.clone());
fresh
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn never_expiring_token_does_not_refresh() {
let tok = CopilotToken {
token: "t".into(),
expires_at: 0,
};
assert!(!tok.needs_refresh(i64::MAX));
}
#[test]
fn refresh_triggers_within_skew_window() {
let tok = CopilotToken {
token: "t".into(),
expires_at: 1_000,
};
assert!(!tok.needs_refresh(800)); // 800 + 120 < 1000
assert!(tok.needs_refresh(881)); // 881 + 120 >= 1000
assert!(tok.needs_refresh(1_000));
}
}
-8
View File
@@ -1,14 +1,6 @@
pub mod anthropic; pub mod anthropic;
pub mod auth;
pub mod codec; pub mod codec;
pub mod copilot;
pub mod modelsdev;
pub mod openai;
pub mod registry; pub mod registry;
pub use anthropic::AnthropicProvider; pub use anthropic::AnthropicProvider;
pub use auth::{AuthRecord, AuthStorage};
pub use copilot::CopilotProvider;
pub use modelsdev::ModelCatalog;
pub use openai::OpenAiProvider;
pub use registry::ProviderRegistry; pub use registry::ProviderRegistry;
-296
View File
@@ -1,296 +0,0 @@
//! models.dev metadata: per-model context/output limits, pricing, and capability flags.
//!
//! At runtime we prefer a cached copy of `https://models.dev/api.json` (refreshed every 24h);
//! if the cache is missing/stale and the network is unavailable, we fall back to a baked
//! snapshot so cost display and limits still work offline.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};
use harness_core::types::{ModelCost, ModelInfo, ModelRef};
use serde::Deserialize;
const API_URL: &str = "https://models.dev/api.json";
const CACHE_TTL: Duration = Duration::from_secs(24 * 60 * 60);
/// Baked fallback, refreshed manually. Keeps cost/limits working with no cache and no network.
const SNAPSHOT: &str = include_str!("../assets/models-snapshot.json");
/// models.dev top-level shape: `{ provider_id: { models: { model_id: {...} } } }`. Unknown
/// keys (provider metadata, per-model extras) are ignored.
#[derive(Deserialize)]
struct ApiProvider {
#[serde(default)]
models: HashMap<String, ApiModel>,
}
#[derive(Deserialize)]
struct ApiModel {
#[serde(default)]
reasoning: bool,
#[serde(default)]
tool_call: bool,
#[serde(default)]
attachment: bool,
#[serde(default)]
cost: ApiCost,
#[serde(default)]
limit: ApiLimit,
}
#[derive(Deserialize, Default)]
struct ApiCost {
#[serde(default)]
input: f64,
#[serde(default)]
output: f64,
#[serde(default)]
cache_read: f64,
#[serde(default)]
cache_write: f64,
}
#[derive(Deserialize, Default)]
struct ApiLimit {
#[serde(default)]
context: u64,
#[serde(default)]
output: u64,
}
/// Parsed metadata keyed by `(provider_id, model_id)`.
#[derive(Debug, Clone, Default)]
pub struct ModelCatalog {
models: HashMap<(String, String), ModelInfo>,
}
impl ModelCatalog {
/// Parses a models.dev `api.json` document.
pub fn from_api_json(bytes: &[u8]) -> Result<Self, serde_json::Error> {
let raw: HashMap<String, ApiProvider> = serde_json::from_slice(bytes)?;
let mut models = HashMap::new();
for (provider_id, provider) in raw {
for (model_id, m) in provider.models {
let info = ModelInfo {
model: ModelRef::new(provider_id.clone(), model_id.clone()),
context_limit: m.limit.context,
output_limit: m.limit.output,
cost: ModelCost {
input: m.cost.input,
output: m.cost.output,
cache_read: m.cost.cache_read,
cache_write: m.cost.cache_write,
},
reasoning: m.reasoning,
tool_call: m.tool_call,
attachment: m.attachment,
};
models.insert((provider_id.clone(), model_id), info);
}
}
Ok(Self { models })
}
/// The baked fallback snapshot — always available, never fails.
pub fn baked() -> Self {
Self::from_api_json(SNAPSHOT.as_bytes()).expect("baked models snapshot must parse")
}
pub fn get(&self, provider: &str, model: &str) -> Option<&ModelInfo> {
self.models.get(&(provider.to_string(), model.to_string()))
}
/// Pricing for a model, or zero-cost if unknown.
pub fn cost(&self, provider: &str, model: &str) -> ModelCost {
self.get(provider, model)
.map(|m| m.cost)
.unwrap_or_default()
}
pub fn len(&self) -> usize {
self.models.len()
}
pub fn is_empty(&self) -> bool {
self.models.is_empty()
}
/// Default cache location: `~/.cache/ai-harness/models.json`.
pub fn default_cache_path() -> PathBuf {
dirs::cache_dir()
.unwrap_or_else(std::env::temp_dir)
.join("ai-harness")
.join("models.json")
}
/// Loads from the cache if present and younger than [`CACHE_TTL`]; otherwise returns the
/// baked snapshot. Never touches the network — call [`ModelCatalog::refresh`] for that.
pub fn load_cached_or_baked(cache_path: &Path) -> Self {
if cache_fresh(cache_path, CACHE_TTL, SystemTime::now()) {
if let Ok(bytes) = std::fs::read(cache_path) {
if let Ok(catalog) = Self::from_api_json(&bytes) {
if !catalog.is_empty() {
return catalog;
}
}
}
}
Self::baked()
}
/// Refreshes the default cache location with a fresh HTTP client. Convenience wrapper for
/// callers (the app) that don't want to depend on `reqwest` directly.
pub async fn refresh_default_cache() -> Result<Self, RefreshError> {
let client = reqwest::Client::new();
Self::refresh(&client, &Self::default_cache_path()).await
}
/// Fetches the latest metadata and writes it to `cache_path` (best-effort). Returns the
/// freshly-parsed catalog. Intended to run in the background so the *next* launch is current.
pub async fn refresh(
client: &reqwest::Client,
cache_path: &Path,
) -> Result<Self, RefreshError> {
let bytes = client
.get(API_URL)
.send()
.await
.map_err(|e| RefreshError::Network(e.to_string()))?
.error_for_status()
.map_err(|e| RefreshError::Network(e.to_string()))?
.bytes()
.await
.map_err(|e| RefreshError::Network(e.to_string()))?;
let catalog =
Self::from_api_json(&bytes).map_err(|e| RefreshError::Parse(e.to_string()))?;
if let Some(parent) = cache_path.parent() {
let _ = std::fs::create_dir_all(parent);
}
if let Err(e) = std::fs::write(cache_path, &bytes) {
tracing::warn!(error = %e, "failed to cache models.dev metadata");
}
Ok(catalog)
}
}
#[derive(Debug, thiserror::Error)]
pub enum RefreshError {
#[error("network: {0}")]
Network(String),
#[error("parse: {0}")]
Parse(String),
}
/// True when `path` exists and was modified within `ttl` of `now`.
fn cache_fresh(path: &Path, ttl: Duration, now: SystemTime) -> bool {
let Ok(modified) = std::fs::metadata(path).and_then(|m| m.modified()) else {
return false;
};
match now.duration_since(modified) {
Ok(age) => age < ttl,
Err(_) => true, // modified in the future (clock skew) — treat as fresh
}
}
#[cfg(test)]
mod tests {
use super::*;
const FIXTURE: &str = r#"{
"anthropic": {
"id": "anthropic",
"name": "Anthropic",
"models": {
"claude-sonnet-4-5": {
"id": "claude-sonnet-4-5",
"reasoning": true,
"tool_call": true,
"attachment": true,
"cost": {"input": 3, "output": 15, "cache_read": 0.3, "cache_write": 3.75},
"limit": {"context": 200000, "output": 64000}
}
}
},
"openai": {
"id": "openai",
"models": {
"gpt-4o": {
"id": "gpt-4o",
"tool_call": true,
"cost": {"input": 2.5, "output": 10},
"limit": {"context": 128000, "output": 16384}
}
}
}
}"#;
#[test]
fn parses_providers_and_models() {
let catalog = ModelCatalog::from_api_json(FIXTURE.as_bytes()).unwrap();
assert_eq!(catalog.len(), 2);
let sonnet = catalog.get("anthropic", "claude-sonnet-4-5").unwrap();
assert_eq!(sonnet.context_limit, 200_000);
assert_eq!(sonnet.output_limit, 64_000);
assert_eq!(sonnet.cost.input, 3.0);
assert_eq!(sonnet.cost.cache_write, 3.75);
assert!(sonnet.reasoning && sonnet.tool_call && sonnet.attachment);
}
#[test]
fn missing_cost_fields_default_to_zero() {
let catalog = ModelCatalog::from_api_json(FIXTURE.as_bytes()).unwrap();
let gpt = catalog.get("openai", "gpt-4o").unwrap();
assert_eq!(gpt.cost.cache_read, 0.0);
assert_eq!(gpt.cost.cache_write, 0.0);
assert!(!gpt.reasoning); // absent → false
assert!(gpt.tool_call);
}
#[test]
fn cost_helper_is_zero_for_unknown_model() {
let catalog = ModelCatalog::from_api_json(FIXTURE.as_bytes()).unwrap();
assert_eq!(catalog.cost("openai", "nonexistent"), ModelCost::default());
assert_eq!(catalog.cost("anthropic", "claude-sonnet-4-5").input, 3.0);
}
#[test]
fn baked_snapshot_parses_and_is_nonempty() {
let catalog = ModelCatalog::baked();
assert!(!catalog.is_empty());
}
#[test]
fn cache_freshness_respects_ttl() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("models.json");
assert!(!cache_fresh(&path, CACHE_TTL, SystemTime::now())); // missing
std::fs::write(&path, "{}").unwrap();
let now = SystemTime::now();
assert!(cache_fresh(&path, CACHE_TTL, now));
// A "now" far in the future makes the file look stale.
let future = now + Duration::from_secs(48 * 60 * 60);
assert!(!cache_fresh(&path, CACHE_TTL, future));
}
#[test]
fn load_cached_or_baked_falls_back_when_cache_absent() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("models.json");
let catalog = ModelCatalog::load_cached_or_baked(&path);
assert!(!catalog.is_empty()); // baked fallback
}
#[test]
fn load_cached_or_baked_reads_fresh_cache() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("models.json");
std::fs::write(&path, FIXTURE).unwrap();
let catalog = ModelCatalog::load_cached_or_baked(&path);
assert_eq!(catalog.len(), 2);
assert!(catalog.get("anthropic", "claude-sonnet-4-5").is_some());
}
}
-220
View File
@@ -1,220 +0,0 @@
use std::time::Duration;
use async_trait::async_trait;
use harness_core::llm::{LlmEventStream, LlmRequest, Provider, ProviderError};
use harness_core::types::ModelInfo;
use tokio_util::sync::CancellationToken;
use crate::codec::{openai_chat, openai_responses};
const DEFAULT_BASE_URL: &str = "https://api.openai.com/v1";
/// OpenCode Zen's OpenAI-compatible gateway (chat-completions only).
const OPENCODE_BASE_URL: &str = "https://opencode.ai/zen/v1";
/// Which OpenAI wire format to speak for a given model.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ApiFlavor {
Responses,
Chat,
}
/// `gpt-*` and `o-*` models use the responses API; everything else (including
/// OpenAI-compatible third-party endpoints) falls back to chat completions.
fn flavor_for(model: &str) -> ApiFlavor {
let is_native = model.starts_with("gpt-")
|| model.starts_with("o1")
|| model.starts_with("o3")
|| model.starts_with("o4")
|| model == "o1"
|| model == "o3";
if is_native {
ApiFlavor::Responses
} else {
ApiFlavor::Chat
}
}
pub struct OpenAiProvider {
id: String,
api_key: String,
base_url: String,
/// When set, always speak chat-completions regardless of model name — required for
/// OpenAI-compatible gateways (e.g. OpenCode Zen) that don't implement `/responses`.
chat_only: bool,
client: reqwest::Client,
}
impl OpenAiProvider {
pub fn new(api_key: impl Into<String>) -> Self {
Self {
id: "openai".to_string(),
api_key: api_key.into(),
base_url: DEFAULT_BASE_URL.to_string(),
chat_only: false,
client: reqwest::Client::new(),
}
}
pub fn with_base_url(api_key: impl Into<String>, base_url: impl Into<String>) -> Self {
Self {
id: "openai".to_string(),
api_key: api_key.into(),
base_url: base_url.into(),
chat_only: false,
client: reqwest::Client::new(),
}
}
/// An OpenCode Zen provider: id `opencode`, chat-completions only, defaulting to Zen's
/// gateway. Pass `base_url = None` to use the default endpoint.
pub fn opencode(api_key: impl Into<String>, base_url: Option<String>) -> Self {
Self {
id: "opencode".to_string(),
api_key: api_key.into(),
base_url: base_url.unwrap_or_else(|| OPENCODE_BASE_URL.to_string()),
chat_only: true,
client: reqwest::Client::new(),
}
}
/// The wire format for `model`, honoring `chat_only`.
fn flavor(&self, model: &str) -> ApiFlavor {
if self.chat_only {
ApiFlavor::Chat
} else {
flavor_for(model)
}
}
fn classify_error(
status: reqwest::StatusCode,
body: String,
retry_after: Option<Duration>,
) -> ProviderError {
match status.as_u16() {
400 if body.contains("context_length_exceeded")
|| body.contains("maximum context length") =>
{
ProviderError::ContextOverflow
}
401 | 403 => ProviderError::Auth(body),
429 => ProviderError::RateLimited { retry_after },
s if (500..600).contains(&s) => ProviderError::Overloaded,
s => ProviderError::Http { status: s, body },
}
}
}
#[async_trait]
impl Provider for OpenAiProvider {
fn id(&self) -> &str {
&self.id
}
async fn list_models(&self) -> Result<Vec<ModelInfo>, ProviderError> {
// models.dev metadata is layered on top by the caller (see `modelsdev.rs`).
Ok(Vec::new())
}
async fn stream(
&self,
req: LlmRequest,
cancel: CancellationToken,
) -> Result<LlmEventStream, ProviderError> {
let (path, body) = match self.flavor(&req.model) {
ApiFlavor::Responses => ("/responses", openai_responses::build_request(&req)),
ApiFlavor::Chat => ("/chat/completions", openai_chat::build_request(&req)),
};
let url = format!("{}{}", self.base_url, path);
let send = self
.client
.post(&url)
.header("authorization", format!("Bearer {}", self.api_key))
.json(&body)
.send();
let response = tokio::select! {
result = send => result.map_err(|e| ProviderError::Network(e.to_string()))?,
_ = cancel.cancelled() => return Err(ProviderError::Cancelled),
};
if !response.status().is_success() {
let status = response.status();
let retry_after = response
.headers()
.get("retry-after")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse::<u64>().ok())
.map(Duration::from_secs);
let body = response.text().await.unwrap_or_default();
return Err(Self::classify_error(status, body, retry_after));
}
Ok(match self.flavor(&req.model) {
ApiFlavor::Responses => openai_responses::decode(response.bytes_stream()),
ApiFlavor::Chat => openai_chat::decode(response.bytes_stream()),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn routes_gpt_and_o_series_to_responses() {
assert_eq!(flavor_for("gpt-4o"), ApiFlavor::Responses);
assert_eq!(flavor_for("gpt-5"), ApiFlavor::Responses);
assert_eq!(flavor_for("o1"), ApiFlavor::Responses);
assert_eq!(flavor_for("o3-mini"), ApiFlavor::Responses);
assert_eq!(flavor_for("o4-mini"), ApiFlavor::Responses);
}
#[test]
fn routes_other_models_to_chat() {
assert_eq!(flavor_for("llama-3.1-70b"), ApiFlavor::Chat);
assert_eq!(flavor_for("deepseek-chat"), ApiFlavor::Chat);
}
#[test]
fn id_is_openai() {
assert_eq!(OpenAiProvider::new("k").id(), "openai");
}
#[test]
fn opencode_provider_is_chat_only_and_ids_as_opencode() {
let p = OpenAiProvider::opencode("k", None);
assert_eq!(p.id(), "opencode");
assert_eq!(p.base_url, OPENCODE_BASE_URL);
// Even a gpt-*/o* model must route to chat completions on a chat-only gateway.
assert_eq!(p.flavor("gpt-5.5"), ApiFlavor::Chat);
assert_eq!(p.flavor("claude-sonnet-5"), ApiFlavor::Chat);
}
#[test]
fn opencode_honors_custom_base_url() {
let p = OpenAiProvider::opencode("k", Some("https://example.test/v1".into()));
assert_eq!(p.base_url, "https://example.test/v1");
}
#[test]
fn classifies_context_overflow_from_400_body() {
assert!(matches!(
OpenAiProvider::classify_error(
reqwest::StatusCode::BAD_REQUEST,
"context_length_exceeded".into(),
None,
),
ProviderError::ContextOverflow
));
assert!(matches!(
OpenAiProvider::classify_error(
reqwest::StatusCode::BAD_REQUEST,
"some other error".into(),
None,
),
ProviderError::Http { status: 400, .. }
));
}
}
-2
View File
@@ -149,8 +149,6 @@ mod tests {
CancellationToken::new(), CancellationToken::new(),
), ),
metadata, metadata,
spawner: None,
context_reporter: None,
} }
} }
-2
View File
@@ -232,8 +232,6 @@ mod tests {
CancellationToken::new(), CancellationToken::new(),
), ),
metadata, metadata,
spawner: None,
context_reporter: None,
} }
} }
-2
View File
@@ -130,8 +130,6 @@ mod tests {
CancellationToken::new(), CancellationToken::new(),
), ),
metadata, metadata,
spawner: None,
context_reporter: None,
} }
} }
-2
View File
@@ -159,8 +159,6 @@ mod tests {
CancellationToken::new(), CancellationToken::new(),
), ),
metadata, metadata,
spawner: None,
context_reporter: None,
} }
} }
-9
View File
@@ -4,7 +4,6 @@ mod glob;
mod grep; mod grep;
mod paths; mod paths;
mod read; mod read;
mod task;
mod write; mod write;
pub use bash::BashTool; pub use bash::BashTool;
@@ -12,7 +11,6 @@ pub use edit::EditTool;
pub use glob::GlobTool; pub use glob::GlobTool;
pub use grep::GrepTool; pub use grep::GrepTool;
pub use read::ReadTool; pub use read::ReadTool;
pub use task::TaskTool;
pub use write::WriteTool; pub use write::WriteTool;
use std::sync::Arc; use std::sync::Arc;
@@ -28,10 +26,3 @@ pub fn register_builtins(registry: &mut ToolRegistry) {
registry.register(Arc::new(GlobTool)); registry.register(Arc::new(GlobTool));
registry.register(Arc::new(GrepTool)); registry.register(Arc::new(GrepTool));
} }
/// Registers the multiagent `task` tool (M4). Kept separate from [`register_builtins`] so
/// non-orchestrating contexts can omit delegation; the tool no-ops with an error if the
/// session has no spawner wired in.
pub fn register_task_tool(registry: &mut ToolRegistry) {
registry.register(Arc::new(TaskTool));
}
-9
View File
@@ -102,13 +102,6 @@ impl Tool for ReadTool {
"(empty file or offset past end)".to_string(), "(empty file or offset past end)".to_string(),
)); ));
} }
// In a subagent session, advertise this read on the job board.
if let Some(reporter) = &ctx.context_reporter {
let reported = paths::relative_pattern(&ctx.cwd, &path);
reporter.report_file(reported, numbered.len() as u32).await;
}
Ok(ToolOutput::new( Ok(ToolOutput::new(
params.file_path.clone(), params.file_path.clone(),
numbered.join("\n"), numbered.join("\n"),
@@ -146,8 +139,6 @@ mod tests {
CancellationToken::new(), CancellationToken::new(),
), ),
metadata, metadata,
spawner: None,
context_reporter: None,
} }
} }
-140
View File
@@ -1,140 +0,0 @@
//! The `task` tool: delegate work to a specialist subagent, foreground or background.
//!
//! This tool is deliberately thin — it validates input, gates on a `task/<agent>` permission,
//! and hands off to the engine's `SubagentSpawner` (owned by the composition root), which
//! resolves the agent, enforces the depth limit, applies permission intersection, and runs
//! the child session. See `docs/04-multiagent.md`.
use async_trait::async_trait;
use serde::Deserialize;
use serde_json::json;
use harness_core::tool::{
invalid_input, SpawnError, SpawnRequest, Tool, ToolCtx, ToolError, ToolOutput,
};
#[derive(Debug, Deserialize)]
struct TaskInput {
/// Short human-facing label for the subtask (shown on the job board).
description: String,
/// The full instruction handed to the subagent.
prompt: String,
/// Which specialist to run (must be a subagent-capable agent).
subagent_type: String,
/// Alias or task id of a completed job to continue instead of starting fresh.
#[serde(default)]
task_id: Option<String>,
/// Run in the background and return immediately (tracked on the job board).
#[serde(default)]
background: bool,
}
pub struct TaskTool;
#[async_trait]
impl Tool for TaskTool {
fn name(&self) -> &str {
"task"
}
fn description(&self) -> &str {
"Delegate a self-contained unit of work to a specialist subagent. Set `background: \
true` to launch it without blocking (track progress on the job board); reuse a \
completed subagent by passing its `task_id`/alias to continue the same session."
}
fn parameters(&self) -> serde_json::Value {
json!({
"type": "object",
"properties": {
"description": { "type": "string", "description": "Short label for the subtask." },
"prompt": { "type": "string", "description": "Full instruction for the subagent." },
"subagent_type": { "type": "string", "description": "Specialist to run." },
"task_id": { "type": "string", "description": "Alias/id of a completed job to reuse." },
"background": { "type": "boolean", "description": "Launch without blocking." }
},
"required": ["description", "prompt", "subagent_type"]
})
}
async fn execute(
&self,
input: serde_json::Value,
ctx: ToolCtx,
) -> Result<ToolOutput, ToolError> {
let args: TaskInput = serde_json::from_value(input).map_err(|e| invalid_input(self, e))?;
let Some(spawner) = ctx.spawner.clone() else {
return Err(ToolError::Other(
"subagent delegation is not available in this session".into(),
));
};
// Gate on task/<agent>. `Always` grants blanket delegation to this specialist.
ctx.ask
.ask(
"task",
&args.subagent_type,
&args.subagent_type,
json!({
"agent": args.subagent_type,
"description": args.description,
"background": args.background,
}),
)
.await?;
let req = SpawnRequest {
parent_session_id: ctx.session_id.clone(),
parent_message_id: ctx.message_id.clone(),
agent: args.subagent_type.clone(),
description: args.description.clone(),
prompt: args.prompt,
reuse_task_id: args.task_id,
background: args.background,
cancel: ctx.cancel.clone(),
};
let outcome = spawner.spawn(req).await.map_err(map_spawn_error)?;
if outcome.background {
let alias = outcome.alias.unwrap_or_default();
Ok(ToolOutput {
title: format!("launched {} ({alias})", args.subagent_type),
output: format!(
"Launched background task {alias} ({}). Check the job board; do not poll — \
wait for completion.",
outcome.child_session_id
),
metadata: json!({
"child_session": outcome.child_session_id,
"agent": args.subagent_type,
"alias": alias,
"background": true,
}),
})
} else {
let text = outcome.final_text.unwrap_or_default();
Ok(ToolOutput {
title: format!("{} — {}", args.subagent_type, args.description),
output: text,
metadata: json!({
"child_session": outcome.child_session_id,
"agent": args.subagent_type,
"background": false,
}),
})
}
}
}
fn map_spawn_error(err: SpawnError) -> ToolError {
match err {
// Depth/agent problems are the model's to fix — surface as tool errors it can read
// and act on, not hard failures.
SpawnError::DepthExceeded => ToolError::Other(err.to_string()),
SpawnError::InvalidAgent(_) => ToolError::Invalid(err.to_string()),
SpawnError::ReuseNotFound(_) => ToolError::Invalid(err.to_string()),
SpawnError::Other(msg) => ToolError::Other(msg),
}
}
-2
View File
@@ -114,8 +114,6 @@ mod tests {
CancellationToken::new(), CancellationToken::new(),
), ),
metadata, metadata,
spawner: None,
context_reporter: None,
} }
} }
-15
View File
@@ -12,21 +12,6 @@ path = "src/main.rs"
harness-app = { workspace = true } harness-app = { workspace = true }
harness-core = { workspace = true } harness-core = { workspace = true }
tokio = { workspace = true } tokio = { workspace = true }
ratatui = { workspace = true }
crossterm = { workspace = true }
tui-textarea = { workspace = true }
pulldown-cmark = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
tracing-appender = { workspace = true }
dirs = { workspace = true }
anyhow = { workspace = true }
serde_json = { workspace = true }
futures = { workspace = true }
tokio-util = { workspace = true }
[dev-dependencies]
insta = "1"
[lints] [lints]
workspace = true workspace = true
-106
View File
@@ -1,106 +0,0 @@
use std::io;
use std::path::PathBuf;
use crossterm::event::EventStream;
use futures::StreamExt;
use harness_app::EngineHandle;
use harness_core::event::AppEvent;
use ratatui::backend::CrosstermBackend;
use ratatui::Terminal;
use tokio::sync::broadcast;
use tokio::time::{interval, Duration};
use crate::input::{apply_action, handle_event};
use crate::render::render;
use crate::state::AppState;
use crate::terminal::TerminalGuard;
const DEFAULT_MODEL: &str = "anthropic/claude-sonnet-4-5";
const DEFAULT_AGENT: &str = "orchestrator";
const RENDER_TICK_MS: u64 = 33;
pub struct App {
engine: EngineHandle,
state: AppState,
_terminal_guard: TerminalGuard,
terminal: Terminal<CrosstermBackend<io::Stdout>>,
events: EventStream,
bus_rx: broadcast::Receiver<AppEvent>,
render_interval: tokio::time::Interval,
}
impl App {
pub async fn new(cwd: PathBuf) -> anyhow::Result<Self> {
let engine = EngineHandle::init(cwd)?;
let bus_rx = engine.bus().subscribe();
let config = engine.config();
let model_ref = config
.model
.clone()
.unwrap_or_else(|| DEFAULT_MODEL.to_string());
let agent = DEFAULT_AGENT.to_string();
let mut state = AppState::new(model_ref, agent);
// Create a default session so the user can start typing immediately.
match engine.new_session(&state.agent, &state.model_ref).await {
Ok(session_id) => {
state.session_id = Some(session_id);
}
Err(e) => {
tracing::warn!(error = %e, "failed to create default session");
}
}
let terminal_guard = TerminalGuard::enter()?;
let backend = CrosstermBackend::new(io::stdout());
let terminal = Terminal::new(backend)?;
let events = EventStream::new();
let render_interval = interval(Duration::from_millis(RENDER_TICK_MS));
Ok(Self {
engine,
state,
_terminal_guard: terminal_guard,
terminal,
events,
bus_rx,
render_interval,
})
}
pub async fn run(&mut self) -> anyhow::Result<()> {
self.state.dirty = true;
while !self.state.quit {
tokio::select! {
biased;
maybe_event = self.events.next() => {
match maybe_event {
Some(Ok(event)) => {
let action = handle_event(event, &mut self.state, &self.engine);
apply_action(action, &mut self.state, &self.engine).await;
}
Some(Err(e)) => {
tracing::error!(error = %e, "input error");
}
None => break,
}
}
Ok(event) = self.bus_rx.recv() => {
self.state.apply_event(event);
}
_ = self.render_interval.tick() => {
if self.state.dirty {
self.terminal.draw(|frame| render(frame, &mut self.state))?;
self.state.dirty = false;
}
}
}
}
Ok(())
}
}
-320
View File
@@ -1,320 +0,0 @@
use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
use harness_app::EngineHandle;
use harness_core::permission::PermissionReply;
use crate::modal;
use crate::state::{AppState, ModalState};
/// Possible high-level actions produced by key input.
#[derive(Debug)]
pub enum InputAction {
None,
Submit { text: String },
Abort,
Quit,
LoadSessions,
NewSession,
SetModel(String),
SetAgent(String),
CloseModal,
ScrollUp(u16),
ScrollDown(u16),
PermissionReply(PermissionReply),
SessionPickerUp,
SessionPickerDown,
SessionPickerSelect,
OpenJobs,
JobsUp,
JobsDown,
JobsDrillIn,
}
/// Translate a crossterm event into an action and/or mutate `state` directly.
pub fn handle_event(event: Event, state: &mut AppState, _engine: &EngineHandle) -> InputAction {
match event {
Event::Key(key) => {
let action = handle_key(key, state);
// Any keypress can change the input buffer or cursor; force a redraw so typed
// characters appear immediately rather than only when some other event sets dirty.
state.dirty = true;
action
}
Event::Resize(_, _) => {
state.dirty = true;
InputAction::None
}
Event::Mouse(_) | Event::FocusGained | Event::FocusLost | Event::Paste(_) => {
InputAction::None
}
}
}
fn handle_key(key: KeyEvent, state: &mut AppState) -> InputAction {
match &state.modal {
ModalState::Permission { .. } => handle_permission_key(key, state),
ModalState::SessionPicker { .. } => handle_session_picker_key(key, state),
ModalState::JobsPane { .. } => handle_jobs_pane_key(key, state),
ModalState::None => handle_normal_key(key, state),
}
}
fn handle_jobs_pane_key(key: KeyEvent, _state: &mut AppState) -> InputAction {
match key.code {
KeyCode::Up => InputAction::JobsUp,
KeyCode::Down => InputAction::JobsDown,
KeyCode::Enter => InputAction::JobsDrillIn,
KeyCode::Esc => InputAction::CloseModal,
_ => InputAction::None,
}
}
fn handle_permission_key(key: KeyEvent, _state: &mut AppState) -> InputAction {
match key.code {
KeyCode::Char('y') | KeyCode::Char('Y') => {
InputAction::PermissionReply(PermissionReply::Once)
}
KeyCode::Char('a') | KeyCode::Char('A') => {
InputAction::PermissionReply(PermissionReply::Always)
}
KeyCode::Char('n') | KeyCode::Char('N') => {
InputAction::PermissionReply(PermissionReply::Reject)
}
// Esc rejects the pending request rather than merely hiding the modal — closing
// without a reply would leave the tool call blocked on its oneshot forever.
KeyCode::Esc => InputAction::PermissionReply(PermissionReply::Reject),
_ => InputAction::None,
}
}
fn handle_session_picker_key(key: KeyEvent, _state: &mut AppState) -> InputAction {
match key.code {
KeyCode::Up => InputAction::SessionPickerUp,
KeyCode::Down => InputAction::SessionPickerDown,
KeyCode::Enter => InputAction::SessionPickerSelect,
KeyCode::Esc => InputAction::CloseModal,
_ => InputAction::None,
}
}
fn handle_normal_key(key: KeyEvent, state: &mut AppState) -> InputAction {
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
// Reset the double-Ctrl+C guard on any key that isn't another Ctrl+C.
if !(matches!(key.code, KeyCode::Char('c') | KeyCode::Char('C')) && ctrl) {
state.ctrl_c_pressed = false;
}
match key.code {
KeyCode::Enter => {
let text = state.input.lines().join("\n");
state.input = tui_textarea::TextArea::default();
state
.input
.set_cursor_line_style(ratatui::style::Style::default());
if let Some(action) = parse_slash_command(&text) {
action
} else {
InputAction::Submit { text }
}
}
KeyCode::Char('c') if ctrl => {
if state.ctrl_c_pressed {
InputAction::Quit
} else {
state.ctrl_c_pressed = true;
state.dirty = true;
InputAction::None
}
}
KeyCode::Esc => {
if state.running {
InputAction::Abort
} else {
InputAction::None
}
}
KeyCode::Char('s') if ctrl => InputAction::LoadSessions,
KeyCode::Char('j') if ctrl => InputAction::OpenJobs,
KeyCode::Up => {
let (row, _) = state.input.cursor();
if row == 0 {
InputAction::ScrollUp(3)
} else {
state.input.input(key);
InputAction::None
}
}
KeyCode::Down => {
let (row, _) = state.input.cursor();
let last_line = state.input.lines().len().saturating_sub(1);
if row == last_line {
InputAction::ScrollDown(3)
} else {
state.input.input(key);
InputAction::None
}
}
_ => {
state.input.input(key);
InputAction::None
}
}
}
fn parse_slash_command(text: &str) -> Option<InputAction> {
let trimmed = text.trim();
if !trimmed.starts_with('/') {
return None;
}
let mut parts = trimmed.split_whitespace();
let cmd = parts.next()?;
let rest: String = parts.collect::<Vec<_>>().join(" ");
match cmd {
"/new" => Some(InputAction::NewSession),
"/model" if !rest.is_empty() => Some(InputAction::SetModel(rest)),
"/agent" if !rest.is_empty() => Some(InputAction::SetAgent(rest)),
"/sessions" => Some(InputAction::LoadSessions),
"/jobs" => Some(InputAction::OpenJobs),
"/quit" => Some(InputAction::Quit),
_ => None,
}
}
/// Apply an action that needs async engine calls. Non-async decisions are applied inline.
pub async fn apply_action(action: InputAction, state: &mut AppState, engine: &EngineHandle) {
match action {
InputAction::Submit { text } => {
if let Some(session_id) = state.session_id.clone() {
if let Err(e) = engine.prompt(session_id, text, &state.model_ref).await {
tracing::error!(error = %e, "prompt failed");
}
}
}
InputAction::Abort => {
if let Some(session_id) = state.session_id.clone() {
engine.abort(&session_id);
}
}
InputAction::LoadSessions => match engine.list_sessions().await {
Ok(sessions) => modal::open_session_picker(state, sessions),
Err(e) => tracing::error!(error = %e, "failed to list sessions"),
},
InputAction::NewSession => match engine.new_session(&state.agent, &state.model_ref).await {
Ok(id) => {
state.session_id = Some(id);
state.messages.clear();
state.scroll_offset = 0;
state.session_cost = 0.0;
state.session_tokens = 0;
state.dirty = true;
}
Err(e) => tracing::error!(error = %e, "failed to create session"),
},
InputAction::SetModel(model_ref) => {
state.model_ref = model_ref;
state.dirty = true;
}
InputAction::SetAgent(agent) => {
state.agent = agent;
state.dirty = true;
}
InputAction::Quit => state.quit = true,
InputAction::CloseModal => state.close_modal(),
InputAction::ScrollUp(n) => state.scroll_up(n),
InputAction::ScrollDown(n) => state.scroll_down(n),
InputAction::PermissionReply(reply) => {
modal::resolve_permission(state, engine, reply);
}
InputAction::SessionPickerUp => {
if let ModalState::SessionPicker {
selected,
sessions: _,
} = &mut state.modal
{
*selected = selected.saturating_sub(1);
}
state.dirty = true;
}
InputAction::SessionPickerDown => {
if let ModalState::SessionPicker { selected, sessions } = &mut state.modal {
if *selected + 1 < sessions.len() {
*selected += 1;
}
}
state.dirty = true;
}
InputAction::SessionPickerSelect => {
if let ModalState::SessionPicker { sessions, selected } = &state.modal {
if let Some(session) = sessions.get(*selected).cloned() {
if let Err(e) = modal::select_session(state, engine, session).await {
tracing::error!(error = %e, "failed to load session");
}
}
}
}
InputAction::OpenJobs => {
if let Some(session_id) = state.session_id.clone() {
match engine.jobs(session_id).await {
Ok(jobs) => {
state.set_jobs(jobs);
state.open_jobs_pane();
}
Err(e) => tracing::error!(error = %e, "failed to load jobs"),
}
}
}
InputAction::JobsUp => {
if let ModalState::JobsPane { selected } = &mut state.modal {
*selected = selected.saturating_sub(1);
}
state.dirty = true;
}
InputAction::JobsDown => {
let job_count = state.jobs.len();
if let ModalState::JobsPane { selected } = &mut state.modal {
if *selected + 1 < job_count {
*selected += 1;
}
}
state.dirty = true;
}
InputAction::JobsDrillIn => {
if let Some(child) = state.selected_job_child() {
match engine.get_session(child).await {
Ok(Some(session)) => {
if let Err(e) = modal::select_session(state, engine, session).await {
tracing::error!(error = %e, "failed to open subtask session");
}
}
Ok(None) => tracing::warn!("subtask session no longer exists"),
Err(e) => tracing::error!(error = %e, "failed to load subtask session"),
}
}
}
InputAction::None => {}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::state::AppState;
use crossterm::event::KeyEvent;
#[tokio::test]
async fn typing_marks_frame_dirty_and_updates_input() {
let engine = EngineHandle::init_in_memory(std::env::temp_dir()).unwrap();
let mut state = AppState::new("anthropic/claude".into(), "orchestrator".into());
state.dirty = false;
let action = handle_event(
Event::Key(KeyEvent::from(KeyCode::Char('x'))),
&mut state,
&engine,
);
assert!(matches!(action, InputAction::None));
assert!(state.dirty, "a keystroke must request a redraw");
assert_eq!(state.input.lines().join("\n"), "x");
}
}
+8 -78
View File
@@ -1,19 +1,9 @@
mod app;
mod input;
mod markdown;
mod modal;
mod render;
mod state;
mod terminal;
use std::path::PathBuf;
use harness_core::event::RunOutcome; use harness_core::event::RunOutcome;
const DEFAULT_MODEL: &str = "anthropic/claude-sonnet-4-5"; const DEFAULT_MODEL: &str = "anthropic/claude-sonnet-4-5";
fn print_usage() { fn print_usage() {
eprintln!("usage: harness [run -p \"<prompt>\" [-m provider/model]] | [tui]"); eprintln!("usage: harness run -p \"<prompt>\" [-m provider/model]");
} }
fn parse_run_args(args: &[String]) -> Option<(String, Option<String>)> { fn parse_run_args(args: &[String]) -> Option<(String, Option<String>)> {
@@ -36,7 +26,7 @@ fn parse_run_args(args: &[String]) -> Option<(String, Option<String>)> {
prompt.map(|p| (p, model)) prompt.map(|p| (p, model))
} }
async fn run_headless(args: &[String]) -> i32 { async fn run(args: &[String]) -> i32 {
let Some((prompt, model_arg)) = parse_run_args(args) else { let Some((prompt, model_arg)) = parse_run_args(args) else {
print_usage(); print_usage();
return 2; return 2;
@@ -59,7 +49,7 @@ async fn run_headless(args: &[String]) -> i32 {
}; };
let model_ref = model_arg let model_ref = model_arg
.or_else(|| app.config().model.clone()) .or_else(|| app.config.model.clone())
.unwrap_or_else(|| DEFAULT_MODEL.to_string()); .unwrap_or_else(|| DEFAULT_MODEL.to_string());
match app.run_prompt(prompt, &model_ref).await { match app.run_prompt(prompt, &model_ref).await {
@@ -83,74 +73,14 @@ async fn run_headless(args: &[String]) -> i32 {
} }
} }
fn log_dir() -> PathBuf {
dirs::data_dir()
.unwrap_or_else(std::env::temp_dir)
.join("ai-harness")
.join("log")
}
fn setup_tracing() -> anyhow::Result<tracing_appender::non_blocking::WorkerGuard> {
let log_dir = log_dir();
std::fs::create_dir_all(&log_dir)?;
let file_appender = tracing_appender::rolling::daily(log_dir, "harness-tui.log");
let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);
tracing_subscriber::fmt()
.with_writer(non_blocking)
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
.init();
Ok(guard)
}
async fn run_tui() -> i32 {
let cwd = match std::env::current_dir() {
Ok(cwd) => cwd,
Err(e) => {
eprintln!("error: could not read cwd: {e}");
return 1;
}
};
let _guard = match setup_tracing() {
Ok(guard) => guard,
Err(e) => {
eprintln!("error: could not initialize logging: {e}");
return 1;
}
};
let mut app = match crate::app::App::new(cwd).await {
Ok(app) => app,
Err(e) => {
tracing::error!(error = %e, "failed to start TUI");
eprintln!("error: {e}");
return 1;
}
};
if let Err(e) = app.run().await {
tracing::error!(error = %e, "TUI error");
eprintln!("error: {e}");
return 1;
}
0
}
#[tokio::main(flavor = "current_thread")] #[tokio::main(flavor = "current_thread")]
async fn main() { async fn main() {
let args: Vec<String> = std::env::args().skip(1).collect(); let args: Vec<String> = std::env::args().skip(1).collect();
let exit_code = match args.first().map(String::as_str) { let exit_code = if args.first().map(String::as_str) == Some("run") {
Some("run") => run_headless(&args[1..]).await, run(&args[1..]).await
Some("tui") | None => run_tui().await, } else {
Some("help") | Some("--help") | Some("-h") => { println!("harness {}", env!("CARGO_PKG_VERSION"));
print_usage(); 0
0
}
Some(cmd) => {
eprintln!("unknown command: {cmd}");
print_usage();
2
}
}; };
std::process::exit(exit_code); std::process::exit(exit_code);
} }
-255
View File
@@ -1,255 +0,0 @@
use pulldown_cmark::{CodeBlockKind, Event, HeadingLevel, Parser, Tag, TagEnd};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
/// Render a markdown string into wrapped ratatui lines.
pub fn render_markdown(text: &str, width: u16) -> Vec<Line<'static>> {
let mut lines: Vec<Line<'static>> = Vec::new();
let mut current_spans: Vec<Span<'static>> = Vec::new();
let mut current_text = String::new();
let mut in_bold = false;
let mut in_italic = false;
let mut in_code_block = false;
let mut code_block_language = String::new();
let mut list_stack: Vec<u64> = Vec::new();
let flush = |current: &mut String, spans: &mut Vec<Span<'static>>, bold, italic| {
if current.is_empty() {
return;
}
let style = base_style(bold, italic);
let span = Span::styled(std::mem::take(current), style);
spans.push(span);
};
for event in Parser::new(text) {
match event {
Event::Start(tag) => match tag {
Tag::Paragraph => {
if !lines.is_empty() && !current_text.is_empty() {
flush(&mut current_text, &mut current_spans, in_bold, in_italic);
wrap_spans(&mut lines, &mut current_spans, width);
}
}
Tag::Heading { level, .. } => {
let level_num = heading_level_from(level);
current_text.push_str(&"#".repeat(level_num as usize));
current_text.push(' ');
}
Tag::Strong => {
flush(&mut current_text, &mut current_spans, in_bold, in_italic);
in_bold = true;
}
Tag::Emphasis => {
flush(&mut current_text, &mut current_spans, in_bold, in_italic);
in_italic = true;
}
Tag::List(start) => {
list_stack.push(start.unwrap_or(1));
}
Tag::Item => {
let prefix = if let Some(n) = list_stack.last_mut() {
let p = format!("{n}. ");
*n += 1;
p
} else {
"".to_string()
};
current_text.push_str(&prefix);
}
Tag::CodeBlock(lang) => {
in_code_block = true;
code_block_language = match lang {
CodeBlockKind::Fenced(name) => name.to_string(),
CodeBlockKind::Indented => String::new(),
};
if !current_text.is_empty() || !current_spans.is_empty() {
flush(&mut current_text, &mut current_spans, in_bold, in_italic);
wrap_spans(&mut lines, &mut current_spans, width);
}
let border = if code_block_language.is_empty() {
"┌────".to_string()
} else {
format!("┌──── {code_block_language}")
};
lines.push(Line::from(Span::styled(border, code_style())));
}
_ => {}
},
Event::End(tag_end) => match tag_end {
TagEnd::Heading(_) => {
flush(&mut current_text, &mut current_spans, in_bold, in_italic);
let mut spans = std::mem::take(&mut current_spans);
for span in &mut spans {
span.style = span.style.add_modifier(Modifier::BOLD);
}
wrap_spans(&mut lines, &mut spans, width);
}
TagEnd::Paragraph => {
flush(&mut current_text, &mut current_spans, in_bold, in_italic);
wrap_spans(&mut lines, &mut current_spans, width);
}
TagEnd::Strong => {
flush(&mut current_text, &mut current_spans, in_bold, in_italic);
in_bold = false;
}
TagEnd::Emphasis => {
flush(&mut current_text, &mut current_spans, in_bold, in_italic);
in_italic = false;
}
TagEnd::List(_) => {
list_stack.pop();
}
TagEnd::CodeBlock => {
flush(&mut current_text, &mut current_spans, in_bold, in_italic);
if !current_spans.is_empty() {
for line in wrap_spans_to_lines(&mut current_spans, width) {
lines.push(prefix_code_block_line(line));
}
}
lines.push(Line::from(Span::styled("└────", code_style())));
in_code_block = false;
code_block_language.clear();
}
_ => {}
},
Event::Text(t) => {
if in_code_block {
flush(&mut current_text, &mut current_spans, in_bold, in_italic);
current_spans.push(Span::styled(t.to_string(), code_style()));
} else {
current_text.push_str(&t);
}
}
Event::Code(c) => {
flush(&mut current_text, &mut current_spans, in_bold, in_italic);
current_spans.push(Span::styled(c.to_string(), code_style()));
}
Event::Html(h) | Event::InlineHtml(h) => {
current_text.push_str(&h);
}
Event::SoftBreak | Event::HardBreak => {
flush(&mut current_text, &mut current_spans, in_bold, in_italic);
wrap_spans(&mut lines, &mut current_spans, width);
}
Event::Rule => {
flush(&mut current_text, &mut current_spans, in_bold, in_italic);
wrap_spans(&mut lines, &mut current_spans, width);
lines.push(Line::from("".repeat(width as usize)));
}
_ => {}
}
}
flush(&mut current_text, &mut current_spans, in_bold, in_italic);
if in_code_block {
for line in wrap_spans_to_lines(&mut current_spans, width) {
lines.push(prefix_code_block_line(line));
}
lines.push(Line::from(Span::styled("└────", code_style())));
} else {
wrap_spans(&mut lines, &mut current_spans, width);
}
if lines.is_empty() {
lines.push(Line::default());
}
lines
}
fn heading_level_from(level: HeadingLevel) -> u8 {
match level {
HeadingLevel::H1 => 1,
HeadingLevel::H2 => 2,
HeadingLevel::H3 => 3,
HeadingLevel::H4 => 4,
HeadingLevel::H5 => 5,
HeadingLevel::H6 => 6,
}
}
fn base_style(bold: bool, italic: bool) -> Style {
let mut style = Style::new();
if bold {
style = style.add_modifier(Modifier::BOLD);
}
if italic {
style = style.add_modifier(Modifier::ITALIC);
}
style
}
fn code_style() -> Style {
Style::new().fg(Color::Yellow)
}
fn prefix_code_block_line(line: Line<'static>) -> Line<'static> {
let mut spans = vec![Span::styled("", code_style())];
spans.extend(line.spans);
Line::from(spans)
}
/// Flush accumulated spans into `lines`, wrapping to `width`.
fn wrap_spans(lines: &mut Vec<Line<'static>>, spans: &mut Vec<Span<'static>>, width: u16) {
if spans.is_empty() {
return;
}
for line in wrap_spans_to_lines(spans, width) {
lines.push(line);
}
spans.clear();
}
fn wrap_spans_to_lines(spans: &mut Vec<Span<'static>>, width: u16) -> Vec<Line<'static>> {
let width = width.max(1) as usize;
let mut out: Vec<Line<'static>> = Vec::new();
let mut current_line: Vec<Span<'static>> = Vec::new();
let mut current_width = 0usize;
for span in spans.drain(..) {
for word in span.content.split(' ') {
let word_width = word.chars().count();
let sep = if current_width == 0 { 0 } else { 1 };
if current_width + sep + word_width > width && current_width > 0 {
out.push(Line::from(std::mem::take(&mut current_line)));
current_width = 0;
}
if current_width > 0 {
current_line.push(Span::styled(" ", span.style));
current_width += 1;
}
current_line.push(Span::styled(word.to_string(), span.style));
current_width += word_width;
}
}
if !current_line.is_empty() {
out.push(Line::from(current_line));
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn renders_heading_and_bold() {
let lines = render_markdown("# Hello\n\n**bold** text", 40);
assert!(!lines.is_empty());
let first: String = lines[0]
.spans
.iter()
.map(|s| s.content.to_string())
.collect();
assert!(first.contains("# Hello"));
}
#[test]
fn wraps_long_paragraphs() {
let text = "a ".repeat(50);
let lines = render_markdown(&text, 20);
assert!(lines.len() > 1);
}
}
-42
View File
@@ -1,42 +0,0 @@
//! Modal helpers for permission dialogs and the session picker.
//!
//! Rendering lives in `render.rs`; key handling lives in `input.rs`. This module
//! provides shared utilities for modal state transitions.
use harness_app::EngineHandle;
use harness_core::permission::PermissionReply;
use harness_core::types::Session;
use crate::state::{AppState, ModalState};
/// Resolve the current permission request with `reply`.
pub fn resolve_permission(state: &mut AppState, engine: &EngineHandle, reply: PermissionReply) {
state.handle_permission_reply(reply, engine);
}
/// Open the session picker with the supplied sessions.
pub fn open_session_picker(state: &mut AppState, sessions: Vec<Session>) {
state.open_session_picker(sessions);
}
/// Load a session's messages and parts into state.
pub async fn select_session(
state: &mut AppState,
engine: &EngineHandle,
session: Session,
) -> Result<(), harness_app::AppError> {
let session_id = session.id.clone();
let messages = engine.session_messages(session_id.clone()).await?;
let mut all_parts = Vec::new();
for message in &messages {
let parts = engine.message_parts(message.id.clone()).await?;
all_parts.extend(parts);
}
state.set_session(session, messages, all_parts);
// Surface any subtasks this session spawned (drill-in and session-switch both land here).
if let Ok(jobs) = engine.jobs(session_id).await {
state.set_jobs(jobs);
}
state.modal = ModalState::None;
Ok(())
}
-647
View File
@@ -1,647 +0,0 @@
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Clear, Paragraph, Wrap};
use ratatui::Frame;
use crate::markdown::render_markdown;
use crate::state::{AppState, ModalState, PartView, ToolStateView};
use harness_core::types::Role;
/// Render the full UI into the terminal frame.
pub fn render(frame: &mut Frame, state: &mut AppState) {
let area = frame.area();
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(1),
Constraint::Min(3),
Constraint::Length(3),
Constraint::Length(1),
])
.split(area);
render_header(frame, state, chunks[0]);
render_chat(frame, state, chunks[1]);
render_input(frame, state, chunks[2]);
render_status(frame, state, chunks[3]);
match &state.modal {
ModalState::Permission { requests } => {
render_permission_modal(frame, &requests[0], area);
}
ModalState::SessionPicker { sessions, selected } => {
render_session_picker(frame, sessions, *selected, area);
}
ModalState::JobsPane { selected } => {
render_jobs_pane(frame, &state.jobs, *selected, area);
}
ModalState::None => {}
}
}
fn render_header(frame: &mut Frame, state: &AppState, area: Rect) {
let title = if state.session_title.is_empty() {
"new session"
} else {
state.session_title.as_str()
};
let text = format!("{} · {} · {}", title, state.agent, state.model_ref);
let paragraph = Paragraph::new(text)
.style(Style::new().add_modifier(Modifier::BOLD))
.alignment(ratatui::layout::Alignment::Center);
frame.render_widget(paragraph, area);
}
fn render_chat(frame: &mut Frame, state: &mut AppState, area: Rect) {
let effective_width = area.width.saturating_sub(4).max(1);
// Cached lines are wrapped to a specific width, so a resize must drop them.
if state.render_width != effective_width {
state.invalidate_caches();
state.render_width = effective_width;
}
let mut lines: Vec<Line<'static>> = Vec::new();
for message in &mut state.messages {
let role_style = match message.role {
Role::User => Style::new().fg(Color::Cyan),
Role::Assistant => Style::new(),
};
let prefix = match message.role {
Role::User => "> ",
Role::Assistant => "",
};
let mut first = true;
for part in &mut message.parts {
let part_lines = render_part(part, effective_width, role_style, prefix, first);
lines.extend(part_lines);
first = false;
}
lines.push(Line::default());
}
let paragraph = Paragraph::new(lines)
.block(Block::default().borders(Borders::ALL).title(" chat "))
.scroll((state.scroll_offset, 0));
frame.render_widget(paragraph, area);
}
fn render_part(
part: &mut PartView,
effective_width: u16,
role_style: Style,
prefix: &'static str,
first: bool,
) -> Vec<Line<'static>> {
match part {
PartView::Text {
text, cached_lines, ..
} => {
// Cache the prefix-free markdown render; the `> ` prefix is cheap to re-apply
// to the clone each frame and would otherwise poison a shared cache.
let base = cached_lines.get_or_insert_with(|| render_markdown(text, effective_width));
let mut rendered = base.clone();
if first && !prefix.is_empty() {
if let Some(first_line) = rendered.first_mut() {
let mut spans = vec![Span::styled(prefix, role_style)];
spans.extend(first_line.spans.clone());
*first_line = Line::from(spans);
}
}
rendered
}
PartView::Reasoning { text, .. } => {
let style = Style::new()
.fg(Color::DarkGray)
.add_modifier(Modifier::ITALIC);
render_markdown(text, effective_width)
.into_iter()
.map(|line| {
let mut spans = vec![Span::styled("🧠 ", style)];
spans.extend(line.spans);
Line::from(spans)
})
.collect()
}
PartView::Tool {
name,
state,
cached_lines,
..
} => {
if let Some(cached) = cached_lines {
return cached.clone();
}
let status = state.status_label();
let icon = match state {
ToolStateView::Pending { .. } => "",
ToolStateView::Running { .. } => "",
ToolStateView::Completed { .. } => "",
ToolStateView::Error { .. } => "",
};
let title = format!("{icon} {name}{status}");
let mut lines = vec![Line::from(title)];
match state {
ToolStateView::Pending { partial_input } => {
lines.extend(render_markdown(partial_input, effective_width));
}
ToolStateView::Completed { output, .. } => {
lines.extend(render_markdown(output, effective_width));
}
ToolStateView::Error { error } => {
lines.extend(render_markdown(error, effective_width));
}
ToolStateView::Running { .. } => {}
}
*cached_lines = Some(lines.clone());
lines
}
PartView::StepFinish { .. } => vec![Line::from("─── step ───")],
}
}
fn render_input(frame: &mut Frame, state: &mut AppState, area: Rect) {
let block = Block::default().borders(Borders::ALL).title(" input ");
state.input.set_block(block);
frame.render_widget(&state.input, area);
}
fn render_status(frame: &mut Frame, state: &AppState, area: Rect) {
let spinner = if state.running { "" } else { "" };
let status = if state.running { "running" } else { "idle" };
let hints = if state.ctrl_c_pressed {
"Press Ctrl+C again to quit"
} else {
"Ctrl+S: sessions | Ctrl+J: jobs | Esc: abort | Ctrl+C: quit"
};
let usage = format!(
"{} · ${:.4}",
format_tokens(state.session_tokens),
state.session_cost
);
let text = format!("{spinner}{status} · {usage} · {hints}");
let paragraph = Paragraph::new(text).style(Style::new().fg(Color::Gray));
frame.render_widget(paragraph, area);
}
/// Compact token count: `1234` → `1.2k`, `2_000_000` → `2.0M`.
fn format_tokens(n: u64) -> String {
match n {
0..=999 => format!("{n} tok"),
1_000..=999_999 => format!("{:.1}k tok", n as f64 / 1_000.0),
_ => format!("{:.1}M tok", n as f64 / 1_000_000.0),
}
}
fn render_permission_modal(
frame: &mut Frame,
request: &harness_core::event::PermissionRequest,
area: Rect,
) {
let popup = centered_rect(60, 60, area);
frame.render_widget(Clear, popup);
let text = vec![
Line::from("Permission required").style(Style::new().add_modifier(Modifier::BOLD)),
Line::default(),
Line::from(format!("permission: {}", request.permission)),
Line::from(format!("pattern: {}", request.pattern)),
Line::default(),
Line::from("y: allow once a: allow always n: reject"),
];
let block = Block::default().borders(Borders::ALL).title(" permission ");
let paragraph = Paragraph::new(text).block(block).wrap(Wrap { trim: true });
frame.render_widget(paragraph, popup);
}
fn render_session_picker(
frame: &mut Frame,
sessions: &[harness_core::types::Session],
selected: usize,
area: Rect,
) {
let popup = centered_rect(60, 60, area);
frame.render_widget(Clear, popup);
let mut text: Vec<Line<'static>> =
vec![Line::from("Select session").style(Style::new().add_modifier(Modifier::BOLD))];
for (i, session) in sessions.iter().enumerate() {
let marker = if i == selected { "> " } else { " " };
let line = format!(
"{}{} · {} · {}/{}",
marker, session.id, session.agent, session.model.provider_id, session.model.model_id
);
let style = if i == selected {
Style::new().bg(Color::Blue).fg(Color::White)
} else {
Style::new()
};
text.push(Line::from(Span::styled(line, style)));
}
let block = Block::default().borders(Borders::ALL).title(" sessions ");
let paragraph = Paragraph::new(text).block(block).wrap(Wrap { trim: false });
frame.render_widget(paragraph, popup);
}
fn render_jobs_pane(
frame: &mut Frame,
jobs: &[harness_core::engine::JobRecord],
selected: usize,
area: Rect,
) {
let popup = centered_rect(70, 70, area);
frame.render_widget(Clear, popup);
let mut text: Vec<Line<'static>> =
vec![Line::from("Background jobs").style(Style::new().add_modifier(Modifier::BOLD))];
if jobs.is_empty() {
text.push(Line::default());
text.push(Line::from("No subtasks spawned yet.").style(Style::new().fg(Color::DarkGray)));
} else {
for (i, job) in jobs.iter().enumerate() {
let marker = if i == selected { "> " } else { " " };
let (icon, color) = job_state_style(job.state);
let header = format!(
"{marker}{icon} {} · {} · {}",
job.alias,
job.agent,
job_state_label(job.state),
);
let style = if i == selected {
Style::new().bg(Color::Blue).fg(Color::White)
} else {
Style::new().fg(color)
};
text.push(Line::from(Span::styled(header, style)));
if let Some(objective) = &job.objective {
text.push(
Line::from(format!(" {objective}")).style(Style::new().fg(Color::Gray)),
);
}
if !job.context_files.is_empty() {
let files: Vec<&str> = job
.context_files
.iter()
.take(8)
.map(|f| f.path.as_str())
.collect();
text.push(
Line::from(format!(" read: {}", files.join(", ")))
.style(Style::new().fg(Color::DarkGray)),
);
}
}
text.push(Line::default());
text.push(
Line::from("Enter: open subtask · Esc: close").style(Style::new().fg(Color::DarkGray)),
);
}
let block = Block::default().borders(Borders::ALL).title(" jobs ");
let paragraph = Paragraph::new(text).block(block).wrap(Wrap { trim: false });
frame.render_widget(paragraph, popup);
}
fn job_state_label(state: harness_core::engine::JobState) -> &'static str {
use harness_core::engine::JobState;
match state {
JobState::Running => "running",
JobState::Completed => "completed",
JobState::Error => "error",
JobState::Cancelled => "cancelled",
}
}
fn job_state_style(state: harness_core::engine::JobState) -> (&'static str, Color) {
use harness_core::engine::JobState;
match state {
JobState::Running => ("", Color::Yellow),
JobState::Completed => ("", Color::Green),
JobState::Error => ("", Color::Red),
JobState::Cancelled => ("", Color::DarkGray),
}
}
fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
let popup_layout = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Percentage((100 - percent_y) / 2),
Constraint::Percentage(percent_y),
Constraint::Percentage((100 - percent_y) / 2),
])
.split(r);
Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage((100 - percent_x) / 2),
Constraint::Percentage(percent_x),
Constraint::Percentage((100 - percent_x) / 2),
])
.split(popup_layout[1])[1]
}
#[cfg(test)]
mod tests {
use ratatui::backend::TestBackend;
use ratatui::Terminal;
use super::*;
use crate::state::{AppState, MessageView, PartView, ToolStateView};
use harness_core::event::PermissionRequest;
use harness_core::types::{MessageId, ModelRef, PartId, Role, Session, SessionId};
fn buffer_to_string(backend: &TestBackend) -> String {
let buffer = backend.buffer();
let area = buffer.area;
let mut result = String::new();
for y in 0..area.height {
for x in 0..area.width {
result.push_str(buffer[(x, y)].symbol());
}
while result.ends_with(' ') {
result.pop();
}
result.push('\n');
}
result
}
#[test]
fn snapshot_empty_session() {
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).unwrap();
let mut state = AppState::new(
"anthropic/claude-sonnet-4-5".to_string(),
"orchestrator".to_string(),
);
terminal.draw(|frame| render(frame, &mut state)).unwrap();
insta::assert_snapshot!(buffer_to_string(terminal.backend()));
}
#[test]
fn snapshot_user_and_assistant_messages() {
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).unwrap();
let mut state = AppState::new(
"anthropic/claude-sonnet-4-5".to_string(),
"orchestrator".to_string(),
);
state.session_id = Some(SessionId("ses_test_001".to_string()));
state.messages.push(MessageView {
id: MessageId("msg_test_001".to_string()),
role: Role::User,
parts: vec![PartView::Text {
id: PartId("prt_test_001".to_string()),
text: "Hello, can you read foo.txt?".to_string(),
cached_lines: None,
}],
});
state.messages.push(MessageView {
id: MessageId("msg_test_002".to_string()),
role: Role::Assistant,
parts: vec![PartView::Text {
id: PartId("prt_test_002".to_string()),
text: "I'll read that file for you.\n\n```rust\nlet x = 42;\n```".to_string(),
cached_lines: None,
}],
});
terminal.draw(|frame| render(frame, &mut state)).unwrap();
insta::assert_snapshot!(buffer_to_string(terminal.backend()));
}
#[test]
fn snapshot_tool_card_completed() {
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).unwrap();
let mut state = AppState::new(
"anthropic/claude-sonnet-4-5".to_string(),
"orchestrator".to_string(),
);
state.session_id = Some(SessionId("ses_test_001".to_string()));
state.messages.push(MessageView {
id: MessageId("msg_test_003".to_string()),
role: Role::Assistant,
parts: vec![PartView::Tool {
id: PartId("prt_test_003".to_string()),
name: "read".to_string(),
state: ToolStateView::Completed {
title: "read foo.txt".to_string(),
output: "file contents here".to_string(),
},
cached_lines: None,
}],
});
terminal.draw(|frame| render(frame, &mut state)).unwrap();
insta::assert_snapshot!(buffer_to_string(terminal.backend()));
}
#[test]
fn snapshot_tool_card_running() {
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).unwrap();
let mut state = AppState::new(
"anthropic/claude-sonnet-4-5".to_string(),
"orchestrator".to_string(),
);
state.session_id = Some(SessionId("ses_test_001".to_string()));
state.messages.push(MessageView {
id: MessageId("msg_test_004".to_string()),
role: Role::Assistant,
parts: vec![PartView::Tool {
id: PartId("prt_test_004".to_string()),
name: "read".to_string(),
state: ToolStateView::Running {
title: Some("read foo.txt".to_string()),
},
cached_lines: None,
}],
});
terminal.draw(|frame| render(frame, &mut state)).unwrap();
insta::assert_snapshot!(buffer_to_string(terminal.backend()));
}
#[test]
fn snapshot_tool_card_error() {
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).unwrap();
let mut state = AppState::new(
"anthropic/claude-sonnet-4-5".to_string(),
"orchestrator".to_string(),
);
state.session_id = Some(SessionId("ses_test_001".to_string()));
state.messages.push(MessageView {
id: MessageId("msg_test_005".to_string()),
role: Role::Assistant,
parts: vec![PartView::Tool {
id: PartId("prt_test_005".to_string()),
name: "read".to_string(),
state: ToolStateView::Error {
error: "file not found".to_string(),
},
cached_lines: None,
}],
});
terminal.draw(|frame| render(frame, &mut state)).unwrap();
insta::assert_snapshot!(buffer_to_string(terminal.backend()));
}
#[test]
fn snapshot_permission_modal() {
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).unwrap();
let mut state = AppState::new(
"anthropic/claude-sonnet-4-5".to_string(),
"orchestrator".to_string(),
);
let request = PermissionRequest {
id: "test".to_string(),
session_id: SessionId("ses_test_001".to_string()),
permission: "bash".to_string(),
pattern: "rm -rf /".to_string(),
always_pattern: "rm *".to_string(),
metadata: serde_json::Value::Null,
};
state.modal = ModalState::Permission {
requests: vec![request],
};
terminal.draw(|frame| render(frame, &mut state)).unwrap();
insta::assert_snapshot!(buffer_to_string(terminal.backend()));
}
#[test]
fn snapshot_session_picker_modal() {
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).unwrap();
let mut state = AppState::new(
"anthropic/claude-sonnet-4-5".to_string(),
"orchestrator".to_string(),
);
let sessions = vec![
Session {
id: SessionId("ses_test_001".to_string()),
parent_id: None,
depth: 0,
title: "Session One".to_string(),
agent: "orchestrator".to_string(),
model: ModelRef::new("anthropic", "claude-sonnet-4-5"),
usage: harness_core::types::TokenUsage::default(),
cost: 0.0,
extra_rules: Vec::new(),
created_at: 1,
updated_at: 1,
},
Session {
id: SessionId("ses_test_002".to_string()),
parent_id: None,
depth: 0,
title: "Session Two".to_string(),
agent: "coder".to_string(),
model: ModelRef::new("openai", "gpt-4o"),
usage: harness_core::types::TokenUsage::default(),
cost: 0.0,
extra_rules: Vec::new(),
created_at: 2,
updated_at: 2,
},
Session {
id: SessionId("ses_test_003".to_string()),
parent_id: None,
depth: 0,
title: "Session Three".to_string(),
agent: "reviewer".to_string(),
model: ModelRef::new("google", "gemini-2.5"),
usage: harness_core::types::TokenUsage::default(),
cost: 0.0,
extra_rules: Vec::new(),
created_at: 3,
updated_at: 3,
},
];
state.modal = ModalState::SessionPicker {
sessions,
selected: 1,
};
terminal.draw(|frame| render(frame, &mut state)).unwrap();
insta::assert_snapshot!(buffer_to_string(terminal.backend()));
}
#[test]
fn snapshot_jobs_pane() {
use harness_core::engine::{ContextFile, JobRecord, JobState};
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).unwrap();
let mut state = AppState::new(
"anthropic/claude-sonnet-4-5".to_string(),
"orchestrator".to_string(),
);
state.session_id = Some(SessionId("ses_test_001".to_string()));
state.jobs = vec![
JobRecord {
task_id: "t1".to_string(),
alias: "exp-1".to_string(),
parent_session: SessionId("ses_test_001".to_string()),
child_session: SessionId("ses_child_001".to_string()),
agent: "explorer".to_string(),
description: "map auth".to_string(),
objective: Some("map the auth flow".to_string()),
state: JobState::Completed,
reconciled: true,
result_summary: Some("done".to_string()),
context_files: vec![ContextFile {
path: "src/auth.rs".to_string(),
lines: 42,
}],
launched_at: 1,
updated_at: 2,
last_used_at: 2,
},
JobRecord {
task_id: "t2".to_string(),
alias: "fix-1".to_string(),
parent_session: SessionId("ses_test_001".to_string()),
child_session: SessionId("ses_child_002".to_string()),
agent: "fixer".to_string(),
description: "patch bug".to_string(),
objective: Some("fix the null deref".to_string()),
state: JobState::Running,
reconciled: false,
result_summary: None,
context_files: Vec::new(),
launched_at: 3,
updated_at: 3,
last_used_at: 3,
},
];
state.modal = ModalState::JobsPane { selected: 1 };
terminal.draw(|frame| render(frame, &mut state)).unwrap();
insta::assert_snapshot!(buffer_to_string(terminal.backend()));
}
#[test]
fn render_empty_state_produces_frame() {
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).unwrap();
let mut state = AppState::new("anthropic/claude".to_string(), "orchestrator".to_string());
terminal.draw(|frame| render(frame, &mut state)).unwrap();
let buffer = terminal.backend().buffer().clone();
assert_eq!(buffer.area.width, 80);
assert_eq!(buffer.area.height, 24);
// Header should contain the agent/model line.
let header_row: String = buffer
.content
.chunks(80)
.next()
.unwrap()
.iter()
.map(|c| c.symbol())
.collect();
assert!(header_row.contains("orchestrator"));
assert!(header_row.contains("anthropic/claude"));
}
}
@@ -1,29 +0,0 @@
---
source: crates/harness-tui/src/render.rs
assertion_line: 381
expression: buffer_to_string(terminal.backend())
---
new session · orchestrator · anthropic/claude-sonnet-4-5
┌ chat ────────────────────────────────────────────────────────────────────────┐
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
└──────────────────────────────────────────────────────────────────────────────┘
┌ input ───────────────────────────────────────────────────────────────────────┐
│ │
└──────────────────────────────────────────────────────────────────────────────┘
idle · 0 tok · $0.0000 · Ctrl+S: sessions | Ctrl+J: jobs | Esc: abort | Ctrl+C:
@@ -1,29 +0,0 @@
---
source: crates/harness-tui/src/render.rs
assertion_line: 621
expression: buffer_to_string(terminal.backend())
---
new session · orchestrator · anthropic/claude-sonnet-4-5
┌ chat ────────────────────────────────────────────────────────────────────────┐
│ │
│ │
│ ┌ jobs ────────────────────────────────────────────────┐ │
│ │Background jobs │ │
│ │ ✓ exp-1 · explorer · completed │ │
│ │ map the auth flow │ │
│ │ read: src/auth.rs │ │
│ │> ⚙ fix-1 · fixer · running │ │
│ │ fix the null deref │ │
│ │ │ │
│ │Enter: open subtask · Esc: close │ │
│ │ │ │
│ │ │ │
│ │ │ │
│ │ │ │
│ │ │ │
│ │ │ │
└───────────└──────────────────────────────────────────────────────┘───────────┘
┌ input ───────────────────────────────────────────────────────────────────────┐
│ │
└──────────────────────────────────────────────────────────────────────────────┘
idle · 0 tok · $0.0000 · Ctrl+S: sessions | Ctrl+J: jobs | Esc: abort | Ctrl+C:
@@ -1,29 +0,0 @@
---
source: crates/harness-tui/src/render.rs
assertion_line: 511
expression: buffer_to_string(terminal.backend())
---
new session · orchestrator · anthropic/claude-sonnet-4-5
┌ chat ────────────────────────────────────────────────────────────────────────┐
│ │
│ │
│ │
│ ┌ permission ──────────────────────────────────┐ │
│ │Permission required │ │
│ │ │ │
│ │permission: bash │ │
│ │pattern: rm -rf / │ │
│ │ │ │
│ │y: allow once a: allow always n: reject │ │
│ │ │ │
│ │ │ │
│ │ │ │
│ │ │ │
│ │ │ │
│ │ │ │
│ └──────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────────────────────────────┘
┌ input ───────────────────────────────────────────────────────────────────────┐
│ │
└──────────────────────────────────────────────────────────────────────────────┘
idle · 0 tok · $0.0000 · Ctrl+S: sessions | Ctrl+J: jobs | Esc: abort | Ctrl+C:
@@ -1,29 +0,0 @@
---
source: crates/harness-tui/src/render.rs
assertion_line: 568
expression: buffer_to_string(terminal.backend())
---
new session · orchestrator · anthropic/claude-sonnet-4-5
┌ chat ────────────────────────────────────────────────────────────────────────┐
│ │
│ │
│ │
│ ┌ sessions ────────────────────────────────────┐ │
│ │Select session │ │
│ │ ses_test_001 · orchestrator · │ │
│ │anthropic/claude-sonnet-4-5 │ │
│ │> ses_test_002 · coder · openai/gpt-4o │ │
│ │ ses_test_003 · reviewer · google/gemini-2.5 │ │
│ │ │ │
│ │ │ │
│ │ │ │
│ │ │ │
│ │ │ │
│ │ │ │
│ │ │ │
│ └──────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────────────────────────────┘
┌ input ───────────────────────────────────────────────────────────────────────┐
│ │
└──────────────────────────────────────────────────────────────────────────────┘
idle · 0 tok · $0.0000 · Ctrl+S: sessions | Ctrl+J: jobs | Esc: abort | Ctrl+C:
@@ -1,29 +0,0 @@
---
source: crates/harness-tui/src/render.rs
assertion_line: 438
expression: buffer_to_string(terminal.backend())
---
new session · orchestrator · anthropic/claude-sonnet-4-5
┌ chat ────────────────────────────────────────────────────────────────────────┐
│✓ read — read foo.txt │
│file contents here │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
└──────────────────────────────────────────────────────────────────────────────┘
┌ input ───────────────────────────────────────────────────────────────────────┐
│ │
└──────────────────────────────────────────────────────────────────────────────┘
idle · 0 tok · $0.0000 · Ctrl+S: sessions | Ctrl+J: jobs | Esc: abort | Ctrl+C:
@@ -1,29 +0,0 @@
---
source: crates/harness-tui/src/render.rs
assertion_line: 488
expression: buffer_to_string(terminal.backend())
---
new session · orchestrator · anthropic/claude-sonnet-4-5
┌ chat ────────────────────────────────────────────────────────────────────────┐
│✗ read — error: file not found │
│file not found │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
└──────────────────────────────────────────────────────────────────────────────┘
┌ input ───────────────────────────────────────────────────────────────────────┐
│ │
└──────────────────────────────────────────────────────────────────────────────┘
idle · 0 tok · $0.0000 · Ctrl+S: sessions | Ctrl+J: jobs | Esc: abort | Ctrl+C:
@@ -1,29 +0,0 @@
---
source: crates/harness-tui/src/render.rs
assertion_line: 463
expression: buffer_to_string(terminal.backend())
---
new session · orchestrator · anthropic/claude-sonnet-4-5
┌ chat ────────────────────────────────────────────────────────────────────────┐
│⚙ read — read foo.txt │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
└──────────────────────────────────────────────────────────────────────────────┘
┌ input ───────────────────────────────────────────────────────────────────────┐
│ │
└──────────────────────────────────────────────────────────────────────────────┘
idle · 0 tok · $0.0000 · Ctrl+S: sessions | Ctrl+J: jobs | Esc: abort | Ctrl+C:
@@ -1,29 +0,0 @@
---
source: crates/harness-tui/src/render.rs
assertion_line: 412
expression: buffer_to_string(terminal.backend())
---
new session · orchestrator · anthropic/claude-sonnet-4-5
┌ chat ────────────────────────────────────────────────────────────────────────┐
│> Hello, can you read foo.txt? │
│ │
│I'll read that file for you. │
│┌──── rust │
││ let x = 42; │
│└──── │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
└──────────────────────────────────────────────────────────────────────────────┘
┌ input ───────────────────────────────────────────────────────────────────────┐
│ │
└──────────────────────────────────────────────────────────────────────────────┘
idle · 0 tok · $0.0000 · Ctrl+S: sessions | Ctrl+J: jobs | Esc: abort | Ctrl+C:
-453
View File
@@ -1,453 +0,0 @@
use harness_app::EngineHandle;
use harness_core::engine::JobRecord;
use harness_core::event::{AppEvent, PermissionRequest, RunOutcome};
use harness_core::permission::PermissionReply;
use harness_core::types::{Message, Part, PartBody, PartId, Role, Session, SessionId, ToolState};
use ratatui::text::Line;
/// Cached view of a message in the chat viewport.
#[derive(Debug)]
pub struct MessageView {
pub id: harness_core::types::MessageId,
pub role: Role,
pub parts: Vec<PartView>,
}
/// Cached view of a part. The optional `cached_lines` field stores a pre-rendered markdown
/// representation; it is invalidated whenever the underlying text changes.
#[derive(Debug)]
pub enum PartView {
Text {
id: PartId,
text: String,
cached_lines: Option<Vec<Line<'static>>>,
},
Reasoning {
id: PartId,
text: String,
},
Tool {
id: PartId,
name: String,
state: ToolStateView,
cached_lines: Option<Vec<Line<'static>>>,
},
StepFinish {
id: PartId,
},
}
/// Simplified tool state for rendering.
#[derive(Debug)]
pub enum ToolStateView {
Pending { partial_input: String },
Running { title: Option<String> },
Completed { title: String, output: String },
Error { error: String },
}
impl ToolStateView {
fn from_tool_state(state: &ToolState) -> Self {
match state {
ToolState::Pending { partial_input } => Self::Pending {
partial_input: partial_input.clone(),
},
ToolState::Running { title, .. } => Self::Running {
title: title.clone(),
},
ToolState::Completed { title, output, .. } => Self::Completed {
title: title.clone(),
output: output.clone(),
},
ToolState::Error { error, .. } => Self::Error {
error: error.clone(),
},
}
}
pub fn status_label(&self) -> String {
match self {
Self::Pending { .. } => "pending".to_string(),
Self::Running { title } => title.clone().unwrap_or_else(|| "running".to_string()),
Self::Completed { title, .. } => title.clone(),
Self::Error { error } => format!("error: {error}"),
}
}
}
/// Active modal overlay state.
#[derive(Debug, Default)]
pub enum ModalState {
#[default]
None,
Permission {
requests: Vec<PermissionRequest>,
},
SessionPicker {
sessions: Vec<Session>,
selected: usize,
},
/// Background job board for the current session, with a cursor for drill-in.
JobsPane {
selected: usize,
},
}
/// All mutable UI state lives here.
#[derive(Debug)]
pub struct AppState {
pub session_id: Option<SessionId>,
pub session_title: String,
pub messages: Vec<MessageView>,
pub modal: ModalState,
pub input: tui_textarea::TextArea<'static>,
pub scroll_offset: u16,
pub running: bool,
pub model_ref: String,
pub agent: String,
pub quit: bool,
pub dirty: bool,
pub ctrl_c_pressed: bool,
/// Width the currently cached part lines were wrapped to; a change invalidates them.
pub render_width: u16,
/// Accumulated session cost in USD, from `SessionCreated`/`SessionUpdated` events.
pub session_cost: f64,
/// Accumulated session tokens (input + output), for the status bar.
pub session_tokens: u64,
/// Background jobs spawned by the current session, newest activity last. Populated on
/// session load and kept live via `JobUpdated` events; surfaced in the jobs pane.
pub jobs: Vec<JobRecord>,
}
impl AppState {
pub fn new(model_ref: String, agent: String) -> Self {
let mut input = tui_textarea::TextArea::default();
input.set_cursor_line_style(ratatui::style::Style::default());
Self {
session_id: None,
session_title: String::new(),
messages: Vec::new(),
modal: ModalState::None,
input,
scroll_offset: 0,
running: false,
model_ref,
agent,
quit: false,
dirty: true,
ctrl_c_pressed: false,
render_width: 0,
session_cost: 0.0,
session_tokens: 0,
jobs: Vec::new(),
}
}
/// Drop every part's cached render (e.g. after a resize changes the wrap width).
pub fn invalidate_caches(&mut self) {
for message in &mut self.messages {
for part in &mut message.parts {
match part {
PartView::Text { cached_lines, .. } | PartView::Tool { cached_lines, .. } => {
*cached_lines = None
}
PartView::Reasoning { .. } | PartView::StepFinish { .. } => {}
}
}
}
}
pub fn set_session(&mut self, session: Session, messages: Vec<Message>, parts: Vec<Part>) {
self.session_id = Some(session.id.clone());
self.session_title = session.title;
self.agent = session.agent;
self.model_ref = format!("{}/{}", session.model.provider_id, session.model.model_id);
self.session_cost = session.cost;
self.session_tokens = session.usage.input + session.usage.output;
self.messages.clear();
// Jobs are reloaded for the newly-selected session by the caller.
self.jobs.clear();
let mut messages = messages;
messages.sort_by_key(|m| m.created_at);
for message in messages {
let message_parts: Vec<Part> = parts
.iter()
.filter(|p| p.message_id == message.id)
.cloned()
.collect();
self.messages.push(message_view(message, message_parts));
}
self.scroll_offset = 0;
self.dirty = true;
}
pub fn apply_event(&mut self, event: AppEvent) {
match event {
AppEvent::SessionCreated { session } | AppEvent::SessionUpdated { session } => {
if self.session_id.as_ref() == Some(&session.id) {
self.session_title = session.title;
self.agent = session.agent;
self.model_ref =
format!("{}/{}", session.model.provider_id, session.model.model_id);
self.session_cost = session.cost;
self.session_tokens = session.usage.input + session.usage.output;
self.dirty = true;
}
}
AppEvent::MessageCreated { message } => {
if self.session_id.as_ref() == Some(&message.session_id) {
self.messages.push(message_view(message, Vec::new()));
self.dirty = true;
}
}
AppEvent::MessageUpdated { message } => {
if let Some(view) = self.messages.iter_mut().find(|m| m.id == message.id) {
view.role = message.role;
self.dirty = true;
}
}
AppEvent::PartUpdated { part } => {
if self.session_id.as_ref() == Some(&part.session_id) {
self.update_or_insert_part(part);
self.dirty = true;
}
}
AppEvent::PartDelta {
part_id,
message_id,
delta,
} => {
self.apply_delta(part_id, message_id, delta);
self.dirty = true;
}
AppEvent::RunStarted { session_id } => {
if self.session_id.as_ref() == Some(&session_id) {
self.running = true;
self.dirty = true;
}
}
AppEvent::RunFinished {
session_id,
outcome,
} => {
if self.session_id.as_ref() == Some(&session_id) {
self.running = false;
if matches!(outcome, RunOutcome::Errored { .. }) {
self.messages.push(MessageView {
id: harness_core::types::MessageId::new(),
role: Role::Assistant,
parts: vec![PartView::Text {
id: PartId::new(),
text: match outcome {
RunOutcome::Errored { message } => message,
_ => String::new(),
},
cached_lines: None,
}],
});
}
self.dirty = true;
}
}
AppEvent::PermissionAsked { request } => {
if let ModalState::Permission { requests } = &mut self.modal {
requests.push(request);
} else {
self.modal = ModalState::Permission {
requests: vec![request],
};
}
self.dirty = true;
}
AppEvent::PermissionResolved { id } => {
if let ModalState::Permission { requests } = &mut self.modal {
requests.retain(|r| r.id != id);
if requests.is_empty() {
self.modal = ModalState::None;
}
}
self.dirty = true;
}
AppEvent::JobUpdated { job } => {
if let Ok(record) = serde_json::from_value::<JobRecord>(job.0) {
if self.session_id.as_ref() == Some(&record.parent_session) {
self.upsert_job(record);
self.dirty = true;
}
}
}
AppEvent::AuthPrompt { .. } | AppEvent::ServerNotice { .. } => {
self.dirty = true;
}
}
}
/// Replaces this session's job list (e.g. after loading a session).
pub fn set_jobs(&mut self, jobs: Vec<JobRecord>) {
self.jobs = jobs;
self.dirty = true;
}
/// Inserts or replaces a job by `task_id`, preserving list order for stable rendering.
fn upsert_job(&mut self, record: JobRecord) {
if let Some(existing) = self.jobs.iter_mut().find(|j| j.task_id == record.task_id) {
*existing = record;
} else {
self.jobs.push(record);
}
}
/// Opens the jobs pane (cursor at the top).
pub fn open_jobs_pane(&mut self) {
self.modal = ModalState::JobsPane { selected: 0 };
self.dirty = true;
}
/// Child session of the currently-selected job in the jobs pane, for drill-in.
pub fn selected_job_child(&self) -> Option<SessionId> {
if let ModalState::JobsPane { selected } = &self.modal {
self.jobs.get(*selected).map(|j| j.child_session.clone())
} else {
None
}
}
pub fn scroll_up(&mut self, n: u16) {
self.scroll_offset = self.scroll_offset.saturating_sub(n);
self.dirty = true;
}
pub fn scroll_down(&mut self, n: u16) {
self.scroll_offset = self.scroll_offset.saturating_add(n);
self.dirty = true;
}
pub fn handle_permission_reply(&mut self, reply: PermissionReply, engine: &EngineHandle) {
let request_id = if let ModalState::Permission { requests } = &self.modal {
requests.first().map(|r| r.id.clone())
} else {
None
};
if let Some(id) = request_id {
engine.permission_reply(&id, reply);
if let ModalState::Permission { requests } = &mut self.modal {
requests.retain(|r| r.id != id);
if requests.is_empty() {
self.modal = ModalState::None;
}
}
self.dirty = true;
}
}
pub fn open_session_picker(&mut self, sessions: Vec<Session>) {
self.modal = ModalState::SessionPicker {
sessions,
selected: 0,
};
self.dirty = true;
}
pub fn close_modal(&mut self) {
self.modal = ModalState::None;
self.dirty = true;
}
fn update_or_insert_part(&mut self, part: Part) {
let target_id = part.id.clone();
let Some(message_view) = self.messages.iter_mut().find(|m| m.id == part.message_id) else {
return;
};
let new_view = part_view(part);
if let Some(existing) = message_view
.parts
.iter_mut()
.find(|p| view_part_id(p) == target_id)
{
*existing = new_view;
} else {
message_view.parts.push(new_view);
}
}
fn apply_delta(
&mut self,
target_id: PartId,
message_id: harness_core::types::MessageId,
delta: String,
) {
let Some(message_view) = self.messages.iter_mut().find(|m| m.id == message_id) else {
return;
};
for part in &mut message_view.parts {
if view_part_id(part) == target_id {
match part {
PartView::Text {
text, cached_lines, ..
} => {
text.push_str(&delta);
*cached_lines = None;
}
PartView::Reasoning { text, .. } => {
text.push_str(&delta);
}
PartView::Tool { cached_lines, .. } => {
*cached_lines = None;
}
PartView::StepFinish { .. } => {}
}
return;
}
}
}
}
fn message_view(message: Message, mut parts: Vec<Part>) -> MessageView {
parts.sort_by_key(|p| p.idx);
MessageView {
id: message.id,
role: message.role,
parts: parts.into_iter().map(part_view).collect(),
}
}
fn part_view(part: Part) -> PartView {
match part.body {
PartBody::Text { text, .. } => PartView::Text {
id: part.id,
text,
cached_lines: None,
},
PartBody::Reasoning { text, .. } => PartView::Reasoning { id: part.id, text },
PartBody::Tool { name, state, .. } => PartView::Tool {
id: part.id,
name,
state: ToolStateView::from_tool_state(&state),
cached_lines: None,
},
PartBody::StepStart | PartBody::StepFinish { .. } => PartView::StepFinish { id: part.id },
PartBody::Subtask { description, .. } => PartView::Text {
id: part.id,
text: description,
cached_lines: None,
},
PartBody::Compaction { summary, .. } => PartView::Text {
id: part.id,
text: format!("_Compaction summary: {summary}_"),
cached_lines: None,
},
}
}
fn view_part_id(part: &PartView) -> PartId {
match part {
PartView::Text { id, .. }
| PartView::Reasoning { id, .. }
| PartView::Tool { id, .. }
| PartView::StepFinish { id } => id.clone(),
}
}
-41
View File
@@ -1,41 +0,0 @@
use std::io;
use std::panic;
use crossterm::cursor::Show;
use crossterm::execute;
use crossterm::terminal::{
disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
};
/// Restores the terminal when dropped or on panic.
pub struct TerminalGuard;
impl TerminalGuard {
/// Enables raw mode, enters the alternate screen, and installs a panic hook
/// that restores the terminal before printing panic info.
pub fn enter() -> io::Result<Self> {
enable_raw_mode()?;
let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen, Show)?;
let original_hook = panic::take_hook();
panic::set_hook(Box::new(move |info| {
let _ = restore();
original_hook(info);
}));
Ok(Self)
}
}
impl Drop for TerminalGuard {
fn drop(&mut self) {
let _ = restore();
}
}
fn restore() -> io::Result<()> {
disable_raw_mode()?;
let mut stdout = io::stdout();
execute!(stdout, LeaveAlternateScreen, Show)
}