diff --git a/Cargo.lock b/Cargo.lock index 2411259..4f4a50c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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" diff --git a/README.md b/README.md index 0daac8e..0a76774 100644 --- a/README.md +++ b/README.md @@ -231,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: @@ -257,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 diff --git a/crates/hx-cli/Cargo.toml b/crates/hx-cli/Cargo.toml index 2aeefc0..dca78c7 100644 --- a/crates/hx-cli/Cargo.toml +++ b/crates/hx-cli/Cargo.toml @@ -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 diff --git a/crates/hx-cli/src/config.sample.toml b/crates/hx-cli/src/config.sample.toml index 488fe2d..2aee308 100644 --- a/crates/hx-cli/src/config.sample.toml +++ b/crates/hx-cli/src/config.sample.toml @@ -5,7 +5,8 @@ # 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 # subagent_parallel = 3 # subagents running at once # subagent_max_turns = 40 # turn limit per subagent (an agent file's max_turns wins) diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index 1e60843..e750c2a 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -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, + #[arg( + long, + requires = "print", + help = "JSON schema file: the final answer must match it (one retry); prints only the JSON" + )] + schema: Option, } #[derive(Clone, Copy, PartialEq, clap::ValueEnum)] @@ -154,6 +171,7 @@ struct Config { codex_model: Option, compact_at: Option, max_tokens: Option, + max_turns: Option, explore_model: Option, subagents: Option, subagent_parallel: Option, @@ -222,6 +240,7 @@ 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), @@ -1137,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); @@ -1161,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; @@ -1321,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 { @@ -1331,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}), ); } @@ -1359,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(()) } diff --git a/crates/hx-cli/src/rpc.rs b/crates/hx-cli/src/rpc.rs index 61987f5..de28cc3 100644 --- a/crates/hx-cli/src/rpc.rs +++ b/crates/hx-cli/src/rpc.rs @@ -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) { }); } +type Pending = + Arc>>>; + +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, pub files: Vec, 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" { diff --git a/crates/hx-cli/src/schema.rs b/crates/hx-cli/src/schema.rs new file mode 100644 index 0000000..0524c89 --- /dev/null +++ b/crates/hx-cli/src/schema.rs @@ -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 { + 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 { + let v = extract(answer).ok_or("the answer is not valid JSON")?; + let errs: Vec = 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 { + 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()); + } +} diff --git a/tests/all.sh b/tests/all.sh index 7826c2a..8f0c7bc 100755 --- a/tests/all.sh +++ b/tests/all.sh @@ -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 diff --git a/tests/rpc_ask_client.py b/tests/rpc_ask_client.py new file mode 100644 index 0000000..4fbb058 --- /dev/null +++ b/tests/rpc_ask_client.py @@ -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) diff --git a/tests/rpc_ask_e2e.sh b/tests/rpc_ask_e2e.sh new file mode 100644 index 0000000..c9b0f99 --- /dev/null +++ b/tests/rpc_ask_e2e.sh @@ -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" diff --git a/tests/schema_e2e.sh b/tests/schema_e2e.sh new file mode 100644 index 0000000..283a468 --- /dev/null +++ b/tests/schema_e2e.sh @@ -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"