Compare commits
11
Commits
v0.2.5
..
dfec176f43
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dfec176f43 | ||
|
|
13d914c8c0 | ||
|
|
164671a0c5 | ||
|
|
823110a518 | ||
|
|
c2ce0e3fe4 | ||
|
|
fd0b0a77dc | ||
|
|
7e428dfb39 | ||
|
|
6048a037ac | ||
|
|
8f0de9465d | ||
|
|
2166ef535b | ||
|
|
951b69837a |
No files matched your search
Generated
+315
-10
@@ -2,6 +2,20 @@
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "ahash"
|
||||
version = "0.8.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3019c0b8d883a8a17df3129e417ef463c087807d245e8881a31d583dee1c0519"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"getrandom 0.4.3",
|
||||
"once_cell",
|
||||
"serde",
|
||||
"version_check",
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aho-corasick"
|
||||
version = "1.1.5"
|
||||
@@ -166,7 +180,16 @@ version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0700ddab506f33b20a03b13996eccd309a48e5ff77d0d95926aa0210fb4e95f1"
|
||||
dependencies = [
|
||||
"bit-vec",
|
||||
"bit-vec 0.6.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bit-set"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
|
||||
dependencies = [
|
||||
"bit-vec 0.8.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -175,6 +198,12 @@ version = "0.6.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb"
|
||||
|
||||
[[package]]
|
||||
name = "bit-vec"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "1.3.2"
|
||||
@@ -205,6 +234,12 @@ dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "borrow-or-share"
|
||||
version = "0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dc0b364ead1874514c8c2855ab558056ebfeb775653e7ae45ff72f28f8f3166c"
|
||||
|
||||
[[package]]
|
||||
name = "bstr"
|
||||
version = "1.13.1"
|
||||
@@ -227,6 +262,12 @@ version = "1.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06"
|
||||
|
||||
[[package]]
|
||||
name = "bytecount"
|
||||
version = "0.6.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "175812e0be2bccb6abe50bb8d566126198344f707e304f45c648fd8f2cc0365e"
|
||||
|
||||
[[package]]
|
||||
name = "bytemuck"
|
||||
version = "1.25.2"
|
||||
@@ -542,6 +583,12 @@ dependencies = [
|
||||
"syn 3.0.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "data-encoding"
|
||||
version = "2.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
|
||||
|
||||
[[package]]
|
||||
name = "deltae"
|
||||
version = "0.3.2"
|
||||
@@ -629,6 +676,15 @@ version = "1.18.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34"
|
||||
|
||||
[[package]]
|
||||
name = "email_address"
|
||||
version = "0.2.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5ab6bbd053d3cdc62ba3de82aae11530a97bbd5b3a572fbdbcd0f0e545e3ff21"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.2"
|
||||
@@ -690,10 +746,21 @@ version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b95f7c0680e4142284cf8b22c14a476e87d61b004a3a0861872b32ef7ead40a2"
|
||||
dependencies = [
|
||||
"bit-set",
|
||||
"bit-set 0.5.3",
|
||||
"regex",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fancy-regex"
|
||||
version = "0.20.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0a2e16b9a584b602f1e0e5e22c30ca0906786088c27500653e432d086def8b53"
|
||||
dependencies = [
|
||||
"bit-set 0.8.0",
|
||||
"regex-automata",
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastrand"
|
||||
version = "2.5.0"
|
||||
@@ -729,6 +796,17 @@ version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"
|
||||
|
||||
[[package]]
|
||||
name = "fluent-uri"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bc74ac4d8359ae70623506d512209619e5cf8f347124910440dbc221714b328e"
|
||||
dependencies = [
|
||||
"borrow-or-share",
|
||||
"ref-cast",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fnv"
|
||||
version = "1.0.7"
|
||||
@@ -750,6 +828,16 @@ dependencies = [
|
||||
"percent-encoding",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fraction"
|
||||
version = "0.17.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e246562084dde8ebbcc943b261c406ce4f68e5032ec28029a251a47d6a295500"
|
||||
dependencies = [
|
||||
"num",
|
||||
"num-bigint",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fs_extra"
|
||||
version = "1.3.0"
|
||||
@@ -874,9 +962,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"js-sys",
|
||||
"libc",
|
||||
"r-efi 5.3.0",
|
||||
"wasip2",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1052,6 +1142,7 @@ dependencies = [
|
||||
"hx-mcp",
|
||||
"hx-tools",
|
||||
"hx-tui",
|
||||
"jsonschema",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"similar",
|
||||
@@ -1464,6 +1555,60 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jsonschema"
|
||||
version = "0.63.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b0802aebc749a4ef12e76aee083622b100249be0dc6d2103d84bbb2f7936a1ae"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytecount",
|
||||
"data-encoding",
|
||||
"email_address",
|
||||
"fancy-regex 0.20.2",
|
||||
"fraction",
|
||||
"getrandom 0.3.4",
|
||||
"itoa",
|
||||
"jsonschema-regex",
|
||||
"jsonschema-value",
|
||||
"num-cmp",
|
||||
"num-traits",
|
||||
"percent-encoding",
|
||||
"referencing",
|
||||
"regex",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"strum",
|
||||
"unicode-general-category",
|
||||
"uuid-simd",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jsonschema-regex"
|
||||
version = "0.63.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ba1527289dfcb1400df61b5c591218e8e30031376671f611faecb5b9a1ff4987"
|
||||
dependencies = [
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jsonschema-value"
|
||||
version = "0.63.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a95285ab129d630f01cf2f1345c28662116340fac1a35eb0795e5dbbf0ef990d"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytecount",
|
||||
"fraction",
|
||||
"getrandom 0.3.4",
|
||||
"memchr",
|
||||
"num-cmp",
|
||||
"num-traits",
|
||||
"serde_json",
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "kasuari"
|
||||
version = "0.4.12"
|
||||
@@ -1598,6 +1743,12 @@ dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "micromap"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a86d3146ed3995b5913c414f6664344b9617457320782e64f0bb44afd49d74"
|
||||
|
||||
[[package]]
|
||||
name = "minimal-lexical"
|
||||
version = "0.2.1"
|
||||
@@ -1645,6 +1796,45 @@ dependencies = [
|
||||
"minimal-lexical",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num"
|
||||
version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23"
|
||||
dependencies = [
|
||||
"num-bigint",
|
||||
"num-complex",
|
||||
"num-integer",
|
||||
"num-iter",
|
||||
"num-rational",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-bigint"
|
||||
version = "0.4.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
|
||||
dependencies = [
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-cmp"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "63335b2e2c34fae2fb0aa2cecfd9f0832a1e24b3b32ecec612c3426d46dc8aaa"
|
||||
|
||||
[[package]]
|
||||
name = "num-complex"
|
||||
version = "0.4.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-conv"
|
||||
version = "0.2.2"
|
||||
@@ -1662,6 +1852,36 @@ dependencies = [
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-integer"
|
||||
version = "0.1.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-iter"
|
||||
version = "0.1.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b"
|
||||
dependencies = [
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-rational"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
|
||||
dependencies = [
|
||||
"num-bigint",
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
@@ -1707,6 +1927,12 @@ dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "outref"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e"
|
||||
|
||||
[[package]]
|
||||
name = "palette"
|
||||
version = "0.7.7"
|
||||
@@ -2200,10 +2426,47 @@ dependencies = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex"
|
||||
version = "1.13.1"
|
||||
name = "ref-cast"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
|
||||
checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3"
|
||||
dependencies = [
|
||||
"ref-cast-impl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ref-cast-impl"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "referencing"
|
||||
version = "0.63.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "858eb92e3a3c1d120695a04d5c6e8861915ee4394b8f77c90adbf686d6ddbf6e"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"fluent-uri",
|
||||
"getrandom 0.3.4",
|
||||
"hashbrown 0.17.1",
|
||||
"itoa",
|
||||
"micromap",
|
||||
"parking_lot",
|
||||
"percent-encoding",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex"
|
||||
version = "1.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
@@ -2213,9 +2476,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "regex-automata"
|
||||
version = "0.4.18"
|
||||
version = "0.4.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
|
||||
checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
@@ -2224,9 +2487,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "regex-syntax"
|
||||
version = "0.8.11"
|
||||
version = "0.8.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
|
||||
checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
|
||||
|
||||
[[package]]
|
||||
name = "relative-path"
|
||||
@@ -2883,7 +3146,7 @@ dependencies = [
|
||||
"anyhow",
|
||||
"base64 0.22.1",
|
||||
"bitflags 2.13.2",
|
||||
"fancy-regex",
|
||||
"fancy-regex 0.11.0",
|
||||
"filedescriptor",
|
||||
"finl_unicode",
|
||||
"fixedbitset",
|
||||
@@ -3183,6 +3446,12 @@ version = "2.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-general-category"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.26"
|
||||
@@ -3260,12 +3529,28 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "uuid-simd"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "23b082222b4f6619906941c17eb2297fff4c2fb96cb60164170522942a200bd8"
|
||||
dependencies = [
|
||||
"outref",
|
||||
"vsimd",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||
|
||||
[[package]]
|
||||
name = "vsimd"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64"
|
||||
|
||||
[[package]]
|
||||
name = "vtparse"
|
||||
version = "0.6.2"
|
||||
@@ -3654,6 +3939,26 @@ dependencies = [
|
||||
"synstructure",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy"
|
||||
version = "0.8.66"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cba8a86aee14fc8cc6c208af60854b3d4ab7185a9a369a12c648faa2716ff42a"
|
||||
dependencies = [
|
||||
"zerocopy-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy-derive"
|
||||
version = "0.8.66"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerofrom"
|
||||
version = "0.1.8"
|
||||
|
||||
@@ -61,6 +61,7 @@ max_tokens = 16384
|
||||
# mouse = true # wheel scrolling; false keeps terminal text selection
|
||||
# codemode = false # add the `codemode` tool: JS scripts that call other tools in a sandbox
|
||||
# explore_model = "claude-haiku-4-5" # model for read-only `task` subagents; default: cheapest tier of the provider
|
||||
# subagent_parallel = 3 / subagent_max_turns = 40 / subagent_max_tokens / subagent_timeout_secs # subagent limits (see Subagents)
|
||||
# system_prompt = "..." # replaces built-in prompt; AGENTS.md still appended
|
||||
|
||||
## Sandbox: bash, LSP servers, lens and test runners run under bwrap (Linux) / sandbox-exec (macOS).
|
||||
@@ -116,7 +117,7 @@ Permissions: only writes ask. `write`/`edit` and unknown `bash` commands prompt;
|
||||
|
||||
Auto permissions (`--auto`, `permissions = "auto"`, `/auto [on|off|log]`): nothing prompts for the usual work, and dangerous calls are refused without asking. A refused call returns `blocked by auto mode: <reason>` to the model (also over a stored "always" rule); `/auto log` lists the last 20. Per call, in order: (1) rules block `rm -rf` of home/root/project root/outside the project, `sudo`, raw disk writes and filesystem creation, download piped to a shell, force push, push to main/master, sending `.env`/keys over the network, `npm|cargo publish`, `docker push`, `kubectl delete`, `terraform destroy`, SQL `DROP`, writes to `/etc`, `~/.ssh`, shell rc files, `.git/hooks`; (2) rules allow routine work inside the project (build/test/format, local git, `mkdir`/`mv`/`cp`/`rm` in the project, `write`/`edit` of project files); (3) everything else (unknown binaries, `curl`, `python -c`, `$(..)`, redirects, paths outside the project) goes to one cheap-model request (Haiku/Luna, ~300 input tokens, 20 s timeout) that answers ALLOW or BLOCK; if that fails or is unavailable the normal prompt appears. `--yolo` / `/yolo` still skip everything. With the `claude_cli` provider claude's tools appear on the event bus (`tool_call` / `tool_result`; hx names `bash{command}`, `write|edit|read{path}`, other tools under claude's name), so extensions can block them (a `block` denies the call with its reason) and NDJSON / `hx stats` see them. Reads are asked too (`--settings` `permissions.ask`; Bash too, claude auto-runs read-only commands like `ls` without asking otherwise). In `-p` there is no prompt and everything is allowed, unless `permissions = "deny"` (every unanswered call is denied) or `permissions = "extensions-only"` (allowed only while a live `tool_call` extension exists). The same rules apply to claude's tool calls, but no model judge runs (unclear ones ask). Pattern rules are not a sandbox: combine with `[sandbox]` for confinement.
|
||||
|
||||
Each `task` call asks for permission (`[a]` allows that kind for the project); `subagents = false` or `--no-subagents` removes the tool. The model can call `task(prompt, kind)` (or `task(prompts=[…], kind)` to fan out: one subagent per prompt, parallel, answers returned numbered; a lone task blocks the parent, so the tool description steers the model to batches) to run a subagent with a fresh context and get back only its final answer (cut at 8 KB), so big searches don't fill the main context. `explore` (default) is read-only (`read`, `lsp`, `bash`) on the provider's cheapest model (`explore_model` in config); `general` has the parent's tools and model, and the lens runs on its edits. Up to 3 run in parallel, none can start another, a parent abort stops them. Their sessions are written to `<session>.sub/`; `hx stats` shows `task` usage (calls, lone vs. batched turns) and lists them and the footer token counts include them. **Overview:** while any subagent exists, a list sits above the footer (bottom right: spinner/✓, id, kind, task, time, calls, tokens). `ctrl-g` focuses it (`↑↓`, `enter` opens, `esc` closes); the detail view shows that agent's live transcript. Typing there messages the agent: while it runs the text is delivered at its next turn end (like steering the main agent), after it finished it continues that agent's conversation. `ctrl-c` aborts that agent only; `ctrl-s` sends its last answer to the main chat as `[subagent N] …`. NDJSON/RPC carry no per-agent events yet.
|
||||
Each `task` call asks for permission (`[a]` allows that kind for the project); `subagents = false` or `--no-subagents` removes the tool. The model can call `task(prompt, kind)` (or `task(prompts=[…], kind)` to fan out: one subagent per prompt, parallel, answers returned numbered; a lone task blocks the parent, so the tool description steers the model to batches) to run a subagent with a fresh context and get back only its final answer (cut at 8 KB), so big searches don't fill the main context. `explore` (default) is read-only (`read`, `lsp`, `skill`, and `bash` restricted to read-only commands: writes, redirects and installs are refused, not asked) on the provider's cheapest model (`explore_model` in config); **custom agents:** `<hx home>/agents/<name>.md` and `<project>/.hx/agents/<name>.md` (project wins) add kinds to `task`: frontmatter `description`, `tools` (list or comma string; default: all of the parent's, unknown names ignored), `model` (default: parent's, cheapest for `readonly`), `readonly: true` (explore's tool set), `max_turns`; the body is the system prompt. Agents that can edit run with the lens, like `general`. The permission rule is `task:<name>`; **background:** `task(prompt|prompts, background=true)` returns the subagent ids at once and the parent keeps working; finished answers are handed to it at the end of its next turn, or it blocks for them with `task(wait=[ids])` (`[]` = all uncollected; needs no new approval). Answers longer than 8 KB are cut in the result and the full text is saved to `<session>.sub/NNN-<kind>.answer.md` (path in the result); `general` has the parent's tools and model, and the lens runs on its edits. Up to 3 run in parallel (`subagent_parallel`), none can start another, a parent abort stops them. Limits: `subagent_max_turns` (default 40), `subagent_max_tokens` (total tokens a subagent may spend) and `subagent_timeout_secs` (per run, counted once it has a slot) stop a child that goes over; it then fails with that reason, and the parent sees it as a failed `task`. Their sessions are written to `<session>.sub/`; `hx stats` shows `task` usage (calls, lone vs. batched turns) and lists them and the footer token counts include them. **Overview:** while any subagent exists, a list sits above the footer (bottom right: spinner/✓, id, kind, task, time, calls, tokens). `ctrl-g` focuses it (`↑↓`, `enter` opens, `esc` closes); the detail view shows that agent's live transcript. Typing there messages the agent: while it runs the text is delivered at its next turn end (like steering the main agent), after it finished it continues that agent's conversation. `ctrl-c` aborts that agent only; `ctrl-s` sends its last answer to the main chat as `[subagent N] …`. NDJSON/RPC carry no per-agent events yet.
|
||||
|
||||
A child starts with a cold prompt cache and costs tokens of its own: it saves *main-context* size, not total tokens.
|
||||
|
||||
@@ -230,6 +231,12 @@ the pane on quit. Outside herdr nothing happens.
|
||||
|
||||
## Machine interfaces
|
||||
|
||||
### Structured output (`hx -p "..." --schema schema.json`)
|
||||
|
||||
The final answer must be JSON matching the schema file. hx adds the schema to the system prompt, validates the answer (a ```json fence is stripped) and, on a mismatch, asks once more with the validation errors. Success prints only the JSON on stdout (`--mode json`: it is `output` in the `done` event); a second mismatch exits non-zero. Streamed text is not printed in text mode, since a rejected first answer must not reach stdout.
|
||||
|
||||
`--max-turns N` (or `max_turns` in config) caps the model calls per prompt (default 200).
|
||||
|
||||
### Event stream (`hx -p "..." --mode json`)
|
||||
|
||||
One JSON object per line on stdout. `type` is one of:
|
||||
@@ -256,6 +263,8 @@ offset defaulting to the end). One prompt at a time; other methods are rejected
|
||||
`abort` and `complete`). Sessions: `sessions {scope?: "project"|"all"}` (path, title, messages, model,
|
||||
branches, project, modified), `new`, `resume {path}`; `state` includes `title`. Example client: `examples/rpc_client.py`.
|
||||
|
||||
With `hx --mode rpc --ask`, a bash/write/edit call that would prompt in the TUI instead sends the client a request `{"id": N, "method": "permission", "params": {tool, detail, rule}}` and waits. Answer with `{"id": N, "result": {"decision": "once" | "always" | "deny"}}` (`always` on write/edit allows edits for the session). Any other reply, or an `abort`, denies. Without `--ask` everything is allowed, as before. Sample: `tests/rpc_ask_client.py`.
|
||||
|
||||
### Extensions
|
||||
|
||||
```toml
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"version": "0.2.4",
|
||||
"version": "0.2.7",
|
||||
"sha256": {
|
||||
"aarch64-apple-darwin": "41ac25d2a2503b6f14ef0a499f914687a515284f06a31830609ef2d8973583fb",
|
||||
"x86_64-unknown-linux-musl": "fcffc0f959fdbf50e99c09501166c661e695dff5c1feed0f39afc6145821f615"
|
||||
"aarch64-apple-darwin": "41e4c6c207ecce76e30517286b29d98685a13b89dcd2a5a02327af5af2947499",
|
||||
"x86_64-unknown-linux-musl": "f4a6306496c959c7b577b3b341ebf43e42c9a2349789ae1c2131d24c52beb41f"
|
||||
}
|
||||
}
|
||||
@@ -200,6 +200,8 @@ impl Provider for ClaudeCli {
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.kill_on_drop(true);
|
||||
#[cfg(unix)]
|
||||
cmd.process_group(0);
|
||||
let mut child = cmd.spawn().map_err(|e| {
|
||||
Error::Http(format!(
|
||||
"cannot start {:?}: {e} (is claude installed?)",
|
||||
@@ -208,17 +210,22 @@ impl Provider for ClaudeCli {
|
||||
})?;
|
||||
let out = child.stdout.take().expect("piped");
|
||||
let mut err = child.stderr.take().expect("piped");
|
||||
let group = KillGroup(child.id());
|
||||
let session = self.session.clone();
|
||||
let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<Result<StreamEvent>>();
|
||||
tokio::spawn(async move {
|
||||
let _child = child;
|
||||
let _group = group;
|
||||
let mut lines = BufReader::new(out).lines();
|
||||
let (mut text, mut think) = (String::new(), String::new());
|
||||
let mut done = false;
|
||||
let mut last: Option<Value> = None;
|
||||
let mut quota = Quota::default();
|
||||
let mut uses: std::collections::HashMap<String, (String, Value)> = Default::default();
|
||||
while let Ok(Some(l)) = lines.next_line().await {
|
||||
while let Some(Ok(Some(l))) = tokio::select! {
|
||||
l = lines.next_line() => Some(l),
|
||||
_ = tx.closed() => None,
|
||||
} {
|
||||
let Ok(v) = serde_json::from_str::<Value>(&l) else {
|
||||
continue;
|
||||
};
|
||||
@@ -325,7 +332,7 @@ impl Provider for ClaudeCli {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if !done {
|
||||
if !done && !tx.is_closed() {
|
||||
let mut e = String::new();
|
||||
let _ = tokio::io::AsyncReadExt::read_to_string(&mut err, &mut e).await;
|
||||
let _ = tx.send(Err(Error::Http(format!(
|
||||
@@ -341,6 +348,18 @@ impl Provider for ClaudeCli {
|
||||
}
|
||||
}
|
||||
|
||||
struct KillGroup(Option<u32>);
|
||||
impl Drop for KillGroup {
|
||||
fn drop(&mut self) {
|
||||
#[cfg(unix)]
|
||||
if let Some(pid) = self.0 {
|
||||
let _ = std::process::Command::new("kill")
|
||||
.args(["-KILL", &format!("-{pid}")])
|
||||
.status();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -419,4 +438,55 @@ mod tests {
|
||||
assert_eq!(usage.cache_read_tokens, 91_000);
|
||||
assert_eq!(usage.output_tokens, 7);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn dropping_the_stream_kills_claude_and_its_children() {
|
||||
let dir = std::env::temp_dir().join(format!("hx-kill-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let pidf = dir.join("pid");
|
||||
let f = pidf.clone();
|
||||
let p = ClaudeCli::new(vec![]).with_spawner(Arc::new(move |_| {
|
||||
let f = f.clone();
|
||||
Box::pin(async move {
|
||||
let mut c = tokio::process::Command::new("sh");
|
||||
c.args([
|
||||
"-c",
|
||||
&format!("sleep 60 & echo $! > {}; wait", f.display()),
|
||||
"sh",
|
||||
]);
|
||||
c
|
||||
})
|
||||
}));
|
||||
let req = Request {
|
||||
model: "m".into(),
|
||||
system: String::new(),
|
||||
messages: vec![Message::user("hi")],
|
||||
tools: vec![],
|
||||
max_tokens: 100,
|
||||
effort: crate::Effort::levels(crate::auth::Kind::Claude)[0],
|
||||
};
|
||||
let s = p.stream(req).await.unwrap();
|
||||
let pid = loop {
|
||||
if let Ok(x) = std::fs::read_to_string(&pidf)
|
||||
&& let Ok(n) = x.trim().parse::<u32>()
|
||||
{
|
||||
break n;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
|
||||
};
|
||||
drop(s);
|
||||
for _ in 0..100 {
|
||||
match std::fs::read_to_string(format!("/proc/{pid}/stat")) {
|
||||
Err(_) => return,
|
||||
Ok(x) if x.rsplit(") ").next().is_some_and(|r| r.starts_with('Z')) => return,
|
||||
_ => {}
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
|
||||
}
|
||||
panic!(
|
||||
"child {pid} survived: {:?}",
|
||||
std::fs::read_to_string(format!("/proc/{pid}/stat"))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,7 @@ similar = "3.2.0"
|
||||
tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "signal", "io-std", "io-util", "sync", "time"] }
|
||||
serde_json = "1.0.151"
|
||||
toml = "1.1.6"
|
||||
jsonschema = { version = "0.63", default-features = false }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -5,9 +5,14 @@
|
||||
# model = "claude-sonnet-5-5" # model for the chosen provider; "auto" = pick per prompt (see [auto])
|
||||
# claude_model = "claude-sonnet-5-5" # default: the account's latest Sonnet
|
||||
# codex_model = "gpt-5.6-sol" # default: Codex's top-listed model
|
||||
# subagents = false # do not offer the `task` tool (default true; every call asks first)
|
||||
# max_turns = 200 # model calls per prompt before the run stops (CLI: --max-turns)
|
||||
# subagents = false # do not offer the `task` tool (default true; every call asks first)
|
||||
# explore_model = "claude-haiku-4-5" # read-only `task` subagents; default: cheapest tier of the provider
|
||||
# remember_model = true # reuse the last model picked with /model or /provider
|
||||
# subagent_parallel = 3 # subagents running at once
|
||||
# subagent_max_turns = 40 # turn limit per subagent (an agent file's max_turns wins)
|
||||
# subagent_max_tokens = 500000 # stop a subagent that spends more tokens than this; default: no limit
|
||||
# subagent_timeout_secs = 600 # stop a subagent run after this long; default: no limit
|
||||
# remember_model = true # reuse the last model picked with /model or /provider
|
||||
# compact_at = 900000 # auto-compact at this many tokens; default: 90% of the context window
|
||||
# max_tokens = 16384
|
||||
# permissions = "ask" # ask | auto (refuse dangerous calls, run safe ones) | yolo (nothing asks)
|
||||
|
||||
+152
-11
@@ -13,6 +13,7 @@ use std::io::Write;
|
||||
|
||||
mod acp;
|
||||
mod rpc;
|
||||
mod schema;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Parser)]
|
||||
@@ -63,6 +64,22 @@ struct Cli {
|
||||
/// Output mode: text (default for -p), json (NDJSON events on stdout; needs -p), rpc (JSON-RPC on stdio).
|
||||
#[arg(long, value_enum, default_value_t = Mode::Text)]
|
||||
mode: Mode,
|
||||
#[arg(
|
||||
long,
|
||||
help = "rpc mode: send a `permission` request to the client for bash/write/edit calls"
|
||||
)]
|
||||
ask: bool,
|
||||
#[arg(
|
||||
long,
|
||||
help = "Model calls per prompt before the run stops (default 200)"
|
||||
)]
|
||||
max_turns: Option<u32>,
|
||||
#[arg(
|
||||
long,
|
||||
requires = "print",
|
||||
help = "JSON schema file: the final answer must match it (one retry); prints only the JSON"
|
||||
)]
|
||||
schema: Option<std::path::PathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, clap::ValueEnum)]
|
||||
@@ -154,8 +171,13 @@ struct Config {
|
||||
codex_model: Option<String>,
|
||||
compact_at: Option<usize>,
|
||||
max_tokens: Option<u32>,
|
||||
max_turns: Option<u32>,
|
||||
explore_model: Option<String>,
|
||||
subagents: Option<bool>,
|
||||
subagent_parallel: Option<usize>,
|
||||
subagent_max_turns: Option<u32>,
|
||||
subagent_max_tokens: Option<u64>,
|
||||
subagent_timeout_secs: Option<u64>,
|
||||
codemode: Option<bool>,
|
||||
mouse: Option<bool>,
|
||||
sessions_dir: Option<String>,
|
||||
@@ -218,8 +240,13 @@ impl Config {
|
||||
codex_model: o.codex_model.or(c.codex_model),
|
||||
compact_at: o.compact_at.or(c.compact_at),
|
||||
max_tokens: o.max_tokens.or(c.max_tokens),
|
||||
max_turns: o.max_turns.or(c.max_turns),
|
||||
explore_model: o.explore_model.or(c.explore_model),
|
||||
subagents: o.subagents.or(c.subagents),
|
||||
subagent_parallel: o.subagent_parallel.or(c.subagent_parallel),
|
||||
subagent_max_turns: o.subagent_max_turns.or(c.subagent_max_turns),
|
||||
subagent_max_tokens: o.subagent_max_tokens.or(c.subagent_max_tokens),
|
||||
subagent_timeout_secs: o.subagent_timeout_secs.or(c.subagent_timeout_secs),
|
||||
codemode: o.codemode.or(c.codemode),
|
||||
mouse: o.mouse.or(c.mouse),
|
||||
sessions_dir: o.sessions_dir.or(c.sessions_dir),
|
||||
@@ -734,7 +761,16 @@ async fn main() -> Result<()> {
|
||||
rows.extend(skill_rows);
|
||||
let mut specs = reg.specs();
|
||||
if !cli.no_subagents && cfg.subagents != Some(false) {
|
||||
specs.push(hx_core::subagent::spec());
|
||||
let (defs, _) = hx_core::subagent::load_agents(&hx_core::subagent::agent_dirs(
|
||||
&hx_core::context::hx_home(),
|
||||
&cwd,
|
||||
));
|
||||
let mut kinds = hx_core::subagent::builtin_kinds();
|
||||
for d in defs {
|
||||
kinds.retain(|k| k.0 != d.name);
|
||||
kinds.push((d.name, d.description));
|
||||
}
|
||||
specs.push(hx_core::subagent::spec_for(&kinds));
|
||||
}
|
||||
specs.sort_by_key(|t| {
|
||||
std::cmp::Reverse(serde_json::to_string(t).map_or(0, |s| s.len()))
|
||||
@@ -1037,13 +1073,19 @@ async fn main() -> Result<()> {
|
||||
if !cli.no_subagents && cfg.subagents != Some(false) {
|
||||
let mut general = agent.tools.clone();
|
||||
general.retain(|n| n != "ask_user" && n != "exit_plan");
|
||||
let base = general.clone();
|
||||
let mut explore = agent.tools.clone();
|
||||
explore.retain(|n| hx_core::subagent::EXPLORE_TOOLS.contains(&n));
|
||||
if let Some(b) = explore.get("bash") {
|
||||
explore.add(hx_core::subagent::ReadOnlyBash(b));
|
||||
}
|
||||
let role = |model: String, tools, base: &str| hx_core::subagent::Role {
|
||||
provider: provider(kind).expect("provider worked above"),
|
||||
model,
|
||||
tools,
|
||||
system: format!("{base}{tail}"),
|
||||
hooks: false,
|
||||
max_turns: None,
|
||||
};
|
||||
let cheap = cfg
|
||||
.explore_model
|
||||
@@ -1051,19 +1093,56 @@ async fn main() -> Result<()> {
|
||||
.or_else(|| hx_ai::models::cheap_for(kind, &models))
|
||||
.unwrap_or_else(|| agent.model().to_string());
|
||||
let mut task = hx_core::subagent::Task::new(
|
||||
role(cheap, explore, hx_core::subagent::EXPLORE_PROMPT),
|
||||
role(cheap.clone(), explore, hx_core::subagent::EXPLORE_PROMPT),
|
||||
role(
|
||||
agent.model().to_string(),
|
||||
general,
|
||||
hx_core::subagent::GENERAL_PROMPT,
|
||||
),
|
||||
path.with_extension("sub"),
|
||||
3,
|
||||
cfg.subagent_parallel.unwrap_or(3),
|
||||
);
|
||||
if let Some(n) = cfg.subagent_max_turns {
|
||||
task.max_turns = n;
|
||||
}
|
||||
task.max_tokens = cfg.subagent_max_tokens;
|
||||
task.timeout = cfg
|
||||
.subagent_timeout_secs
|
||||
.map(std::time::Duration::from_secs);
|
||||
if let Some(l) = &lens_ref {
|
||||
task.hooks.push(Arc::new(ArcHook(l.clone())));
|
||||
}
|
||||
let (defs, warns) = hx_core::subagent::load_agents(&hx_core::subagent::agent_dirs(
|
||||
&context::hx_home(),
|
||||
&cwd,
|
||||
));
|
||||
for w in warns {
|
||||
eprintln!("hx: agent {w}");
|
||||
}
|
||||
for d in defs {
|
||||
let tools = hx_core::subagent::agent_tools(&base, &d);
|
||||
let (model, default_prompt) = if d.readonly {
|
||||
(cheap.clone(), hx_core::subagent::EXPLORE_PROMPT)
|
||||
} else {
|
||||
(agent.model().to_string(), hx_core::subagent::GENERAL_PROMPT)
|
||||
};
|
||||
let mut r = role(
|
||||
d.model.clone().unwrap_or(model),
|
||||
tools,
|
||||
if d.system.is_empty() {
|
||||
default_prompt
|
||||
} else {
|
||||
&d.system
|
||||
},
|
||||
);
|
||||
r.hooks = hx_core::subagent::edits(&r.tools);
|
||||
r.max_turns = d.max_turns;
|
||||
task.add_kind(d.name, d.description, r);
|
||||
}
|
||||
agent.tools.add(task);
|
||||
agent
|
||||
.bus
|
||||
.add(hx_core::subagent::Notify(agent.cx.state.clone()));
|
||||
}
|
||||
if CLAUDE_CLI.get().is_none()
|
||||
&& let (Ok(p), Some(model)) = (
|
||||
@@ -1077,6 +1156,9 @@ async fn main() -> Result<()> {
|
||||
.judge
|
||||
.set(hx_core::danger::Judge { provider: p, model });
|
||||
}
|
||||
if let Some(n) = cli.max_turns.or(cfg.max_turns) {
|
||||
agent.set_max_turns(n);
|
||||
}
|
||||
if cfg.codemode.unwrap_or(false) {
|
||||
let cm = hx_tools::codemode::Codemode::new(&agent.tools);
|
||||
agent.tools.add(cm);
|
||||
@@ -1101,6 +1183,7 @@ async fn main() -> Result<()> {
|
||||
.auto_cfg(auto_cfg.clone())
|
||||
.remember_in(last_path.clone(), start.clone())
|
||||
.auto_on(want_auto),
|
||||
ask: cli.ask,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
@@ -1155,11 +1238,28 @@ async fn main() -> Result<()> {
|
||||
open_sessions,
|
||||
yolo: cli.yolo || cfg.permissions.as_deref() == Some("yolo"),
|
||||
auto: cli.auto || cfg.permissions.as_deref() == Some("auto"),
|
||||
mcp: mcp
|
||||
.servers
|
||||
.iter()
|
||||
.map(|(n, s)| (n.clone(), s.st().error.is_none()))
|
||||
.collect(),
|
||||
mcp: {
|
||||
let mcp = mcp.clone();
|
||||
Box::new(move || {
|
||||
mcp.servers
|
||||
.iter()
|
||||
.map(|(n, s)| {
|
||||
let st = s.st();
|
||||
hx_tui::side::McpRow {
|
||||
name: n.clone(),
|
||||
state: match (&st.error, st.pending) {
|
||||
(Some(_), _) => hx_tui::side::McpState::Failed,
|
||||
(None, true) => hx_tui::side::McpState::Pending,
|
||||
(None, false) => hx_tui::side::McpState::Ok,
|
||||
},
|
||||
tools: st.tools.len(),
|
||||
prompts: st.prompts.len(),
|
||||
error: st.error.clone(),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
},
|
||||
mouse: cfg.mouse.unwrap_or(true)
|
||||
&& std::env::var_os("HX_MOUSE").is_none_or(|v| v != "0"),
|
||||
commands: {
|
||||
@@ -1244,9 +1344,17 @@ async fn main() -> Result<()> {
|
||||
mgr.shutdown().await;
|
||||
return Ok(());
|
||||
};
|
||||
let schema = cli
|
||||
.schema
|
||||
.as_deref()
|
||||
.map(schema::Schema::load)
|
||||
.transpose()?;
|
||||
if let Some(s) = &schema {
|
||||
agent.append_system(&format!("{}{}", schema::INSTRUCTION, s.text));
|
||||
}
|
||||
if cli.mode == Mode::Json {
|
||||
agent.bus.add(rpc::Ndjson);
|
||||
} else {
|
||||
} else if schema.is_none() {
|
||||
agent.bus.add(Printer);
|
||||
}
|
||||
tokio::spawn(async move {
|
||||
@@ -1254,10 +1362,40 @@ async fn main() -> Result<()> {
|
||||
abort.abort();
|
||||
}
|
||||
});
|
||||
let r = agent.run(prompt).await;
|
||||
let mut r = agent.run(prompt).await;
|
||||
let mut output = None;
|
||||
let mut schema_err = None;
|
||||
if let Some(s) = &schema {
|
||||
for attempt in 0..2 {
|
||||
let Ok(m) = &r else { break };
|
||||
match s.check(&m.text()) {
|
||||
Ok(v) => {
|
||||
schema_err = None;
|
||||
output = Some(v);
|
||||
break;
|
||||
}
|
||||
Err(p) => {
|
||||
schema_err = Some(p.clone());
|
||||
if attempt == 0 {
|
||||
r = agent.run(schema::retry_prompt(&p)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(v) = &output
|
||||
&& cli.mode != Mode::Json
|
||||
{
|
||||
println!("{v}");
|
||||
}
|
||||
}
|
||||
let error = r
|
||||
.as_ref()
|
||||
.err()
|
||||
.map(|e| e.to_string())
|
||||
.or(schema_err.map(|e| format!("answer does not match the schema: {e}")));
|
||||
if cli.mode == Mode::Json {
|
||||
rpc::emit(
|
||||
&serde_json::json!({"type": "done", "error": r.as_ref().err().map(|e| e.to_string()),
|
||||
&serde_json::json!({"type": "done", "error": error, "output": output,
|
||||
"usage": agent.usage(), "session": path}),
|
||||
);
|
||||
}
|
||||
@@ -1282,6 +1420,9 @@ async fn main() -> Result<()> {
|
||||
hx_core::herdr::release().await;
|
||||
mgr.shutdown().await;
|
||||
r?;
|
||||
if let Some(e) = error {
|
||||
anyhow::bail!(e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
use anyhow::Result;
|
||||
use hx_core::agent::{AbortHandle, Agent};
|
||||
use hx_core::hook::{Event, Hook, HookAction};
|
||||
use hx_core::permit::Decision;
|
||||
use serde_json::{Value, json};
|
||||
use std::io::Write;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering::SeqCst};
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
@@ -38,11 +40,56 @@ fn reply(id: &Value, r: Result<Value, String>) {
|
||||
});
|
||||
}
|
||||
|
||||
type Pending =
|
||||
Arc<std::sync::Mutex<std::collections::HashMap<u64, tokio::sync::oneshot::Sender<Value>>>>;
|
||||
|
||||
fn install_permit(agent: &Agent, pending: &Pending) {
|
||||
let state = &agent.cx.state;
|
||||
let abort = state.abort.get().cloned();
|
||||
let next = Arc::new(AtomicU64::new(1));
|
||||
let pending = pending.clone();
|
||||
let _ = state.permit.set(Arc::new(move |r| {
|
||||
let (pending, abort) = (pending.clone(), abort.clone());
|
||||
let n = next.fetch_add(1, SeqCst);
|
||||
Box::pin(async move {
|
||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||
pending
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.insert(n, tx);
|
||||
emit(&json!({"jsonrpc": "2.0", "id": n, "method": "permission",
|
||||
"params": {"tool": r.tool, "detail": r.detail, "rule": r.rule}}));
|
||||
let mut abort = abort;
|
||||
let reply = tokio::select! {
|
||||
v = rx => v.ok(),
|
||||
_ = async {
|
||||
match abort.as_mut() {
|
||||
Some(a) => { let _ = a.wait_for(|x| *x).await; }
|
||||
None => std::future::pending::<()>().await,
|
||||
}
|
||||
} => None,
|
||||
};
|
||||
pending.lock().unwrap_or_else(|e| e.into_inner()).remove(&n);
|
||||
let edit = matches!(r.tool.as_str(), "write" | "edit");
|
||||
match reply
|
||||
.as_ref()
|
||||
.and_then(|v| v["result"]["decision"].as_str())
|
||||
{
|
||||
Some("once") => Decision::Once,
|
||||
Some("always") if edit => Decision::Edits,
|
||||
Some("always") => Decision::Always,
|
||||
_ => Decision::Deny,
|
||||
}
|
||||
})
|
||||
}));
|
||||
}
|
||||
|
||||
pub struct Ctx {
|
||||
pub specs: Vec<hx_core::command::CmdSpec>,
|
||||
pub files: Vec<String>,
|
||||
pub session_dir: std::path::PathBuf,
|
||||
pub switcher: hx_core::switch::Switcher,
|
||||
pub ask: bool,
|
||||
}
|
||||
|
||||
pub async fn serve(mut agent: Agent, abort: AbortHandle, cx: Ctx) -> Result<()> {
|
||||
@@ -51,7 +98,12 @@ pub async fn serve(mut agent: Agent, abort: AbortHandle, cx: Ctx) -> Result<()>
|
||||
files,
|
||||
session_dir,
|
||||
mut switcher,
|
||||
ask,
|
||||
} = cx;
|
||||
let pending = Pending::default();
|
||||
if ask {
|
||||
install_permit(&agent, &pending);
|
||||
}
|
||||
agent.bus.add(Notify);
|
||||
let agent = Arc::new(Mutex::new(agent));
|
||||
let busy = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
@@ -66,6 +118,15 @@ pub async fn serve(mut agent: Agent, abort: AbortHandle, cx: Ctx) -> Result<()>
|
||||
}
|
||||
};
|
||||
let id = m["id"].clone();
|
||||
if m.get("method").is_none() && id.is_u64() {
|
||||
let tx = id
|
||||
.as_u64()
|
||||
.and_then(|n| pending.lock().unwrap_or_else(|e| e.into_inner()).remove(&n));
|
||||
if let Some(tx) = tx {
|
||||
let _ = tx.send(m);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let p = &m["params"];
|
||||
let method = m["method"].as_str().unwrap_or_default();
|
||||
if method == "complete" {
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
use serde_json::Value;
|
||||
|
||||
pub const INSTRUCTION: &str = "\n\nYour final answer must be a single JSON value that matches this JSON schema. Reply with the JSON only, no prose and no code fence:\n";
|
||||
|
||||
pub struct Schema {
|
||||
validator: jsonschema::Validator,
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
impl Schema {
|
||||
pub fn load(path: &std::path::Path) -> anyhow::Result<Self> {
|
||||
let text = std::fs::read_to_string(path)
|
||||
.map_err(|e| anyhow::anyhow!("--schema {}: {e}", path.display()))?;
|
||||
let v: Value = serde_json::from_str(&text)
|
||||
.map_err(|e| anyhow::anyhow!("--schema {}: {e}", path.display()))?;
|
||||
let validator = jsonschema::validator_for(&v)
|
||||
.map_err(|e| anyhow::anyhow!("--schema {}: {e}", path.display()))?;
|
||||
Ok(Self { validator, text })
|
||||
}
|
||||
|
||||
pub fn check(&self, answer: &str) -> Result<Value, String> {
|
||||
let v = extract(answer).ok_or("the answer is not valid JSON")?;
|
||||
let errs: Vec<String> = self
|
||||
.validator
|
||||
.iter_errors(&v)
|
||||
.map(|e| format!("{} (at {})", e, e.instance_path()))
|
||||
.collect();
|
||||
if errs.is_empty() {
|
||||
Ok(v)
|
||||
} else {
|
||||
Err(errs.join("\n"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn retry_prompt(problem: &str) -> String {
|
||||
format!(
|
||||
"Your last answer does not match the schema:\n{problem}\nReply again with only the corrected JSON."
|
||||
)
|
||||
}
|
||||
|
||||
fn extract(s: &str) -> Option<Value> {
|
||||
let s = s.trim();
|
||||
let body = match s.strip_prefix("```") {
|
||||
Some(rest) => {
|
||||
let rest = rest.split_once('\n').map_or(rest, |(_, b)| b);
|
||||
rest.rsplit_once("```").map_or(rest, |(b, _)| b)
|
||||
}
|
||||
None => s,
|
||||
};
|
||||
serde_json::from_str(body.trim()).ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn schema() -> Schema {
|
||||
let v: Value = serde_json::json!({
|
||||
"type": "object",
|
||||
"required": ["name"],
|
||||
"properties": {"name": {"type": "string"}}
|
||||
});
|
||||
Schema {
|
||||
validator: jsonschema::validator_for(&v).unwrap(),
|
||||
text: v.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_plain_and_fenced() {
|
||||
let s = schema();
|
||||
assert!(s.check(r#"{"name":"a"}"#).is_ok());
|
||||
assert!(s.check("```json\n{\"name\":\"a\"}\n```").is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_wrong_shape_and_prose() {
|
||||
let s = schema();
|
||||
assert!(s.check(r#"{"name":1}"#).unwrap_err().contains("name"));
|
||||
assert!(s.check("here you go").is_err());
|
||||
}
|
||||
}
|
||||
@@ -421,6 +421,25 @@ impl Agent {
|
||||
*self.abort.borrow()
|
||||
}
|
||||
|
||||
fn abort_calls(
|
||||
&mut self,
|
||||
calls: &[(String, String, serde_json::Value)],
|
||||
) -> Result<Message, Error> {
|
||||
let content = calls
|
||||
.iter()
|
||||
.map(|(id, ..)| ContentBlock::ToolResult {
|
||||
tool_use_id: id.clone(),
|
||||
content: "aborted by user".into(),
|
||||
is_error: true,
|
||||
})
|
||||
.collect();
|
||||
self.push(Message {
|
||||
role: Role::User,
|
||||
content,
|
||||
})?;
|
||||
Err(Error::Aborted)
|
||||
}
|
||||
|
||||
pub async fn run(&mut self, prompt: impl Into<String>) -> Result<Message, Error> {
|
||||
let r = self.run_inner(prompt.into()).await;
|
||||
self.emit(Event::RunEnd {
|
||||
@@ -529,6 +548,9 @@ impl Agent {
|
||||
continue;
|
||||
}
|
||||
|
||||
if self.aborted() {
|
||||
return self.abort_calls(&calls);
|
||||
}
|
||||
let mut results: Vec<Option<ContentBlock>> = vec![None; calls.len()];
|
||||
let mut runnable = vec![];
|
||||
for (i, (id, name, args)) in calls.iter().enumerate() {
|
||||
@@ -577,10 +599,12 @@ impl Agent {
|
||||
&self.cx,
|
||||
);
|
||||
tokio::pin!(round);
|
||||
let mut ab = self.abort.clone();
|
||||
loop {
|
||||
tokio::select! {
|
||||
outs = &mut round => break outs,
|
||||
outs = &mut round => break Some(outs),
|
||||
Some(line) = nrx.recv() => { self.emit(Event::Info(line)).await; }
|
||||
_ = async { ab.wait_for(|a| *a).await.is_ok() } => break None,
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -590,6 +614,9 @@ impl Agent {
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.take();
|
||||
let Some(outs) = outs else {
|
||||
return self.abort_calls(&calls);
|
||||
};
|
||||
while let Ok(line) = nrx.try_recv() {
|
||||
self.emit(Event::Info(line)).await;
|
||||
}
|
||||
@@ -1093,6 +1120,73 @@ mod tests {
|
||||
assert!(matches!(a.run("again").await, Err(Error::Aborted)));
|
||||
}
|
||||
|
||||
struct Slow;
|
||||
#[async_trait]
|
||||
impl Tool for Slow {
|
||||
fn spec(&self) -> ToolSpec {
|
||||
ToolSpec {
|
||||
name: "slow".into(),
|
||||
description: "sleeps".into(),
|
||||
input_schema: json!({"type":"object","properties":{}}),
|
||||
}
|
||||
}
|
||||
async fn call(&self, _: Value, _: &crate::tool::ToolCtx) -> ToolResult {
|
||||
tokio::time::sleep(std::time::Duration::from_secs(30)).await;
|
||||
ToolResult::ok("done")
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn abort_during_tool_round_stops_it_and_answers_the_calls() {
|
||||
let p = Arc::new(Script(
|
||||
Mutex::new(vec![
|
||||
asst(vec![
|
||||
ContentBlock::ToolUse {
|
||||
id: "1".into(),
|
||||
name: "slow".into(),
|
||||
input: json!({}),
|
||||
},
|
||||
ContentBlock::ToolUse {
|
||||
id: "2".into(),
|
||||
name: "slow".into(),
|
||||
input: json!({}),
|
||||
},
|
||||
]),
|
||||
asst(vec![ContentBlock::Text { text: "ok".into() }]),
|
||||
]),
|
||||
Mutex::new(vec![]),
|
||||
));
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut tools = Registry::default();
|
||||
tools.add(Slow);
|
||||
let cx = ToolCtx {
|
||||
cwd: dir.path().into(),
|
||||
state: Default::default(),
|
||||
};
|
||||
let (mut a, h) = Agent::new(
|
||||
p.clone(),
|
||||
tools,
|
||||
Session::open(dir.path().join("s.jsonl")).unwrap(),
|
||||
cx,
|
||||
);
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
h.abort();
|
||||
});
|
||||
let t = std::time::Instant::now();
|
||||
assert!(matches!(a.run("go").await, Err(Error::Aborted)));
|
||||
assert!(t.elapsed() < std::time::Duration::from_secs(5));
|
||||
assert!(a.run("again").await.is_ok());
|
||||
let reqs = p.1.lock().unwrap();
|
||||
let last = &reqs[1].messages;
|
||||
let results = last
|
||||
.iter()
|
||||
.flat_map(|m| &m.content)
|
||||
.filter(|b| matches!(b, ContentBlock::ToolResult { is_error: true, .. }))
|
||||
.count();
|
||||
assert_eq!(results, 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mask_boundary_waits_for_big_context_and_is_recorded() {
|
||||
let big = "z".repeat(8000);
|
||||
|
||||
@@ -200,6 +200,19 @@ pub async fn serve(path: &Path, cx: ToolCtx, bus: Bus, mode: Unanswered) -> std:
|
||||
}
|
||||
}
|
||||
|
||||
async fn choose_or_abort(
|
||||
cx: &ToolCtx,
|
||||
q: crate::Question,
|
||||
) -> Result<Option<Vec<String>>, &'static str> {
|
||||
match cx.state.abort.get().cloned() {
|
||||
Some(mut rx) => tokio::select! {
|
||||
r = cx.state.choose(q) => r,
|
||||
_ = async { rx.wait_for(|a| *a).await.is_ok() } => Ok(None),
|
||||
},
|
||||
None => cx.state.choose(q).await,
|
||||
}
|
||||
}
|
||||
|
||||
async fn exit_plan(cx: &ToolCtx, plan: &str) -> Result<(), String> {
|
||||
let q = crate::Question {
|
||||
text: "Implement this plan?".into(),
|
||||
@@ -214,7 +227,7 @@ async fn exit_plan(cx: &ToolCtx, plan: &str) -> Result<(), String> {
|
||||
other: true,
|
||||
plan: Some(plan.into()),
|
||||
};
|
||||
match cx.state.choose(q).await {
|
||||
match choose_or_abort(cx, q).await {
|
||||
Ok(Some(v)) if v.first().is_some_and(|s| s == "Implement") => {
|
||||
cx.state
|
||||
.allow
|
||||
@@ -239,17 +252,18 @@ async fn ask(cx: &ToolCtx, input: &Value) -> Option<Value> {
|
||||
let s = |k| o[k].as_str().unwrap_or_default().to_string();
|
||||
(s("label"), s("description"))
|
||||
});
|
||||
let r = cx
|
||||
.state
|
||||
.choose(crate::Question {
|
||||
let r = choose_or_abort(
|
||||
cx,
|
||||
crate::Question {
|
||||
text: text.into(),
|
||||
options: options.collect(),
|
||||
multi: q["multiSelect"].as_bool().unwrap_or(false),
|
||||
other: true,
|
||||
plan: None,
|
||||
})
|
||||
.await
|
||||
.ok()??;
|
||||
},
|
||||
)
|
||||
.await
|
||||
.ok()??;
|
||||
answers.insert(text.into(), r.join(", ").into());
|
||||
}
|
||||
let mut out = input.clone();
|
||||
|
||||
@@ -151,7 +151,7 @@ pub(crate) fn split_cmd(cmd: &str) -> Option<Vec<Seg>> {
|
||||
Some(segs)
|
||||
}
|
||||
|
||||
fn readonly_cmd(cmd: &str) -> bool {
|
||||
pub fn readonly_cmd(cmd: &str) -> bool {
|
||||
split_cmd(cmd).is_some_and(|s| s.iter().all(readonly_seg))
|
||||
}
|
||||
|
||||
@@ -181,7 +181,10 @@ pub fn needs_permit(tool: &str, args: &serde_json::Value) -> bool {
|
||||
match tool {
|
||||
"bash" => !readonly_cmd(a("command").trim()),
|
||||
"read" => secret(a("path")),
|
||||
"web_fetch" | "task" => true,
|
||||
"task" => {
|
||||
!(args["wait"].is_array() && args["prompt"].is_null() && args["prompts"].is_null())
|
||||
}
|
||||
"web_fetch" => true,
|
||||
_ => gated(tool),
|
||||
}
|
||||
}
|
||||
|
||||
+683
-41
@@ -16,14 +16,17 @@ pub struct Role {
|
||||
pub model: String,
|
||||
pub tools: Registry,
|
||||
pub system: String,
|
||||
pub hooks: bool,
|
||||
pub max_turns: Option<u32>,
|
||||
}
|
||||
|
||||
pub struct Task {
|
||||
pub explore: Role,
|
||||
pub general: Role,
|
||||
roles: Vec<(String, String, Role)>,
|
||||
pub dir: PathBuf,
|
||||
pub hooks: Vec<Arc<dyn Hook>>,
|
||||
pub max_turns: u32,
|
||||
pub max_tokens: Option<u64>,
|
||||
pub timeout: Option<std::time::Duration>,
|
||||
sem: Arc<Semaphore>,
|
||||
n: AtomicUsize,
|
||||
}
|
||||
@@ -38,7 +41,7 @@ pub enum Status {
|
||||
|
||||
pub struct Shared {
|
||||
pub id: usize,
|
||||
pub kind: &'static str,
|
||||
pub kind: String,
|
||||
pub model: String,
|
||||
pub prompt: String,
|
||||
pub started: Instant,
|
||||
@@ -48,9 +51,24 @@ pub struct Shared {
|
||||
pub usage: Mutex<Usage>,
|
||||
inbox: Mutex<Vec<String>>,
|
||||
rolled: Mutex<Usage>,
|
||||
stop: Mutex<Option<String>>,
|
||||
timeout: Option<std::time::Duration>,
|
||||
runs: AtomicUsize,
|
||||
background: bool,
|
||||
result: Mutex<Option<(String, bool)>>,
|
||||
collected: std::sync::atomic::AtomicBool,
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
fn stop_with(&self, why: String) {
|
||||
let mut s = self.stop.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if s.is_none() {
|
||||
*s = Some(why);
|
||||
}
|
||||
}
|
||||
fn stopped(&self) -> Option<String> {
|
||||
self.stop.lock().unwrap_or_else(|e| e.into_inner()).clone()
|
||||
}
|
||||
pub fn status(&self) -> Status {
|
||||
self.status
|
||||
.lock()
|
||||
@@ -72,6 +90,7 @@ pub struct Sub {
|
||||
abort: crate::agent::AbortHandle,
|
||||
state: Arc<crate::State>,
|
||||
sem: Arc<Semaphore>,
|
||||
dir: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -140,7 +159,15 @@ fn diff(a: &Usage, b: &Usage) -> Usage {
|
||||
}
|
||||
}
|
||||
|
||||
struct Live(Arc<Shared>, Option<mpsc::UnboundedSender<(usize, Event)>>);
|
||||
struct Live(
|
||||
Arc<Shared>,
|
||||
Option<mpsc::UnboundedSender<(usize, Event)>>,
|
||||
Option<(u64, crate::agent::AbortHandle)>,
|
||||
);
|
||||
|
||||
fn total(u: &Usage) -> u64 {
|
||||
u.input_tokens + u.cache_read_tokens + u.cache_write_tokens + u.output_tokens
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Hook for Live {
|
||||
@@ -150,11 +177,21 @@ impl Hook for Live {
|
||||
self.0.calls.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
Event::Stream(StreamEvent::Done { usage, .. }) => {
|
||||
self.0
|
||||
.usage
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.add(usage);
|
||||
let spent = {
|
||||
let mut u = self.0.usage.lock().unwrap_or_else(|e| e.into_inner());
|
||||
u.add(usage);
|
||||
total(&u)
|
||||
};
|
||||
if let Some((max, h)) = &self.2
|
||||
&& spent > *max
|
||||
{
|
||||
self.0.stop_with(format!(
|
||||
"token budget exceeded ({}k of {}k)",
|
||||
spent / 1000,
|
||||
max / 1000
|
||||
));
|
||||
h.abort();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -189,14 +226,29 @@ impl Sub {
|
||||
}
|
||||
*st = Status::Running;
|
||||
*self.sh.ended.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||
*self.sh.stop.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||
}
|
||||
let me = self.clone();
|
||||
tokio::spawn(async move {
|
||||
let _permit = me.sem.acquire().await;
|
||||
me.arm();
|
||||
let _ = me.drive(text).await;
|
||||
});
|
||||
}
|
||||
|
||||
fn arm(&self) {
|
||||
let Some(t) = self.sh.timeout else { return };
|
||||
let (sh, abort) = (self.sh.clone(), self.abort.clone());
|
||||
let run = sh.runs.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(t).await;
|
||||
if sh.status() == Status::Running && sh.runs.load(Ordering::Relaxed) == run {
|
||||
sh.stop_with(format!("timeout after {}s", t.as_secs()));
|
||||
abort.abort();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async fn drive(&self, mut p: String) -> Result<Message, Error> {
|
||||
let mut a = self.agent.lock().await;
|
||||
loop {
|
||||
@@ -222,7 +274,10 @@ impl Sub {
|
||||
}
|
||||
*st = match &r {
|
||||
Ok(_) => Status::Done,
|
||||
Err(Error::Aborted) => Status::Aborted,
|
||||
Err(Error::Aborted) => match self.sh.stopped() {
|
||||
Some(why) => Status::Failed(why),
|
||||
None => Status::Aborted,
|
||||
},
|
||||
Err(e) => Status::Failed(e.to_string()),
|
||||
};
|
||||
*self.sh.ended.lock().unwrap_or_else(|e| e.into_inner()) = Some(Instant::now());
|
||||
@@ -231,43 +286,277 @@ impl Sub {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ReadOnlyBash(pub Arc<dyn Tool>);
|
||||
|
||||
#[async_trait]
|
||||
impl Tool for ReadOnlyBash {
|
||||
fn spec(&self) -> ToolSpec {
|
||||
self.0.spec()
|
||||
}
|
||||
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
|
||||
let cmd = a["command"].as_str().unwrap_or_default().trim();
|
||||
if !crate::permit::readonly_cmd(cmd) {
|
||||
return ToolResult::err(
|
||||
"read-only subagent: only read-only commands (rg, fd, ls, cat, git log/diff/show, ...; no redirects or `$()`) are allowed",
|
||||
);
|
||||
}
|
||||
self.0.call(a, cx).await
|
||||
}
|
||||
}
|
||||
|
||||
pub const EXPLORE_TOOLS: &[&str] = &["read", "lsp", "bash", "skill"];
|
||||
pub const EXPLORE_PROMPT: &str = "You are a research subagent of hx. Answer the task by reading code; do not modify anything (no writes, no redirects, no installs). Your final message is the only thing the caller sees: give the answer with file:line references, short, no preamble.";
|
||||
pub const GENERAL_PROMPT: &str = "You are a subagent of hx working in the user's repository. Do the task fully with the tools; read files before editing them, and run the narrowest relevant check (build, test, lint) after editing. Your final message is the only thing the caller sees: say what you changed or found, short, with file paths.";
|
||||
const MAX_RESULT: usize = 8_000;
|
||||
|
||||
impl Task {
|
||||
pub fn new(explore: Role, general: Role, dir: PathBuf, parallel: usize) -> Self {
|
||||
pub fn new(mut explore: Role, mut general: Role, dir: PathBuf, parallel: usize) -> Self {
|
||||
explore.hooks = false;
|
||||
general.hooks = true;
|
||||
Self {
|
||||
explore,
|
||||
general,
|
||||
roles: vec![
|
||||
("explore".into(), BUILTIN[0].1.into(), explore),
|
||||
("general".into(), BUILTIN[1].1.into(), general),
|
||||
],
|
||||
dir: dir.clone(),
|
||||
hooks: vec![],
|
||||
max_turns: 40,
|
||||
max_tokens: None,
|
||||
timeout: None,
|
||||
sem: Arc::new(Semaphore::new(parallel.max(1))),
|
||||
n: AtomicUsize::new(std::fs::read_dir(&dir).map_or(0, |d| d.count())),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add_kind(&mut self, name: String, desc: String, role: Role) {
|
||||
match self.roles.iter_mut().find(|r| r.0 == name) {
|
||||
Some(r) => *r = (name, desc, role),
|
||||
None => self.roles.push((name, desc, role)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn kinds(&self) -> Vec<(String, String)> {
|
||||
self.roles
|
||||
.iter()
|
||||
.map(|r| (r.0.clone(), r.1.clone()))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn spec() -> ToolSpec {
|
||||
const BUILTIN: [(&str, &str); 2] = [
|
||||
("explore", "read-only research on a cheaper model (default)"),
|
||||
("general", "same tools as you, may edit"),
|
||||
];
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Default)]
|
||||
pub struct AgentDef {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub tools: Vec<String>,
|
||||
pub model: Option<String>,
|
||||
pub readonly: bool,
|
||||
pub max_turns: Option<u32>,
|
||||
pub system: String,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, Default)]
|
||||
#[serde(untagged)]
|
||||
enum Names {
|
||||
#[default]
|
||||
None,
|
||||
One(String),
|
||||
Many(Vec<String>),
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, Default)]
|
||||
struct AgentFront {
|
||||
name: Option<String>,
|
||||
description: Option<String>,
|
||||
#[serde(default)]
|
||||
tools: Names,
|
||||
model: Option<String>,
|
||||
readonly: Option<bool>,
|
||||
max_turns: Option<u32>,
|
||||
}
|
||||
|
||||
pub fn agent_dirs(home: &std::path::Path, cwd: &std::path::Path) -> Vec<PathBuf> {
|
||||
vec![home.join("agents"), cwd.join(".hx/agents")]
|
||||
}
|
||||
|
||||
pub fn parse_agent(path: &std::path::Path, s: &str) -> Result<AgentDef, String> {
|
||||
let (fm, body) = s
|
||||
.strip_prefix("---")
|
||||
.and_then(|r| r.split_once("\n---"))
|
||||
.map_or(("", s), |(f, b)| {
|
||||
(f, b.split_once('\n').map_or("", |x| x.1))
|
||||
});
|
||||
let f: AgentFront = if fm.trim().is_empty() {
|
||||
AgentFront::default()
|
||||
} else {
|
||||
serde_norway::from_str(fm).map_err(|e| e.to_string())?
|
||||
};
|
||||
let name = f.name.unwrap_or_else(|| {
|
||||
path.file_stem()
|
||||
.unwrap_or_default()
|
||||
.to_string_lossy()
|
||||
.into()
|
||||
});
|
||||
if name.is_empty()
|
||||
|| !name
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
|
||||
{
|
||||
return Err(format!(
|
||||
"bad agent name `{name}` (use letters, digits, - _)"
|
||||
));
|
||||
}
|
||||
let tools = match f.tools {
|
||||
Names::None => vec![],
|
||||
Names::One(s) => s.split(',').map(|t| t.trim().to_string()).collect(),
|
||||
Names::Many(v) => v,
|
||||
};
|
||||
Ok(AgentDef {
|
||||
name,
|
||||
description: f
|
||||
.description
|
||||
.unwrap_or_default()
|
||||
.split_whitespace()
|
||||
.collect::<Vec<_>>()
|
||||
.join(" "),
|
||||
tools: tools.into_iter().filter(|t| !t.is_empty()).collect(),
|
||||
model: f.model.filter(|m| !m.trim().is_empty()),
|
||||
readonly: f.readonly.unwrap_or(false),
|
||||
max_turns: f.max_turns,
|
||||
system: body.trim().to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn load_agents(dirs: &[PathBuf]) -> (Vec<AgentDef>, Vec<String>) {
|
||||
let mut out: Vec<AgentDef> = vec![];
|
||||
let mut warn = vec![];
|
||||
for dir in dirs {
|
||||
let Ok(rd) = std::fs::read_dir(dir) else {
|
||||
continue;
|
||||
};
|
||||
let mut paths: Vec<_> = rd
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.extension().is_some_and(|x| x == "md") && p.is_file())
|
||||
.collect();
|
||||
paths.sort();
|
||||
for p in paths {
|
||||
let Ok(s) = std::fs::read_to_string(&p) else {
|
||||
continue;
|
||||
};
|
||||
match parse_agent(&p, &s) {
|
||||
Ok(a) => {
|
||||
out.retain(|x| x.name != a.name);
|
||||
out.push(a);
|
||||
}
|
||||
Err(e) => warn.push(format!("{}: skipped: {e}", p.display())),
|
||||
}
|
||||
}
|
||||
}
|
||||
(out, warn)
|
||||
}
|
||||
|
||||
pub fn agent_tools(base: &Registry, def: &AgentDef) -> Registry {
|
||||
let mut t = base.clone();
|
||||
if !def.tools.is_empty() {
|
||||
t.retain(|n| def.tools.iter().any(|x| x == n));
|
||||
}
|
||||
if def.readonly {
|
||||
t.retain(|n| EXPLORE_TOOLS.contains(&n));
|
||||
if let Some(b) = t.get("bash") {
|
||||
t.add(ReadOnlyBash(b));
|
||||
}
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
pub fn edits(t: &Registry) -> bool {
|
||||
t.get("edit").is_some() || t.get("write").is_some()
|
||||
}
|
||||
|
||||
pub fn builtin_kinds() -> Vec<(String, String)> {
|
||||
BUILTIN
|
||||
.iter()
|
||||
.map(|(n, d)| (n.to_string(), d.to_string()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn spec_for(kinds: &[(String, String)]) -> ToolSpec {
|
||||
let list: Vec<String> = kinds
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, (n, d))| {
|
||||
let d = if d.is_empty() { "custom agent" } else { d };
|
||||
format!("kind={n}{}: {d}.", if i == 0 { " (default)" } else { "" })
|
||||
})
|
||||
.collect();
|
||||
let names: Vec<&str> = kinds.iter().map(|k| k.0.as_str()).collect();
|
||||
ToolSpec {
|
||||
name: "task".into(),
|
||||
description: "Run a subagent in a fresh context; you get back only its final answer. The user is asked to approve every call: use it only when the user asked for subagents or parallel work, or when a search would clearly put >10k tokens in your context. Do ordinary discovery (read, grep, lsp, bash) yourself in this session. kind=explore (default): read-only research on a cheaper model. kind=general: same tools as you, may edit. The subagent sees nothing of this conversation: make every prompt self-contained. You are blocked until it answers. For 2+ independent subtasks pass `prompts` (array); they run in parallel.".into(),
|
||||
description: format!(
|
||||
"Run a subagent in a fresh context; you get back only its final answer. The user is asked to approve every call: use it only when the user asked for subagents or parallel work, or when a search would clearly put >10k tokens in your context. Do ordinary discovery (read, grep, lsp, bash) yourself in this session. {} The subagent sees nothing of this conversation: make every prompt self-contained. You are blocked until it answers. For 2+ independent subtasks pass `prompts` (array); they run in parallel. With background=true the call returns at once with the subagent ids and you keep working; their answers are handed to you at the end of a turn, or call task(wait=[ids]) (empty array = all) to block for them.",
|
||||
list.join(" ")
|
||||
),
|
||||
input_schema: json!({"type":"object","properties":{
|
||||
"prompt":{"type":"string"},
|
||||
"prompts":{"type":"array","items":{"type":"string"},"description":"several independent subtasks: one subagent each, run in parallel, answers returned numbered"},
|
||||
"kind":{"type":"string","enum":["explore","general"]}},
|
||||
}),
|
||||
"prompt":{"type":"string"},
|
||||
"background":{"type":"boolean","description":"start and return immediately"},
|
||||
"wait":{"type":"array","items":{"type":"integer"},"description":"block until these background subagents answered; [] = all uncollected"},
|
||||
"prompts":{"type":"array","items":{"type":"string"},"description":"several independent subtasks: one subagent each, run in parallel, answers returned numbered"},
|
||||
"kind":{"type":"string","enum":names}},
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Tool for Task {
|
||||
fn spec(&self) -> ToolSpec {
|
||||
spec()
|
||||
spec_for(&self.kinds())
|
||||
}
|
||||
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
|
||||
if a["prompt"].is_null()
|
||||
&& a["prompts"].is_null()
|
||||
&& let Some(w) = a["wait"].as_array()
|
||||
{
|
||||
let ids: Vec<usize> = w
|
||||
.iter()
|
||||
.filter_map(|v| v.as_u64())
|
||||
.map(|n| n as usize)
|
||||
.collect();
|
||||
return self.wait(&ids, cx).await;
|
||||
}
|
||||
if a["background"].as_bool() == Some(true) {
|
||||
let ps: Vec<&str> = match a["prompts"].as_array() {
|
||||
Some(ps) => ps.iter().filter_map(|p| p.as_str()).collect(),
|
||||
None => vec![a["prompt"].as_str().unwrap_or_default()],
|
||||
};
|
||||
let mut started = vec![];
|
||||
for p in ps {
|
||||
match self.start(p, a["kind"].as_str(), true, cx) {
|
||||
Ok(sub) => {
|
||||
let (me, p) = (sub.clone(), p.to_string());
|
||||
tokio::spawn(async move {
|
||||
let permit = me.sem.acquire().await;
|
||||
me.arm();
|
||||
let r = me.drive(p).await;
|
||||
drop(permit);
|
||||
let out = me.finish(r);
|
||||
*me.sh.result.lock().unwrap_or_else(|e| e.into_inner()) =
|
||||
Some((out.content, out.is_error));
|
||||
});
|
||||
started.push(format!("{} ({})", sub.sh.id, sub.sh.kind));
|
||||
}
|
||||
Err(e) => return e,
|
||||
}
|
||||
}
|
||||
return ToolResult::ok(format!(
|
||||
"started in the background: subagent {}. Their answers are reported to you at the end of a turn, or collect them with task(wait=[ids]).",
|
||||
started.join(", ")
|
||||
));
|
||||
}
|
||||
let Some(ps) = a["prompts"].as_array() else {
|
||||
return self
|
||||
.run(
|
||||
@@ -298,24 +587,74 @@ impl Tool for Task {
|
||||
}
|
||||
|
||||
impl Task {
|
||||
async fn run(&self, prompt: &str, kind: Option<&str>, cx: &ToolCtx) -> ToolResult {
|
||||
let (kind, role) = match kind {
|
||||
None | Some("explore") => ("explore", &self.explore),
|
||||
Some("general") => ("general", &self.general),
|
||||
Some(k) => return ToolResult::err(format!("unknown kind `{k}` (explore | general)")),
|
||||
};
|
||||
let aborted = || cx.state.abort.get().is_some_and(|r| *r.borrow());
|
||||
if aborted() {
|
||||
return ToolResult::err("aborted");
|
||||
async fn wait(&self, ids: &[usize], cx: &ToolCtx) -> ToolResult {
|
||||
let subs: Vec<Arc<Sub>> = cx
|
||||
.state
|
||||
.subs
|
||||
.list()
|
||||
.into_iter()
|
||||
.filter(|s| {
|
||||
s.sh.background
|
||||
&& if ids.is_empty() {
|
||||
!s.sh.collected.load(Ordering::Relaxed)
|
||||
} else {
|
||||
ids.contains(&s.sh.id)
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
if subs.is_empty() {
|
||||
return ToolResult::err("no such background subagent");
|
||||
}
|
||||
let Ok(_permit) = self.sem.acquire().await else {
|
||||
return ToolResult::err("subagents unavailable");
|
||||
let (mut out, mut err) = (String::new(), true);
|
||||
for s in subs {
|
||||
let r = loop {
|
||||
if let Some(r) =
|
||||
s.sh.result
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.clone()
|
||||
{
|
||||
break r;
|
||||
}
|
||||
if cx.state.abort.get().is_some_and(|r| *r.borrow()) {
|
||||
return ToolResult::err("aborted");
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
};
|
||||
s.sh.collected.store(true, Ordering::Relaxed);
|
||||
err &= r.1;
|
||||
out.push_str(&format!("## {} ({})\n{}\n\n", s.sh.id, s.sh.kind, r.0));
|
||||
}
|
||||
ToolResult {
|
||||
content: out,
|
||||
is_error: err,
|
||||
images: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
fn start(
|
||||
&self,
|
||||
prompt: &str,
|
||||
kind: Option<&str>,
|
||||
background: bool,
|
||||
cx: &ToolCtx,
|
||||
) -> Result<Arc<Sub>, ToolResult> {
|
||||
let want = kind.unwrap_or(&self.roles[0].0);
|
||||
let Some((kind, _, role)) = self.roles.iter().find(|r| r.0 == want) else {
|
||||
let names: Vec<&str> = self.roles.iter().map(|r| r.0.as_str()).collect();
|
||||
return Err(ToolResult::err(format!(
|
||||
"unknown kind `{want}` ({})",
|
||||
names.join(" | ")
|
||||
)));
|
||||
};
|
||||
if cx.state.abort.get().is_some_and(|r| *r.borrow()) {
|
||||
return Err(ToolResult::err("aborted"));
|
||||
}
|
||||
let id = self.n.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
let path = self.dir.join(format!("{id:03}-{kind}.jsonl"));
|
||||
let session = match Session::open(&path) {
|
||||
Ok(s) => s,
|
||||
Err(e) => return ToolResult::err(format!("subagent session: {e}")),
|
||||
Err(e) => return Err(ToolResult::err(format!("subagent session: {e}"))),
|
||||
};
|
||||
let (mut child, handle) = Agent::new(
|
||||
role.provider.clone(),
|
||||
@@ -328,10 +667,10 @@ impl Task {
|
||||
);
|
||||
child.set_model(role.model.clone());
|
||||
child.set_system(role.system.clone());
|
||||
child.set_max_turns(self.max_turns);
|
||||
child.set_max_turns(role.max_turns.unwrap_or(self.max_turns));
|
||||
let sh = Arc::new(Shared {
|
||||
id,
|
||||
kind,
|
||||
kind: kind.clone(),
|
||||
model: role.model.clone(),
|
||||
prompt: prompt.to_string(),
|
||||
started: Instant::now(),
|
||||
@@ -341,11 +680,19 @@ impl Task {
|
||||
usage: Mutex::default(),
|
||||
inbox: Mutex::default(),
|
||||
rolled: Mutex::default(),
|
||||
stop: Mutex::new(None),
|
||||
timeout: self.timeout,
|
||||
runs: AtomicUsize::new(0),
|
||||
background,
|
||||
result: Mutex::new(None),
|
||||
collected: Default::default(),
|
||||
});
|
||||
child
|
||||
.bus
|
||||
.add(Live(sh.clone(), cx.state.subs.events.get().cloned()));
|
||||
if kind == "general" {
|
||||
child.bus.add(Live(
|
||||
sh.clone(),
|
||||
cx.state.subs.events.get().cloned(),
|
||||
self.max_tokens.map(|m| (m, handle.clone())),
|
||||
));
|
||||
if role.hooks {
|
||||
for h in &self.hooks {
|
||||
child.bus.add_arc(h.clone());
|
||||
}
|
||||
@@ -356,17 +703,38 @@ impl Task {
|
||||
abort: handle,
|
||||
state: cx.state.clone(),
|
||||
sem: self.sem.clone(),
|
||||
dir: self.dir.clone(),
|
||||
});
|
||||
cx.state.subs.add(sub.clone());
|
||||
cx.state.subs.watch(&cx.state);
|
||||
if aborted() {
|
||||
Ok(sub)
|
||||
}
|
||||
|
||||
async fn run(&self, prompt: &str, kind: Option<&str>, cx: &ToolCtx) -> ToolResult {
|
||||
let sub = match self.start(prompt, kind, false, cx) {
|
||||
Ok(s) => s,
|
||||
Err(e) => return e,
|
||||
};
|
||||
let Ok(_permit) = self.sem.acquire().await else {
|
||||
return ToolResult::err("subagents unavailable");
|
||||
};
|
||||
if cx.state.abort.get().is_some_and(|r| *r.borrow()) {
|
||||
sub.abort();
|
||||
}
|
||||
sub.arm();
|
||||
let r = sub.drive(prompt.to_string()).await;
|
||||
sub.finish(r)
|
||||
}
|
||||
}
|
||||
|
||||
impl Sub {
|
||||
fn finish(&self, r: Result<Message, Error>) -> ToolResult {
|
||||
let sh = &self.sh;
|
||||
let u = sh.usage.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
||||
let tok = u.input_tokens + u.cache_read_tokens + u.cache_write_tokens + u.output_tokens;
|
||||
let stats = format!(
|
||||
"[task {kind} · {} tool calls · {}k tok · {}s]",
|
||||
"[task {} · {} tool calls · {}k tok · {}s]",
|
||||
sh.kind,
|
||||
sh.calls.load(Ordering::Relaxed),
|
||||
tok / 1000,
|
||||
sh.elapsed().as_secs()
|
||||
@@ -375,16 +743,58 @@ impl Task {
|
||||
Ok(m) => {
|
||||
let mut t = m.text();
|
||||
if t.len() > MAX_RESULT {
|
||||
let p = self.dir.join(format!("{:03}-{}.answer.md", sh.id, sh.kind));
|
||||
let saved = std::fs::write(&p, &t).is_ok();
|
||||
let mut i = MAX_RESULT;
|
||||
while !t.is_char_boundary(i) {
|
||||
i -= 1;
|
||||
}
|
||||
t.truncate(i);
|
||||
t.push_str("\n[... answer cut ...]");
|
||||
if saved {
|
||||
t.push_str(&format!("\nfull answer: {}", p.display()));
|
||||
}
|
||||
}
|
||||
ToolResult::ok(format!("{t}\n{stats}"))
|
||||
}
|
||||
Err(e) => ToolResult::err(format!("subagent failed: {e}\n{stats}")),
|
||||
Err(e) => {
|
||||
let why = sh.stopped().unwrap_or_else(|| e.to_string());
|
||||
ToolResult::err(format!("subagent failed: {why}\n{stats}"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Notify(pub Arc<crate::State>);
|
||||
|
||||
#[async_trait]
|
||||
impl Hook for Notify {
|
||||
async fn on(&self, ev: &Event) -> HookAction {
|
||||
if !matches!(ev, Event::TurnEnd | Event::AgentEnd) {
|
||||
return HookAction::Continue;
|
||||
}
|
||||
let mut out = vec![];
|
||||
for s in self.0.subs.list() {
|
||||
if !s.sh.background || s.sh.collected.load(Ordering::Relaxed) {
|
||||
continue;
|
||||
}
|
||||
if let Some(r) =
|
||||
s.sh.result
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.clone()
|
||||
{
|
||||
s.sh.collected.store(true, Ordering::Relaxed);
|
||||
out.push(format!(
|
||||
"background subagent {} ({}) finished:\n{}",
|
||||
s.sh.id, s.sh.kind, r.0
|
||||
));
|
||||
}
|
||||
}
|
||||
if out.is_empty() {
|
||||
HookAction::Continue
|
||||
} else {
|
||||
HookAction::Inject(out.join("\n\n"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -468,9 +878,211 @@ mod tests {
|
||||
model: model.into(),
|
||||
tools,
|
||||
system: "child".into(),
|
||||
hooks: false,
|
||||
max_turns: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_files_parse_override_and_filter_tools() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let (a, b) = (d.path().join("a"), d.path().join("b"));
|
||||
std::fs::create_dir_all(&a).unwrap();
|
||||
std::fs::create_dir_all(&b).unwrap();
|
||||
std::fs::write(
|
||||
a.join("rev.md"),
|
||||
"---\ndescription: reviews\ntools: [read, nope]\nmax_turns: 5\n---\nBe strict.\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
b.join("rev.md"),
|
||||
"---\ndescription: project review\ntools: read, bash\nreadonly: true\nmodel: m\n---\nP\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(b.join("bad name.md"), "x").unwrap();
|
||||
let (defs, warn) = load_agents(&[a, b]);
|
||||
assert_eq!(warn.len(), 1, "{warn:?}");
|
||||
assert_eq!(defs.len(), 1);
|
||||
let r = &defs[0];
|
||||
assert_eq!(
|
||||
(r.name.as_str(), r.description.as_str(), r.system.as_str()),
|
||||
("rev", "project review", "P")
|
||||
);
|
||||
assert_eq!(r.tools, ["read", "bash"]);
|
||||
assert!(r.readonly && r.model.as_deref() == Some("m"));
|
||||
let mut base = Registry::default();
|
||||
base.add(Echo);
|
||||
base.add(Bash);
|
||||
let t = agent_tools(&base, r);
|
||||
assert!(t.get("read").is_some() && t.get("bash").is_some());
|
||||
let t = agent_tools(
|
||||
&base,
|
||||
&AgentDef {
|
||||
tools: vec!["read".into(), "nope".into()],
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
assert!(t.get("read").is_some() && t.get("bash").is_none());
|
||||
assert!(!edits(&t));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn background_returns_at_once_then_wait_and_notify_deliver() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let p = Arc::new(Script(
|
||||
Mutex::new(vec![text("first"), text("second")]),
|
||||
Default::default(),
|
||||
));
|
||||
let t = Task::new(
|
||||
role(&p, "cheap"),
|
||||
role(&p, "main"),
|
||||
d.path().join("s.sub"),
|
||||
3,
|
||||
);
|
||||
let cx = ToolCtx {
|
||||
cwd: d.path().into(),
|
||||
state: Default::default(),
|
||||
};
|
||||
let r = t
|
||||
.call(json!({"prompts":["a","b"],"background":true}), &cx)
|
||||
.await;
|
||||
assert!(
|
||||
!r.is_error && r.content.contains("started in the background"),
|
||||
"{r:?}"
|
||||
);
|
||||
assert_eq!(cx.state.subs.list().len(), 2);
|
||||
let w = t.call(json!({"wait":[1]}), &cx).await;
|
||||
assert!(
|
||||
!w.is_error && w.content.starts_with("## 1 (explore)\n"),
|
||||
"{w:?}"
|
||||
);
|
||||
let n = Notify(cx.state.clone());
|
||||
let mut got = None;
|
||||
for _ in 0..100 {
|
||||
if let HookAction::Inject(m) = n.on(&Event::TurnEnd).await {
|
||||
got = Some(m);
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
|
||||
}
|
||||
let m = got.expect("notified");
|
||||
assert!(
|
||||
m.contains("background subagent 2") && !m.contains("subagent 1"),
|
||||
"{m}"
|
||||
);
|
||||
assert!(matches!(n.on(&Event::TurnEnd).await, HookAction::Continue));
|
||||
assert!(t.call(json!({"wait":[9]}), &cx).await.is_error);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn token_budget_stops_child() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let p = Arc::new(Script(
|
||||
Mutex::new(vec![call("read", json!({}))]),
|
||||
Default::default(),
|
||||
));
|
||||
let mut t = Task::new(
|
||||
role(&p, "cheap"),
|
||||
role(&p, "main"),
|
||||
d.path().join("s.sub"),
|
||||
1,
|
||||
);
|
||||
t.max_tokens = Some(500);
|
||||
let cx = ToolCtx {
|
||||
cwd: d.path().into(),
|
||||
state: Default::default(),
|
||||
};
|
||||
let r = t.call(json!({"prompt":"a"}), &cx).await;
|
||||
assert!(
|
||||
r.is_error && r.content.contains("token budget exceeded"),
|
||||
"{r:?}"
|
||||
);
|
||||
assert!(matches!(
|
||||
cx.state.subs.get(1).unwrap().sh.status(),
|
||||
Status::Failed(w) if w.contains("token budget")
|
||||
));
|
||||
}
|
||||
|
||||
struct Hang;
|
||||
#[async_trait]
|
||||
impl Provider for Hang {
|
||||
async fn stream(
|
||||
&self,
|
||||
_: Request,
|
||||
) -> hx_ai::Result<BoxStream<'static, hx_ai::Result<StreamEvent>>> {
|
||||
Ok(futures::stream::pending().boxed())
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn timeout_stops_child() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let mut r = role(&Arc::new(Script(Mutex::default(), Default::default())), "m");
|
||||
r.provider = Arc::new(Hang);
|
||||
let mut r2 = role(&Arc::new(Script(Mutex::default(), Default::default())), "m");
|
||||
r2.provider = Arc::new(Hang);
|
||||
let mut t = Task::new(r, r2, d.path().join("s.sub"), 1);
|
||||
t.timeout = Some(std::time::Duration::from_millis(100));
|
||||
let cx = ToolCtx {
|
||||
cwd: d.path().into(),
|
||||
state: Default::default(),
|
||||
};
|
||||
let r = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(5),
|
||||
t.call(json!({"prompt":"a"}), &cx),
|
||||
)
|
||||
.await
|
||||
.expect("timeout must end the child");
|
||||
assert!(r.is_error && r.content.contains("timeout after"), "{r:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn long_answer_is_saved_to_a_file() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let big = "y".repeat(20_000);
|
||||
let p = Arc::new(Script(Mutex::new(vec![text(&big)]), Default::default()));
|
||||
let t = Task::new(
|
||||
role(&p, "cheap"),
|
||||
role(&p, "main"),
|
||||
d.path().join("s.sub"),
|
||||
1,
|
||||
);
|
||||
let cx = ToolCtx {
|
||||
cwd: d.path().into(),
|
||||
state: Default::default(),
|
||||
};
|
||||
let r = t.call(json!({"prompt":"a"}), &cx).await;
|
||||
assert!(r.content.contains("full answer: "), "{}", r.content);
|
||||
let f = d.path().join("s.sub/001-explore.answer.md");
|
||||
assert_eq!(std::fs::read_to_string(f).unwrap(), big);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn custom_kind_is_listed_and_runs_with_its_role() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let p = Arc::new(Script(Mutex::new(vec![text("ok")]), Default::default()));
|
||||
let mut t = Task::new(
|
||||
role(&p, "cheap"),
|
||||
role(&p, "main"),
|
||||
d.path().join("s.sub"),
|
||||
1,
|
||||
);
|
||||
let mut r = role(&p, "mine");
|
||||
r.max_turns = Some(3);
|
||||
t.add_kind("rev".into(), "reviews".into(), r);
|
||||
let s = Tool::spec(&t);
|
||||
assert_eq!(s.input_schema["properties"]["kind"]["enum"][2], "rev");
|
||||
assert!(s.description.contains("kind=rev: reviews."));
|
||||
let cx = ToolCtx {
|
||||
cwd: d.path().into(),
|
||||
state: Default::default(),
|
||||
};
|
||||
let r = t.call(json!({"prompt":"a","kind":"rev"}), &cx).await;
|
||||
assert!(r.content.contains("[task rev"), "{}", r.content);
|
||||
assert_eq!(p.1.lock().unwrap()[0].model, "mine");
|
||||
assert!(d.path().join("s.sub/001-rev.jsonl").exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn child_runs_returns_answer_and_usage() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
@@ -561,6 +1173,36 @@ mod tests {
|
||||
assert!(d.path().join("s.sub/001-general.jsonl").exists());
|
||||
}
|
||||
|
||||
struct Bash;
|
||||
#[async_trait]
|
||||
impl Tool for Bash {
|
||||
fn spec(&self) -> ToolSpec {
|
||||
ToolSpec {
|
||||
name: "bash".into(),
|
||||
description: "".into(),
|
||||
input_schema: json!({"type":"object"}),
|
||||
}
|
||||
}
|
||||
async fn call(&self, _: Value, _: &ToolCtx) -> ToolResult {
|
||||
ToolResult::ok("ran")
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn readonly_bash_refuses_writes() {
|
||||
let cx = ToolCtx {
|
||||
cwd: ".".into(),
|
||||
state: Default::default(),
|
||||
};
|
||||
let t = ReadOnlyBash(Arc::new(Bash));
|
||||
assert!(t.call(json!({"command":"echo x > f"}), &cx).await.is_error);
|
||||
assert!(t.call(json!({"command":"rm -rf x"}), &cx).await.is_error);
|
||||
assert_eq!(
|
||||
t.call(json!({"command":"rg foo"}), &cx).await.content,
|
||||
"ran"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn parent_abort_stops_child() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -135,7 +135,14 @@ pub async fn gate_why(cx: &ToolCtx, req: crate::permit::Request) -> Result<(), S
|
||||
}
|
||||
}
|
||||
let rule = req.rule.clone();
|
||||
match ask(req).await {
|
||||
let decision = match cx.state.abort.get().cloned() {
|
||||
Some(mut rx) => tokio::select! {
|
||||
d = ask(req) => d,
|
||||
_ = async { rx.wait_for(|a| *a).await.is_ok() } => Decision::Deny,
|
||||
},
|
||||
None => ask(req).await,
|
||||
};
|
||||
match decision {
|
||||
Decision::Once => {}
|
||||
Decision::Always => allow().add(&rule),
|
||||
Decision::Edits => allow().allow_edits(),
|
||||
|
||||
@@ -366,6 +366,19 @@ impl Tool for ExitPlan {
|
||||
|
||||
const LIVE_TAIL: usize = 2048;
|
||||
|
||||
#[cfg(unix)]
|
||||
struct KillGroup(Option<u32>);
|
||||
#[cfg(unix)]
|
||||
impl Drop for KillGroup {
|
||||
fn drop(&mut self) {
|
||||
if let Some(pid) = self.0 {
|
||||
let _ = std::process::Command::new("kill")
|
||||
.args(["-KILL", &format!("-{pid}")])
|
||||
.status();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Bash;
|
||||
#[async_trait]
|
||||
impl Tool for Bash {
|
||||
@@ -396,6 +409,8 @@ impl Tool for Bash {
|
||||
Err(e) => return ToolResult::err(format!("spawn: {e}")),
|
||||
};
|
||||
let pid = child.id();
|
||||
#[cfg(unix)]
|
||||
let mut group = KillGroup(pid);
|
||||
let mut so = child.stdout.take().expect("piped");
|
||||
let live = &cx.state.live;
|
||||
let run = async {
|
||||
@@ -420,15 +435,21 @@ impl Tool for Bash {
|
||||
let res = tokio::time::timeout(Duration::from_secs(secs), run).await;
|
||||
live.lock().unwrap_or_else(|e| e.into_inner()).remove(cmd);
|
||||
let (out, code) = match res {
|
||||
Ok(Ok((o, st))) => (o, st.code()),
|
||||
Ok(Err(e)) => return ToolResult::err(format!("wait: {e}")),
|
||||
Err(_) => {
|
||||
Ok(Ok((o, st))) => {
|
||||
#[cfg(unix)]
|
||||
if let Some(pid) = pid {
|
||||
let _ = std::process::Command::new("kill")
|
||||
.args(["-KILL", &format!("-{pid}")])
|
||||
.status();
|
||||
{
|
||||
group.0 = None;
|
||||
}
|
||||
(o, st.code())
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
group.0 = None;
|
||||
}
|
||||
return ToolResult::err(format!("wait: {e}"));
|
||||
}
|
||||
Err(_) => {
|
||||
return ToolResult::err(format!("timed out after {secs}s"));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::time::Duration;
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Row {
|
||||
pub id: usize,
|
||||
pub kind: &'static str,
|
||||
pub kind: String,
|
||||
pub prompt: String,
|
||||
pub status: Status,
|
||||
pub elapsed: Duration,
|
||||
@@ -23,7 +23,7 @@ pub fn row(s: &Sub) -> Row {
|
||||
let u = s.sh.usage.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
||||
Row {
|
||||
id: s.sh.id,
|
||||
kind: s.sh.kind,
|
||||
kind: s.sh.kind.clone(),
|
||||
prompt: s.sh.prompt.lines().next().unwrap_or_default().to_string(),
|
||||
status: s.sh.status(),
|
||||
elapsed: s.sh.elapsed(),
|
||||
@@ -204,7 +204,7 @@ mod tests {
|
||||
fn r(id: usize, st: Status) -> Row {
|
||||
Row {
|
||||
id,
|
||||
kind: "explore",
|
||||
kind: "explore".into(),
|
||||
prompt: "grep the auth middleware for token expiry checks".into(),
|
||||
status: st,
|
||||
elapsed: Duration::from_secs(72),
|
||||
|
||||
+147
-146
@@ -11,6 +11,7 @@ pub mod review;
|
||||
pub mod scroll;
|
||||
pub mod select;
|
||||
pub mod sessions;
|
||||
pub mod side;
|
||||
pub mod stats_view;
|
||||
pub mod status;
|
||||
pub mod theme;
|
||||
@@ -51,7 +52,7 @@ pub struct Setup {
|
||||
pub mouse: bool,
|
||||
pub yolo: bool,
|
||||
pub auto: bool,
|
||||
pub mcp: Vec<(String, bool)>,
|
||||
pub mcp: side::McpStatus,
|
||||
}
|
||||
|
||||
#[derive(Default, Clone, Copy)]
|
||||
@@ -109,6 +110,12 @@ impl Hook for Forward {
|
||||
}
|
||||
}
|
||||
|
||||
type DocPrompt = (
|
||||
doc_view::DocView,
|
||||
hx_core::Question,
|
||||
tokio::sync::oneshot::Sender<Option<Vec<String>>>,
|
||||
);
|
||||
|
||||
struct App {
|
||||
t: Transcript,
|
||||
ed: Editor,
|
||||
@@ -142,11 +149,7 @@ struct App {
|
||||
tokio::sync::oneshot::Sender<hx_core::permit::Decision>,
|
||||
)>,
|
||||
review: Option<review::Review>,
|
||||
doc: Option<(
|
||||
doc_view::DocView,
|
||||
hx_core::Question,
|
||||
tokio::sync::oneshot::Sender<Option<Vec<String>>>,
|
||||
)>,
|
||||
doc: Option<DocPrompt>,
|
||||
probe: bool,
|
||||
kbd: bool,
|
||||
stats: Option<(hx_core::stats::Summary, String)>,
|
||||
@@ -154,7 +157,11 @@ struct App {
|
||||
snap: Option<tokio::sync::watch::Receiver<Arc<hx_core::agent::Snap>>>,
|
||||
side: bool,
|
||||
lens_lines: Vec<String>,
|
||||
mcp: Vec<(String, bool)>,
|
||||
mcp: Vec<side::McpRow>,
|
||||
log: side::LogRing,
|
||||
consult: Option<side::Consult>,
|
||||
seen_subs: std::collections::HashMap<usize, String>,
|
||||
mode: &'static str,
|
||||
choose: Option<(
|
||||
choose::Choose,
|
||||
tokio::sync::oneshot::Sender<Option<Vec<String>>>,
|
||||
@@ -179,6 +186,60 @@ impl App {
|
||||
if sw.provider_changed {
|
||||
self.st.quota = None;
|
||||
}
|
||||
self.log.push("main", format!("model {}", self.st.model));
|
||||
}
|
||||
|
||||
fn sync_log(&mut self) {
|
||||
for s in self.state.subs.list() {
|
||||
let st = match s.sh.status() {
|
||||
hx_core::subagent::Status::Running => "started".to_string(),
|
||||
hx_core::subagent::Status::Done => {
|
||||
format!("done {}s", s.sh.elapsed().as_secs())
|
||||
}
|
||||
hx_core::subagent::Status::Failed(e) => format!("failed {e}"),
|
||||
hx_core::subagent::Status::Aborted => "aborted".into(),
|
||||
};
|
||||
let key = format!("{} {}", s.sh.model, st);
|
||||
if self.seen_subs.get(&s.sh.id) != Some(&key) {
|
||||
self.log.push(format!("{} {}", s.sh.kind, s.sh.model), st);
|
||||
self.seen_subs.insert(s.sh.id, key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn sync_lens_log(&mut self, new: &[String]) {
|
||||
let state = |x: &str| {
|
||||
x.split_once(" @ ")
|
||||
.map(|(n, r)| {
|
||||
(
|
||||
n.to_string(),
|
||||
r.rsplit_once(": ").map_or("", |p| p.1).to_string(),
|
||||
)
|
||||
})
|
||||
.unwrap_or_else(|| (x.to_string(), String::new()))
|
||||
};
|
||||
for x in new {
|
||||
let (n, s) = state(x);
|
||||
let old = self.lens_lines.iter().map(|o| state(o)).find(|o| o.0 == n);
|
||||
if old.as_ref().map(|o| &o.1) != Some(&s) && !s.is_empty() {
|
||||
self.log.push("lsp", format!("{n} {s}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn sync_mcp(&mut self, new: Vec<side::McpRow>) {
|
||||
for m in &new {
|
||||
let old = self.mcp.iter().find(|o| o.name == m.name).map(|o| o.state);
|
||||
if old != Some(m.state) && m.state != side::McpState::Pending {
|
||||
let what = match (&m.state, &m.error) {
|
||||
(side::McpState::Failed, Some(e)) => format!("{} failed: {e}", m.name),
|
||||
(side::McpState::Failed, None) => format!("{} failed", m.name),
|
||||
_ => format!("{} up {} tools", m.name, m.tools),
|
||||
};
|
||||
self.log.push("mcp", what);
|
||||
}
|
||||
}
|
||||
self.mcp = new;
|
||||
}
|
||||
|
||||
fn ctx_max_from(&mut self, a: &Agent) {
|
||||
@@ -233,7 +294,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
mouse,
|
||||
yolo,
|
||||
auto,
|
||||
mcp,
|
||||
mcp: mcp_status,
|
||||
} = setup;
|
||||
let kbd = crossterm::terminal::supports_keyboard_enhancement().unwrap_or(false);
|
||||
let (tx, mut rx) = mpsc::unbounded_channel();
|
||||
@@ -350,12 +411,25 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
snap: Some(agent.snap()),
|
||||
side: true,
|
||||
lens_lines: vec![],
|
||||
mcp,
|
||||
mcp: vec![],
|
||||
log: Default::default(),
|
||||
consult: None,
|
||||
seen_subs: Default::default(),
|
||||
mode: if yolo {
|
||||
"yolo"
|
||||
} else if auto {
|
||||
"auto"
|
||||
} else {
|
||||
"ask"
|
||||
},
|
||||
state: agent.cx.state.clone(),
|
||||
sub_t: Default::default(),
|
||||
agents: None,
|
||||
};
|
||||
sessions::history(&mut app.t, &agent.session().messages());
|
||||
let first = mcp_status();
|
||||
app.sync_mcp(first);
|
||||
app.log.push("main", format!("model {}", app.st.model));
|
||||
if open_sessions {
|
||||
open_sessions_picker(&mut app);
|
||||
}
|
||||
@@ -551,6 +625,9 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
}
|
||||
Ui::Done(r) => {
|
||||
app.busy = false;
|
||||
app.choose = None;
|
||||
app.doc = None;
|
||||
app.perm = None;
|
||||
{
|
||||
let mut a = agent.lock().await;
|
||||
if let Some(sw) = app.sw.end_turn(&mut a) {
|
||||
@@ -601,15 +678,23 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
}
|
||||
t.apply(&ev);
|
||||
}
|
||||
_ = tick.tick(), if app.busy || subs_running(&app) => dirty = true,
|
||||
_ = tick.tick(), if app.busy || subs_running(&app) => {
|
||||
app.sync_log();
|
||||
dirty = true;
|
||||
}
|
||||
_ = lens_tick.tick() => {
|
||||
let to = std::time::Duration::from_millis(200);
|
||||
if let Ok(v) = tokio::time::timeout(to, lsp_status()).await {
|
||||
let s = status::lens_summary(&v);
|
||||
app.sync_lens_log(&v);
|
||||
app.lens_lines = v;
|
||||
dirty |= s != app.lens;
|
||||
app.lens = s;
|
||||
}
|
||||
let m = mcp_status();
|
||||
dirty |= m != app.mcp;
|
||||
app.sync_mcp(m);
|
||||
app.sync_log();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -884,7 +969,7 @@ fn chat_buf(app: &App) -> (Buffer, Vec<bool>) {
|
||||
.line_count(w)
|
||||
.max(1);
|
||||
cont.push(false);
|
||||
cont.extend(std::iter::repeat(true).take(n - 1));
|
||||
cont.extend(std::iter::repeat_n(true, n - 1));
|
||||
}
|
||||
let para = Paragraph::new(lines).wrap(Wrap { trim: false });
|
||||
let r = Rect::new(0, 0, w, para.line_count(w) as u16);
|
||||
@@ -1806,14 +1891,32 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
|
||||
f.render_widget(block, side);
|
||||
let mut ls = vec![
|
||||
spread_line(
|
||||
Span::styled("/lsp", th.accent().add_modifier(Modifier::BOLD)),
|
||||
Span::styled("/status", th.accent().add_modifier(Modifier::BOLD)),
|
||||
Span::styled("ctrl-l ×", th.dim()),
|
||||
body.width,
|
||||
),
|
||||
Line::default(),
|
||||
];
|
||||
ls.extend(side_lines(app, body.width as usize));
|
||||
f.render_widget(Paragraph::new(ls).wrap(Wrap { trim: false }), body);
|
||||
let lens = app
|
||||
.state
|
||||
.lens
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.clone();
|
||||
let subs = app.state.subs.list();
|
||||
ls.extend(side::lines(&side::View {
|
||||
st: &app.st,
|
||||
mode: app.mode,
|
||||
lens_lines: &app.lens_lines,
|
||||
lens: &lens,
|
||||
mcp: &app.mcp,
|
||||
subs: &subs,
|
||||
consult: app.consult.as_ref(),
|
||||
log: &app.log,
|
||||
w: body.width as usize,
|
||||
h: (body.height as usize).saturating_sub(2),
|
||||
}));
|
||||
f.render_widget(Paragraph::new(ls), body);
|
||||
app.areas.panel = Rect::default();
|
||||
m
|
||||
}
|
||||
@@ -1953,128 +2056,6 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
|
||||
}
|
||||
}
|
||||
|
||||
const SIDE_DIAGS: usize = 8;
|
||||
const SIDE_TESTS: usize = 6;
|
||||
|
||||
fn side_lines(app: &App, w: usize) -> Vec<Line<'static>> {
|
||||
let th = theme::t();
|
||||
let sec = |label: String| {
|
||||
Line::styled(
|
||||
th.rule(&label, w)
|
||||
.replacen(th.sym.rule, "", 1)
|
||||
.trim_start()
|
||||
.to_string(),
|
||||
th.dim(),
|
||||
)
|
||||
};
|
||||
let mut l = vec![];
|
||||
if app.lens_lines.is_empty() {
|
||||
l.push(Line::styled("no servers started", th.dim()));
|
||||
}
|
||||
for x in &app.lens_lines {
|
||||
let (name, state) = match x.split_once(" @ ") {
|
||||
Some((n, r)) => (n.to_string(), r.rsplit_once(": ").map_or("", |p| p.1)),
|
||||
None => (x.clone(), ""),
|
||||
};
|
||||
let (mark, st, word) = if state.starts_with("running") {
|
||||
(th.sym.done, th.ok(), "ready")
|
||||
} else if state.is_empty() {
|
||||
(th.sym.info, th.dim(), "")
|
||||
} else if state == "stopped" {
|
||||
(th.sym.off, th.dim(), "stopped")
|
||||
} else {
|
||||
(th.sym.err, th.err(), state)
|
||||
};
|
||||
l.push(Line::from(vec![
|
||||
Span::styled(format!("{mark} "), st),
|
||||
Span::styled(
|
||||
format!("{name:<16}"),
|
||||
if word.is_empty() {
|
||||
th.sec()
|
||||
} else {
|
||||
th.plain()
|
||||
},
|
||||
),
|
||||
Span::styled(format!(" {word}"), th.sec()),
|
||||
]));
|
||||
}
|
||||
let view = app
|
||||
.state
|
||||
.lens
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.clone();
|
||||
if !view.diags.is_empty() {
|
||||
l.push(Line::default());
|
||||
l.push(sec(format!("diagnostics {}", view.diags.len())));
|
||||
let mut ds = view.diags.clone();
|
||||
ds.sort_by_key(|d| (!d.error, d.file.clone(), d.line));
|
||||
for d in ds.iter().take(SIDE_DIAGS) {
|
||||
let (mark, st) = if d.error {
|
||||
(th.sym.err, th.err())
|
||||
} else {
|
||||
(th.sym.warn, th.warn())
|
||||
};
|
||||
let file = d.file.rsplit('/').next().unwrap_or(&d.file);
|
||||
l.push(Line::from(vec![
|
||||
Span::styled(format!("{mark} "), st),
|
||||
Span::styled(format!("{file}:{}:{}", d.line, d.col), th.plain()),
|
||||
]));
|
||||
l.push(Line::styled(format!(" {}", d.message), th.sec()));
|
||||
}
|
||||
if ds.len() > SIDE_DIAGS {
|
||||
l.push(Line::styled(
|
||||
format!(" {} {} more", th.sym.ellipsis, ds.len() - SIDE_DIAGS),
|
||||
th.dim(),
|
||||
));
|
||||
}
|
||||
}
|
||||
if let Some(ts) = &view.tests {
|
||||
let mut ts = ts.clone();
|
||||
ts.sort_by_key(|t| t.1);
|
||||
l.push(Line::default());
|
||||
l.push(sec(format!("affected tests {}", ts.len())));
|
||||
for (n, ok) in ts.iter().take(SIDE_TESTS) {
|
||||
l.push(Line::from(vec![
|
||||
Span::styled(
|
||||
format!("{} ", if *ok { th.sym.ok } else { th.sym.err }),
|
||||
if *ok { th.ok() } else { th.err() },
|
||||
),
|
||||
Span::styled(n.clone(), th.plain()),
|
||||
]));
|
||||
}
|
||||
if ts.len() > SIDE_TESTS {
|
||||
l.push(Line::styled(
|
||||
format!(" {} {} more", th.sym.ellipsis, ts.len() - SIDE_TESTS),
|
||||
th.dim(),
|
||||
));
|
||||
}
|
||||
}
|
||||
let u = &app.st.usage;
|
||||
let tot = u.input_tokens + u.cache_read_tokens + u.cache_write_tokens;
|
||||
l.push(Line::default());
|
||||
l.push(sec("context".into()));
|
||||
let mut ctx = format!("{}k / {}k", app.st.ctx_tokens / 1000, app.st.ctx_max / 1000);
|
||||
if let Some(p) = (100 * u.cache_read_tokens).checked_div(tot) {
|
||||
ctx += &format!(" {} cache {p}%", th.sym.info);
|
||||
}
|
||||
l.push(Line::styled(ctx, th.sec()));
|
||||
if !app.mcp.is_empty() {
|
||||
l.push(Line::default());
|
||||
l.push(sec("mcp".into()));
|
||||
l.extend(app.mcp.iter().map(|(n, ok)| {
|
||||
Line::from(vec![
|
||||
Span::styled(
|
||||
format!("{} ", if *ok { th.sym.done } else { th.sym.err }),
|
||||
if *ok { th.ok() } else { th.err() },
|
||||
),
|
||||
Span::styled(n.clone(), th.plain()),
|
||||
])
|
||||
}));
|
||||
}
|
||||
l
|
||||
}
|
||||
|
||||
fn skills_list(specs: &[CmdSpec], dirs: &[std::path::PathBuf]) -> String {
|
||||
let sk: Vec<String> = specs
|
||||
.iter()
|
||||
@@ -2322,7 +2303,23 @@ mod tests {
|
||||
#[test]
|
||||
fn side_panel_only_on_wide_terminals() {
|
||||
let mut app = test_app();
|
||||
app.mcp = vec![("git".into(), true), ("db".into(), false)];
|
||||
app.mcp = vec![
|
||||
side::McpRow {
|
||||
name: "git".into(),
|
||||
state: side::McpState::Ok,
|
||||
tools: 3,
|
||||
prompts: 0,
|
||||
error: None,
|
||||
},
|
||||
side::McpRow {
|
||||
name: "db".into(),
|
||||
state: side::McpState::Failed,
|
||||
tools: 0,
|
||||
prompts: 0,
|
||||
error: Some("refused".into()),
|
||||
},
|
||||
];
|
||||
app.log.push("lsp", "rust-analyzer running");
|
||||
app.lens_lines = vec!["rust-analyzer @ /p: running".into()];
|
||||
*app.state.lens.lock().unwrap() = hx_core::LensView {
|
||||
diags: vec![hx_core::Diag {
|
||||
@@ -2336,23 +2333,21 @@ mod tests {
|
||||
};
|
||||
let s = screen(&mut app, 160, 50);
|
||||
assert!(
|
||||
s.contains("diagnostics 1 ┈") && s.contains("⚠ codemode.rs:88:13"),
|
||||
"{s}"
|
||||
);
|
||||
assert!(
|
||||
s.contains("affected tests 2 ┈") && s.contains("✗ a::bad"),
|
||||
s.contains("LSP") && s.contains("⚠ codemode.rs:88 unused variable"),
|
||||
"{s}"
|
||||
);
|
||||
assert!(s.contains("TESTS") && s.contains("✗ a::bad"), "{s}");
|
||||
let bad = s.find("✗ a::bad").unwrap();
|
||||
assert!(bad < s.find("✓ a::ok").unwrap(), "failures first");
|
||||
assert!(
|
||||
s.contains("/lsp") && s.contains("● rust-analyzer ready"),
|
||||
s.contains("/status") && s.contains("● rust-analyzer") && s.contains("ready"),
|
||||
"{s}"
|
||||
);
|
||||
assert!(s.contains("mcp ┈") && s.contains("✗ db"), "{s}");
|
||||
assert!(!screen(&mut app, 80, 24).contains("/lsp"));
|
||||
assert!(s.contains("MCP") && s.contains("✗ db"), "{s}");
|
||||
assert!(s.contains("MODEL") && s.contains("SESSION LOG"), "{s}");
|
||||
assert!(!screen(&mut app, 80, 24).contains("/status"));
|
||||
app.side = false;
|
||||
assert!(!screen(&mut app, 160, 50).contains("/lsp"));
|
||||
assert!(!screen(&mut app, 160, 50).contains("/status"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2426,6 +2421,8 @@ mod tests {
|
||||
model: "m".into(),
|
||||
tools: Default::default(),
|
||||
system: String::new(),
|
||||
hooks: false,
|
||||
max_turns: None,
|
||||
};
|
||||
let task = hx_core::subagent::Task::new(role(), role(), d.path().join("s.sub"), 1);
|
||||
let cx = ToolCtx {
|
||||
@@ -2647,6 +2644,10 @@ mod tests {
|
||||
side: true,
|
||||
lens_lines: vec![],
|
||||
mcp: vec![],
|
||||
log: Default::default(),
|
||||
consult: None,
|
||||
seen_subs: Default::default(),
|
||||
mode: "ask",
|
||||
state: Default::default(),
|
||||
sub_t: Default::default(),
|
||||
agents: None,
|
||||
|
||||
@@ -234,9 +234,6 @@ impl W {
|
||||
self.text(" ", st);
|
||||
} else {
|
||||
self.flush();
|
||||
if self.lists.is_empty() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
Event::Rule => {
|
||||
|
||||
@@ -0,0 +1,696 @@
|
||||
use crate::status::Status;
|
||||
use crate::theme;
|
||||
use hx_core::LensView;
|
||||
use hx_core::subagent::{Status as SubStatus, Sub};
|
||||
use ratatui::style::{Modifier, Style};
|
||||
use ratatui::text::{Line, Span};
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const DIAGS: usize = 6;
|
||||
const TESTS: usize = 5;
|
||||
const LOG_ROWS: usize = 8;
|
||||
const LOG_CAP: usize = 50;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Debug)]
|
||||
pub enum McpState {
|
||||
Pending,
|
||||
Ok,
|
||||
Failed,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Debug)]
|
||||
pub struct McpRow {
|
||||
pub name: String,
|
||||
pub state: McpState,
|
||||
pub tools: usize,
|
||||
pub prompts: usize,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
pub type McpStatus = Box<dyn Fn() -> Vec<McpRow> + Send>;
|
||||
|
||||
#[derive(Clone, PartialEq, Debug)]
|
||||
pub struct Consult {
|
||||
pub model: String,
|
||||
pub advising: bool,
|
||||
pub consults: u32,
|
||||
pub last: Option<(Duration, Duration)>,
|
||||
pub triggers: Vec<(String, bool)>,
|
||||
}
|
||||
|
||||
pub struct LogRing {
|
||||
start: Instant,
|
||||
items: VecDeque<(Duration, String, String)>,
|
||||
}
|
||||
|
||||
impl Default for LogRing {
|
||||
fn default() -> Self {
|
||||
LogRing {
|
||||
start: Instant::now(),
|
||||
items: VecDeque::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl LogRing {
|
||||
pub fn push(&mut self, src: impl Into<String>, text: impl Into<String>) {
|
||||
let (src, text) = (src.into(), text.into());
|
||||
if self.items.back().is_some_and(|l| l.1 == src && l.2 == text) {
|
||||
return;
|
||||
}
|
||||
if self.items.len() == LOG_CAP {
|
||||
self.items.pop_front();
|
||||
}
|
||||
self.items.push_back((self.start.elapsed(), src, text));
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.items.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.items.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct View<'a> {
|
||||
pub st: &'a Status,
|
||||
pub mode: &'a str,
|
||||
pub lens_lines: &'a [String],
|
||||
pub lens: &'a LensView,
|
||||
pub mcp: &'a [McpRow],
|
||||
pub subs: &'a [Arc<Sub>],
|
||||
pub consult: Option<&'a Consult>,
|
||||
pub log: &'a LogRing,
|
||||
pub w: usize,
|
||||
pub h: usize,
|
||||
}
|
||||
|
||||
fn short(model: &str) -> &str {
|
||||
model.strip_prefix("claude-").unwrap_or(model)
|
||||
}
|
||||
|
||||
fn clock(d: Duration) -> String {
|
||||
let s = d.as_secs();
|
||||
format!("{}:{:02}", s / 60, s % 60)
|
||||
}
|
||||
|
||||
fn tokens(n: u64) -> String {
|
||||
match n {
|
||||
n if n >= 1_000_000 => format!("{:.1}M", n as f64 / 1e6),
|
||||
n if n >= 1000 => format!("{}k", n / 1000),
|
||||
n => n.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn clip(s: &str, w: usize) -> String {
|
||||
let th = theme::t();
|
||||
if Span::raw(s).width() <= w {
|
||||
return s.to_string();
|
||||
}
|
||||
let keep = w.saturating_sub(Span::raw(th.sym.ellipsis).width());
|
||||
let mut out = String::new();
|
||||
for c in s.chars() {
|
||||
if Span::raw(format!("{out}{c}")).width() > keep {
|
||||
break;
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
out + th.sym.ellipsis
|
||||
}
|
||||
|
||||
fn fit(l: Line<'static>, w: usize) -> Line<'static> {
|
||||
if l.width() <= w {
|
||||
return l;
|
||||
}
|
||||
let mut left = w;
|
||||
let mut out = vec![];
|
||||
for s in l.spans {
|
||||
let sw = s.width();
|
||||
if sw <= left {
|
||||
left -= sw;
|
||||
out.push(s);
|
||||
continue;
|
||||
}
|
||||
out.push(Span::styled(clip(&s.content, left), s.style));
|
||||
break;
|
||||
}
|
||||
Line::from(out)
|
||||
}
|
||||
|
||||
fn bar(frac: f64, n: usize, st: Style) -> Vec<Span<'static>> {
|
||||
let th = theme::t();
|
||||
let full = ((frac.clamp(0.0, 1.0) * n as f64).round() as usize).min(n);
|
||||
vec![
|
||||
Span::styled(th.sym.bar_full.repeat(full), st),
|
||||
Span::styled(th.sym.bar_empty.repeat(n - full), th.dim()),
|
||||
]
|
||||
}
|
||||
|
||||
fn load_style(frac: f64) -> Style {
|
||||
let th = theme::t();
|
||||
match frac {
|
||||
f if f >= 0.9 => th.err(),
|
||||
f if f >= 0.7 => th.warn(),
|
||||
_ => th.accent(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn card(
|
||||
title: &str,
|
||||
right: &str,
|
||||
border: Style,
|
||||
body: Vec<Line<'static>>,
|
||||
w: usize,
|
||||
) -> Vec<Line<'static>> {
|
||||
let th = theme::t();
|
||||
let [h, v, tl, _, tr, _, _, _, bl, _, br] = th.sym.tbl;
|
||||
let inner = w.saturating_sub(2);
|
||||
let head = format!(" {title} ");
|
||||
let tail = if right.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(" {} ", clip(right, inner.saturating_sub(head.len() + 3)))
|
||||
};
|
||||
let fill = inner.saturating_sub(Span::raw(&head).width() + Span::raw(&tail).width() + 1);
|
||||
let mut out = vec![Line::from(vec![
|
||||
Span::styled(format!("{tl}{h}"), border),
|
||||
Span::styled(head, border.add_modifier(Modifier::BOLD)),
|
||||
Span::styled(h.repeat(fill), border),
|
||||
Span::styled(tail, th.sec()),
|
||||
Span::styled(tr, border),
|
||||
])];
|
||||
let cw = inner.saturating_sub(2);
|
||||
for l in body {
|
||||
let l = fit(l, cw);
|
||||
let pad = cw.saturating_sub(l.width());
|
||||
let mut spans = vec![Span::styled(format!("{v} "), border)];
|
||||
spans.extend(l.spans);
|
||||
spans.push(Span::raw(" ".repeat(pad)));
|
||||
spans.push(Span::styled(format!(" {v}"), border));
|
||||
out.push(Line::from(spans));
|
||||
}
|
||||
out.push(Line::styled(format!("{bl}{}{br}", h.repeat(inner)), border));
|
||||
out
|
||||
}
|
||||
|
||||
fn model_card(c: &View) -> Vec<Line<'static>> {
|
||||
let th = theme::t();
|
||||
let st = c.st;
|
||||
let mut b = vec![Line::from(vec![
|
||||
Span::styled(short(&st.model).to_string(), th.plain()),
|
||||
Span::styled(
|
||||
format!(
|
||||
" {} think {} {} {}",
|
||||
th.sym.info,
|
||||
st.effort.name(),
|
||||
th.sym.info,
|
||||
c.mode
|
||||
),
|
||||
th.sec(),
|
||||
),
|
||||
])];
|
||||
let frac = st.ctx_tokens as f64 / st.ctx_max.max(1) as f64;
|
||||
let mut ctx = vec![Span::styled("ctx ", th.sec())];
|
||||
ctx.extend(bar(frac, 10, load_style(frac)));
|
||||
ctx.push(Span::styled(
|
||||
format!(
|
||||
" {:.0}% {}/{}",
|
||||
frac * 100.0,
|
||||
tokens(st.ctx_tokens as u64),
|
||||
tokens(st.ctx_max as u64)
|
||||
),
|
||||
th.sec(),
|
||||
));
|
||||
b.push(Line::from(ctx));
|
||||
let u = &st.usage;
|
||||
let tot = u.input_tokens + u.cache_read_tokens + u.cache_write_tokens;
|
||||
let mut extra = vec![];
|
||||
if let Some(p) = (100 * u.cache_read_tokens).checked_div(tot) {
|
||||
extra.push(format!("cache {p}%"));
|
||||
}
|
||||
if let Some(p) = (st.pricing)(&st.model) {
|
||||
extra.push(format!("${:.2}", u.cost(&p)));
|
||||
}
|
||||
if !extra.is_empty() {
|
||||
b.push(Line::styled(
|
||||
extra.join(&format!(" {} ", th.sym.info)),
|
||||
th.sec(),
|
||||
));
|
||||
}
|
||||
if let Some(q) = &st.quota {
|
||||
for w in &q.windows {
|
||||
let f = w.used_pct / 100.0;
|
||||
let mut l = vec![Span::styled(format!("{:<4}", w.label), th.sec())];
|
||||
l.extend(bar(f, 10, load_style(f)));
|
||||
l.push(Span::styled(format!(" {:.0}%", w.used_pct), th.sec()));
|
||||
b.push(Line::from(l));
|
||||
}
|
||||
}
|
||||
card("MODEL", "", th.accent(), b, c.w)
|
||||
}
|
||||
|
||||
fn consult_card(c: &View) -> Option<Vec<Line<'static>>> {
|
||||
let k = c.consult?;
|
||||
let th = theme::t();
|
||||
let mut b = vec![Line::styled(short(&k.model).to_string(), th.plain())];
|
||||
if let Some((ago, took)) = k.last {
|
||||
b.push(Line::styled(
|
||||
format!(
|
||||
"last {} ago {} took {}",
|
||||
clock(ago),
|
||||
th.sym.info,
|
||||
clock(took)
|
||||
),
|
||||
th.sec(),
|
||||
));
|
||||
}
|
||||
if !k.triggers.is_empty() {
|
||||
let mut spans = vec![];
|
||||
for (n, on) in &k.triggers {
|
||||
if !spans.is_empty() {
|
||||
spans.push(Span::raw(" "));
|
||||
}
|
||||
let (m, st) = if *on {
|
||||
(th.sym.done, th.accent().add_modifier(Modifier::BOLD))
|
||||
} else {
|
||||
(th.sym.off, th.dim())
|
||||
};
|
||||
spans.push(Span::styled(format!("{m} {n}"), st));
|
||||
}
|
||||
b.push(Line::from(spans));
|
||||
}
|
||||
let (state, border) = if k.advising {
|
||||
("advising", th.accent())
|
||||
} else {
|
||||
("on call", th.dim())
|
||||
};
|
||||
Some(card(
|
||||
"CONSULTANT",
|
||||
&format!("{state} {} {}", th.sym.info, k.consults),
|
||||
border,
|
||||
b,
|
||||
c.w,
|
||||
))
|
||||
}
|
||||
|
||||
fn runs_card(c: &View) -> Vec<Line<'static>> {
|
||||
let th = theme::t();
|
||||
let u = &c.st.usage;
|
||||
let mut b = vec![Line::from(vec![
|
||||
Span::styled(format!("{} ", th.sym.done), th.accent()),
|
||||
Span::styled(format!("{:<8}", "main"), th.sec()),
|
||||
Span::styled(short(&c.st.model).to_string(), th.plain()),
|
||||
Span::styled(
|
||||
format!(
|
||||
" {}",
|
||||
tokens(u.input_tokens + u.cache_read_tokens + u.output_tokens)
|
||||
),
|
||||
th.dim(),
|
||||
),
|
||||
])];
|
||||
let mut running = 0;
|
||||
for s in c.subs.iter().rev().take(4).rev() {
|
||||
let (mark, st) = match s.sh.status() {
|
||||
SubStatus::Running => {
|
||||
running += 1;
|
||||
(th.sym.pending, th.accent())
|
||||
}
|
||||
SubStatus::Done => (th.sym.done, th.ok()),
|
||||
_ => (th.sym.err, th.err()),
|
||||
};
|
||||
b.push(Line::from(vec![
|
||||
Span::styled(format!("{mark} "), st),
|
||||
Span::styled(format!("{:<8}", s.sh.kind), th.sec()),
|
||||
Span::styled(short(&s.sh.model).to_string(), th.plain()),
|
||||
Span::styled(format!(" {}", clock(s.sh.elapsed())), th.dim()),
|
||||
]));
|
||||
}
|
||||
let right = if c.subs.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!("{running} running {} {} total", th.sym.info, c.subs.len())
|
||||
};
|
||||
card("MODELS RUN", &right, th.dim(), b, c.w)
|
||||
}
|
||||
|
||||
fn lsp_card(c: &View) -> Vec<Line<'static>> {
|
||||
let th = theme::t();
|
||||
let mut b = vec![];
|
||||
let (mut up, mut bad) = (0, false);
|
||||
for x in c.lens_lines {
|
||||
let (name, state) = match x.split_once(" @ ") {
|
||||
Some((n, r)) => (n.to_string(), r.rsplit_once(": ").map_or("", |p| p.1)),
|
||||
None => (x.clone(), ""),
|
||||
};
|
||||
let (mark, st, word) = if state.starts_with("running") {
|
||||
up += 1;
|
||||
(th.sym.done, th.ok(), "ready")
|
||||
} else if state.is_empty() {
|
||||
(th.sym.info, th.dim(), "")
|
||||
} else if state == "stopped" {
|
||||
(th.sym.off, th.dim(), "stopped")
|
||||
} else {
|
||||
bad = true;
|
||||
(th.sym.err, th.err(), state)
|
||||
};
|
||||
b.push(Line::from(vec![
|
||||
Span::styled(format!("{mark} "), st),
|
||||
Span::styled(format!("{name:<16}"), th.plain()),
|
||||
Span::styled(format!(" {word}"), th.sec()),
|
||||
]));
|
||||
}
|
||||
if b.is_empty() {
|
||||
b.push(Line::styled("no servers started", th.dim()));
|
||||
}
|
||||
let (errs, warns) =
|
||||
c.lens.diags.iter().fold(
|
||||
(0, 0),
|
||||
|(e, w), d| {
|
||||
if d.error { (e + 1, w) } else { (e, w + 1) }
|
||||
},
|
||||
);
|
||||
if errs + warns > 0 {
|
||||
let mut ds = c.lens.diags.clone();
|
||||
ds.sort_by_key(|d| (!d.error, d.file.clone(), d.line));
|
||||
for d in ds.iter().take(DIAGS) {
|
||||
let (mark, st) = if d.error {
|
||||
(th.sym.err, th.err())
|
||||
} else {
|
||||
(th.sym.warn, th.warn())
|
||||
};
|
||||
let file = d.file.rsplit('/').next().unwrap_or(&d.file);
|
||||
b.push(Line::from(vec![
|
||||
Span::styled(format!("{mark} "), st),
|
||||
Span::styled(format!("{file}:{} ", d.line), th.plain()),
|
||||
Span::styled(d.message.lines().next().unwrap_or("").to_string(), th.sec()),
|
||||
]));
|
||||
}
|
||||
if ds.len() > DIAGS {
|
||||
b.push(Line::styled(
|
||||
format!("{} {} more", th.sym.ellipsis, ds.len() - DIAGS),
|
||||
th.dim(),
|
||||
));
|
||||
}
|
||||
}
|
||||
let mut right = format!("{up}/{} ready", c.lens_lines.len());
|
||||
if errs + warns > 0 {
|
||||
right += &format!(
|
||||
" {} {}{errs} {}{warns}",
|
||||
th.sym.info, th.sym.err, th.sym.warn
|
||||
);
|
||||
}
|
||||
let border = if bad || errs > 0 {
|
||||
th.err()
|
||||
} else if up > 0 {
|
||||
th.ok()
|
||||
} else {
|
||||
th.dim()
|
||||
};
|
||||
card("LSP", &right, border, b, c.w)
|
||||
}
|
||||
|
||||
fn mcp_card(c: &View) -> Option<Vec<Line<'static>>> {
|
||||
if c.mcp.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let th = theme::t();
|
||||
let mut b = vec![];
|
||||
for m in c.mcp {
|
||||
let (mark, st) = match m.state {
|
||||
McpState::Ok => (th.sym.done, th.ok()),
|
||||
McpState::Pending => (th.sym.pending, th.dim()),
|
||||
McpState::Failed => (th.sym.err, th.err()),
|
||||
};
|
||||
let note = match m.state {
|
||||
McpState::Ok => format!("{} tools", m.tools),
|
||||
McpState::Pending => "connecting".into(),
|
||||
McpState::Failed => "failed".into(),
|
||||
};
|
||||
b.push(Line::from(vec![
|
||||
Span::styled(format!("{mark} "), st),
|
||||
Span::styled(format!("{:<14}", m.name), th.plain()),
|
||||
Span::styled(format!(" {note}"), th.sec()),
|
||||
]));
|
||||
if let Some(e) = &m.error {
|
||||
b.push(Line::styled(
|
||||
format!(" {}", e.lines().next().unwrap_or("")),
|
||||
th.err(),
|
||||
));
|
||||
}
|
||||
}
|
||||
let up = c.mcp.iter().filter(|m| m.state == McpState::Ok).count();
|
||||
let border = if c.mcp.iter().any(|m| m.state == McpState::Failed) {
|
||||
th.err()
|
||||
} else if up == c.mcp.len() {
|
||||
th.ok()
|
||||
} else {
|
||||
th.dim()
|
||||
};
|
||||
Some(card(
|
||||
"MCP",
|
||||
&format!("{up}/{} up", c.mcp.len()),
|
||||
border,
|
||||
b,
|
||||
c.w,
|
||||
))
|
||||
}
|
||||
|
||||
fn tests_card(c: &View) -> Option<Vec<Line<'static>>> {
|
||||
let ts = c.lens.tests.as_ref()?;
|
||||
let th = theme::t();
|
||||
let mut ts = ts.clone();
|
||||
ts.sort_by_key(|t| t.1);
|
||||
let failed = ts.iter().filter(|t| !t.1).count();
|
||||
let mut b: Vec<Line<'static>> = ts
|
||||
.iter()
|
||||
.take(TESTS)
|
||||
.map(|(n, ok)| {
|
||||
Line::from(vec![
|
||||
Span::styled(
|
||||
format!("{} ", if *ok { th.sym.ok } else { th.sym.err }),
|
||||
if *ok { th.ok() } else { th.err() },
|
||||
),
|
||||
Span::styled(n.clone(), th.plain()),
|
||||
])
|
||||
})
|
||||
.collect();
|
||||
if ts.len() > TESTS {
|
||||
b.push(Line::styled(
|
||||
format!("{} {} more", th.sym.ellipsis, ts.len() - TESTS),
|
||||
th.dim(),
|
||||
));
|
||||
}
|
||||
let border = if failed > 0 { th.err() } else { th.ok() };
|
||||
Some(card(
|
||||
"TESTS",
|
||||
&format!("{} ok {} {failed} failed", ts.len() - failed, th.sym.info),
|
||||
border,
|
||||
b,
|
||||
c.w,
|
||||
))
|
||||
}
|
||||
|
||||
fn log_card(c: &View) -> Option<Vec<Line<'static>>> {
|
||||
if c.log.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let th = theme::t();
|
||||
let skip = c.log.items.len().saturating_sub(LOG_ROWS);
|
||||
let b = c
|
||||
.log
|
||||
.items
|
||||
.iter()
|
||||
.skip(skip)
|
||||
.map(|(t, src, text)| {
|
||||
Line::from(vec![
|
||||
Span::styled(format!("{:>5} ", clock(*t)), th.dim()),
|
||||
Span::styled(format!("{src} "), th.accent()),
|
||||
Span::styled(text.clone(), th.sec()),
|
||||
])
|
||||
})
|
||||
.collect();
|
||||
Some(card(
|
||||
"SESSION LOG",
|
||||
&format!("{}", c.log.len()),
|
||||
th.dim(),
|
||||
b,
|
||||
c.w,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn lines(c: &View) -> Vec<Line<'static>> {
|
||||
let cards = [
|
||||
Some(model_card(c)),
|
||||
consult_card(c),
|
||||
Some(runs_card(c)),
|
||||
Some(lsp_card(c)),
|
||||
mcp_card(c),
|
||||
tests_card(c),
|
||||
log_card(c),
|
||||
];
|
||||
let mut out: Vec<Line<'static>> = vec![];
|
||||
for card in cards.into_iter().flatten() {
|
||||
let need = card.len() + usize::from(!out.is_empty());
|
||||
if !out.is_empty() && out.len() + need > c.h {
|
||||
break;
|
||||
}
|
||||
if !out.is_empty() {
|
||||
out.push(Line::default());
|
||||
}
|
||||
out.extend(card);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn text(ls: &[Line]) -> String {
|
||||
ls.iter()
|
||||
.map(|l| {
|
||||
l.spans
|
||||
.iter()
|
||||
.map(|s| s.content.as_ref())
|
||||
.collect::<String>()
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
fn status() -> Status {
|
||||
Status {
|
||||
auto: false,
|
||||
kind: hx_ai::auth::Kind::Claude,
|
||||
model: "claude-opus-5-5".into(),
|
||||
effort: hx_ai::Effort::Off,
|
||||
usage: Default::default(),
|
||||
ctx_tokens: 500_000,
|
||||
ctx_max: 1_000_000,
|
||||
quota: None,
|
||||
pricing: |_| None,
|
||||
}
|
||||
}
|
||||
|
||||
fn view<'a>(
|
||||
st: &'a Status,
|
||||
lens: &'a LensView,
|
||||
mcp: &'a [McpRow],
|
||||
log: &'a LogRing,
|
||||
h: usize,
|
||||
) -> View<'a> {
|
||||
View {
|
||||
st,
|
||||
mode: "auto",
|
||||
lens_lines: &[],
|
||||
lens,
|
||||
mcp,
|
||||
subs: &[],
|
||||
consult: None,
|
||||
log,
|
||||
w: 37,
|
||||
h,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cards_never_exceed_width() {
|
||||
let l = card(
|
||||
"LSP",
|
||||
"a very long right label that will not fit",
|
||||
Style::default(),
|
||||
vec![Line::raw("x".repeat(100))],
|
||||
37,
|
||||
);
|
||||
assert!(l.iter().all(|l| l.width() == 37), "{}", text(&l));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_rows_show_state_and_error() {
|
||||
let (st, lens, log) = (status(), LensView::default(), LogRing::default());
|
||||
let mcp = vec![
|
||||
McpRow {
|
||||
name: "git".into(),
|
||||
state: McpState::Ok,
|
||||
tools: 12,
|
||||
prompts: 0,
|
||||
error: None,
|
||||
},
|
||||
McpRow {
|
||||
name: "db".into(),
|
||||
state: McpState::Failed,
|
||||
tools: 0,
|
||||
prompts: 0,
|
||||
error: Some("connection refused".into()),
|
||||
},
|
||||
McpRow {
|
||||
name: "web".into(),
|
||||
state: McpState::Pending,
|
||||
tools: 0,
|
||||
prompts: 0,
|
||||
error: None,
|
||||
},
|
||||
];
|
||||
let s = text(&lines(&view(&st, &lens, &mcp, &log, 80)));
|
||||
assert!(s.contains("MCP") && s.contains("1/3 up"), "{s}");
|
||||
assert!(s.contains("git") && s.contains("12 tools"), "{s}");
|
||||
assert!(
|
||||
s.contains("connection refused") && s.contains("connecting"),
|
||||
"{s}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn log_ring_caps_and_skips_repeats() {
|
||||
let mut r = LogRing::default();
|
||||
r.push("lsp", "up");
|
||||
r.push("lsp", "up");
|
||||
assert_eq!(r.len(), 1);
|
||||
for i in 0..80 {
|
||||
r.push("x", format!("{i}"));
|
||||
}
|
||||
assert_eq!(r.len(), LOG_CAP);
|
||||
assert_eq!(r.items.back().unwrap().2, "79");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn consultant_hidden_without_data_and_marks_active_trigger() {
|
||||
let (st, lens, log) = (status(), LensView::default(), LogRing::default());
|
||||
let mut v = view(&st, &lens, &[], &log, 80);
|
||||
assert!(!text(&lines(&v)).contains("CONSULTANT"));
|
||||
let k = Consult {
|
||||
model: "claude-fable-5-2".into(),
|
||||
advising: true,
|
||||
consults: 2,
|
||||
last: Some((Duration::from_secs(7), Duration::from_secs(27))),
|
||||
triggers: vec![
|
||||
("before a plan".into(), false),
|
||||
("before done".into(), true),
|
||||
],
|
||||
};
|
||||
v.consult = Some(&k);
|
||||
let s = text(&lines(&v));
|
||||
assert!(s.contains("CONSULTANT") && s.contains("advising"), "{s}");
|
||||
assert!(
|
||||
s.contains("● before done") && s.contains("○ before a plan"),
|
||||
"{s}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn short_panels_drop_lowest_cards_first() {
|
||||
let (st, lens) = (status(), LensView::default());
|
||||
let mut log = LogRing::default();
|
||||
log.push("lsp", "up");
|
||||
let tall = text(&lines(&view(&st, &lens, &[], &log, 80)));
|
||||
assert!(tall.contains("SESSION LOG"), "{tall}");
|
||||
let short = text(&lines(&view(&st, &lens, &[], &log, 12)));
|
||||
assert!(
|
||||
short.contains("MODEL") && !short.contains("SESSION LOG"),
|
||||
"{short}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,8 @@ cargo test -q -p hx-lens rust_analyzer_turn_end >>"$log" 2>&1 || { grep -E 'FAIL
|
||||
grep -oE 'ok. [0-9]+ passed' "$log" | awk '{s+=$2} END {print s" unit tests ok"}'
|
||||
cargo build -q
|
||||
sh tests/e2e.sh
|
||||
sh tests/schema_e2e.sh
|
||||
sh tests/rpc_ask_e2e.sh
|
||||
python3 tests/tui_smoke.py | grep -q FAIL && { echo "tui smoke FAIL"; exit 1; } || echo "tui smoke ok"
|
||||
sh tests/lens_e2e.sh
|
||||
sh tests/m4_e2e.sh
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
"""RPC client for `hx --mode rpc --ask`: allows write, denies everything else.
|
||||
Usage: python3 tests/rpc_ask_client.py HX_BINARY
|
||||
"""
|
||||
import json, subprocess, sys
|
||||
|
||||
p = subprocess.Popen([sys.argv[1], "--mode", "rpc", "--ask"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
|
||||
|
||||
|
||||
def send(m):
|
||||
p.stdin.write(json.dumps({"jsonrpc": "2.0", **m}) + "\n")
|
||||
p.stdin.flush()
|
||||
|
||||
|
||||
send({"id": 1000, "method": "prompt", "params": {"text": "make hello.txt"}})
|
||||
asked = []
|
||||
while True:
|
||||
m = json.loads(p.stdout.readline())
|
||||
if m.get("method") == "permission":
|
||||
asked.append(m["params"]["tool"])
|
||||
send({"id": m["id"], "result": {"decision": "once" if m["params"]["tool"] == "write" else "deny"}})
|
||||
elif m.get("id") == 1000:
|
||||
assert "error" not in m, m
|
||||
break
|
||||
p.stdin.close()
|
||||
p.wait(timeout=30)
|
||||
assert asked and asked[0] == "write", asked
|
||||
print("asked", asked)
|
||||
@@ -0,0 +1,15 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
root=$(cd "$(dirname "$0")/.." && pwd)
|
||||
tmp=$(mktemp -d)
|
||||
trap 'kill $srv 2>/dev/null; rm -rf "$tmp"' EXIT
|
||||
port=$((20000 + ($$ + 13) % 20000))
|
||||
python3 "$root/tests/fake_anthropic.py" $port & srv=$!
|
||||
mkdir -p "$tmp/home/.hx" "$tmp/repo"
|
||||
echo '{"claude":{"access":"fake-token","refresh":"r","expires":99999999999999}}' > "$tmp/home/.hx/auth.json"
|
||||
sleep 0.5
|
||||
cd "$tmp/repo"
|
||||
export HOME="$tmp/home" HX_BASE_URL="http://127.0.0.1:$port"
|
||||
python3 "$root/tests/rpc_ask_client.py" "$root/target/debug/hx" > "$tmp/out" || { echo "FAIL: rpc ask"; cat "$tmp/out"; exit 1; }
|
||||
[ "$(cat hello.txt)" = "hi from hx" ] || { echo "FAIL: allowed write did not run"; exit 1; }
|
||||
echo "rpc ask e2e ok"
|
||||
@@ -0,0 +1,18 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
root=$(cd "$(dirname "$0")/.." && pwd)
|
||||
tmp=$(mktemp -d)
|
||||
trap 'kill $srv 2>/dev/null; rm -rf "$tmp"' EXIT
|
||||
port=$((20000 + ($$ + 7) % 20000))
|
||||
echo '[[["text","no json here"]],[["text","```json\n{\"name\":\"Ann\"}\n```"]]]' > "$tmp/turns.json"
|
||||
python3 "$root/tests/fake_anthropic.py" $port "$tmp/turns.json" & srv=$!
|
||||
mkdir -p "$tmp/home/.hx" "$tmp/repo"
|
||||
echo '{"claude":{"access":"fake-token","refresh":"r","expires":99999999999999}}' > "$tmp/home/.hx/auth.json"
|
||||
echo '{"type":"object","required":["name"],"properties":{"name":{"type":"string"}}}' > "$tmp/schema.json"
|
||||
sleep 0.5
|
||||
cd "$tmp/repo"
|
||||
export HOME="$tmp/home" HX_BASE_URL="http://127.0.0.1:$port"
|
||||
out=$("$root/target/debug/hx" -p "who" --schema "$tmp/schema.json" 2> "$tmp/err")
|
||||
[ "$out" = '{"name":"Ann"}' ] || { echo "FAIL: schema output: $out"; cat "$tmp/err"; exit 1; }
|
||||
curl -s "http://127.0.0.1:$port/" | grep -q 'does not match the schema' || { echo "FAIL: no retry prompt"; exit 1; }
|
||||
echo "schema e2e ok"
|
||||
Reference in new issue
Block a user