17 Commits
Author SHA1 Message Date
johannesandClaude Sonnet 5.5 aec92ff5a5 hx serve --acp: headless Agent Client Protocol mode
build / version (push) Successful in 13s
build / build (aarch64-apple-darwin) (push) Successful in 6m46s
build / build (x86_64-unknown-linux-musl) (push) Successful in 5m58s
build / release (push) Successful in 28s
JSON-RPC on stdio with permission requests, hx/step|message|interrupt|compact
in and hx/step_result|intent|edit|usage|decision|plan out. Sessions persist by
id. Limits are soft: a limit stop is blocked with reason "limit" and no catch;
catch is only a validated name from the step's catches list.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 13:14:32 +01:00
gitea-actions 5408db83a9 ci: bin.json v0.1.12 2026-11-14 12:13:26 +00:00
hermes 77e32bbc78 Merge pull request 'router: skip tiers whose window cannot hold the history' (#188) from fix-router-window-fit into main
build / version (push) Successful in 14s
build / build (aarch64-apple-darwin) (push) Successful in 6m30s
build / build (x86_64-unknown-linux-musl) (push) Successful in 5m40s
build / release (push) Successful in 24s
2026-11-14 12:00:36 +00:00
hermes 79cf5fcda1 agent: abort also ends a hanging request and compaction 2026-11-14 12:00:00 +00:00
gitea-actions 05dbb8e63f ci: bin.json v0.1.11 2026-11-14 11:58:50 +00:00
hermes e119dc2f0d router: skip tiers whose window cannot hold the history 2026-11-14 11:56:17 +00:00
hermes 0184627f27 Merge pull request 'plan mode (/plan, exit_plan shows full plan)' (#187) from feat/plan-mode into main
build / version (push) Successful in 14s
build / build (aarch64-apple-darwin) (push) Successful in 6m52s
build / build (x86_64-unknown-linux-musl) (push) Successful in 5m59s
build / release (push) Successful in 24s
2026-11-14 11:45:19 +00:00
hermes 5d4cdbf10d plan view: f opens the feedback input directly 2026-11-14 11:36:40 +00:00
hermes 4949a4b558 tui: DocView full-screen scroll view; plan approval opens it instead of printing the plan in chat 2026-11-14 11:36:40 +00:00
hermes fa8641f803 plan mode: pass --permission-mode plan to claude while /plan is on 2026-11-14 11:36:40 +00:00
hermes 8a9d8fe607 plan mode: show full plan before the exit prompt (claude ExitPlanMode via bridge, ask_user path) 2026-11-14 11:36:40 +00:00
hermes 36e99fc8af plan mode: /plan makes bash/write/edit read-only; exit_plan shows the full plan for approval 2026-11-14 11:36:31 +00:00
gitea-actions 1da3d52190 ci: bin.json v0.1.10 2026-11-14 10:56:12 +00:00
hermes f1b3ee0607 Merge pull request 'claude_cli: tool calls on the event bus (#182)' (#183) from feat/claude-cli-bus into main
build / version (push) Successful in 11s
build / build (aarch64-apple-darwin) (push) Successful in 6m54s
build / build (x86_64-unknown-linux-musl) (push) Successful in 6m13s
build / release (push) Successful in 29s
2026-11-14 10:42:26 +00:00
hermes ddf8bcd92c claude_cli: hx stats lists claude's tools; unknown permissions value denies in -p 2026-11-14 10:34:49 +00:00
hermes 71f05d9a0d claude_cli: ask for every Bash call too (read-only commands bypassed the bridge) 2026-11-14 10:01:49 +00:00
hermes 6978aad27a claude_cli: tool calls on the event bus, extensions can block, permissions deny/extensions-only (#182) 2026-11-13 19:38:29 +00:00
21 changed files with 1407 additions and 20 deletions

No files matched your search

Generated
+1
View File
@@ -1054,6 +1054,7 @@ dependencies = [
"hx-tui",
"serde",
"serde_json",
"similar",
"tokio",
"toml",
]
+1 -1
View File
@@ -106,7 +106,7 @@ fable = false # same as /fable on|off
Permissions: only writes ask. `write`/`edit` and unknown `bash` commands prompt; `read` and read-only `bash` (`ls cat head tail wc grep rg fd pwd echo stat file du df which tree diff`, `git status|log|diff|show|branch|blame|ls-files|rev-parse`) run freely, unless chained/redirected or a path looks secret (`.env*`, `.ssh/`, `.aws/`, `*.pem`, `*.key`, `id_rsa*`, `.netrc`, `.git-credentials`, `auth.json`), which asks first. `--yolo` skips all prompts; `/yolo` toggles it live (also while a turn runs), `!` on a permission prompt allows it and turns yolo on.
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 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.
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.
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.
+3 -3
View File
@@ -1,7 +1,7 @@
{
"version": "0.1.9",
"version": "0.1.12",
"sha256": {
"aarch64-apple-darwin": "0987c70a428b29e799ad76cad33efef37b524cde1a8cfcafd551a87073b21bb8",
"x86_64-unknown-linux-musl": "eb2b885e37df32f8878af85fb6b15513486d5583c9b0b4c71f2a2f500c9b9b97"
"aarch64-apple-darwin": "6968aaabddcfc54d7cde0df3e5fa5769fb4aeb2d8f79334661e850e39451edf5",
"x86_64-unknown-linux-musl": "3d1b524c3dabf824035486376580270bf8c0a76276ba54a4ed1b82b826869733"
}
}
+45
View File
@@ -123,6 +123,18 @@ fn tool_line(b: &Value) -> String {
format!("{name}: {d}")
}
/// Tool result content: a string or a list of `{type: "text", text}` blocks.
fn result_text(c: &Value) -> String {
match c.as_array() {
Some(a) => a
.iter()
.filter_map(|b| b["text"].as_str())
.collect::<Vec<_>>()
.join("\n"),
None => c.as_str().unwrap_or_default().to_string(),
}
}
fn usage(u: &Value) -> Usage {
let n = |k: &str| u[k].as_u64().unwrap_or(0);
Usage {
@@ -192,7 +204,13 @@ impl Provider for ClaudeCli {
let cfg = json!({"mcpServers": {"hx": {"command": c, "args": a, "env": env}}});
cmd.args(["--mcp-config", &cfg.to_string()]);
if !env.is_null() {
// reads in the project run without a prompt by default; "ask" sends them to hx too
// ponytail: unverified against a real claude (not installed on the dev box)
cmd.args(["--permission-prompt-tool", "mcp__hx__approve"]);
cmd.args([
"--settings",
r#"{"permissions":{"ask":["Bash","Read","Grep","Glob","LS"]}}"#,
]);
}
}
if PLAN.load(std::sync::atomic::Ordering::Relaxed) {
@@ -223,6 +241,8 @@ impl Provider for ClaudeCli {
// usage of the last API request: the real context size (`result` sums all requests)
let mut last: Option<Value> = None;
let mut quota = Quota::default();
// tool_use blocks by id, completed by the `user` message carrying the result
let mut uses: std::collections::HashMap<String, (String, Value)> = Default::default();
while let Ok(Some(l)) = lines.next_line().await {
let Ok(v) = serde_json::from_str::<Value>(&l) else {
continue;
@@ -261,12 +281,37 @@ impl Provider for ClaudeCli {
}
for b in v["message"]["content"].as_array().into_iter().flatten() {
if b["type"] == "tool_use" {
uses.insert(
b["id"].as_str().unwrap_or_default().into(),
(
b["name"].as_str().unwrap_or("tool").into(),
b["input"].clone(),
),
);
let _ = tx.send(Ok(StreamEvent::TextDelta {
text: format!("\n[claude {}]\n", tool_line(b)),
}));
}
}
}
Some("user") => {
for b in v["message"]["content"].as_array().into_iter().flatten() {
let id = b["tool_use_id"].as_str().unwrap_or_default();
if b["type"] != "tool_result" {
continue;
}
let Some((name, input)) = uses.remove(id) else {
continue;
};
let _ = tx.send(Ok(StreamEvent::ToolRun {
id: id.into(),
name,
input,
content: result_text(&b["content"]),
is_error: b["is_error"].as_bool().unwrap_or(false),
}));
}
}
Some("rate_limit_event") => {
if let Some(w) = window(&v) {
quota.windows.retain(|x| x.label != w.label);
+9
View File
@@ -258,6 +258,15 @@ pub enum StreamEvent {
id: String,
name: String,
},
/// A tool the provider ran itself (`claude_cli`): raw tool name and input plus its result.
/// The agent turns it into `ToolCall` / `ToolResult` events; it is not part of the message.
ToolRun {
id: String,
name: String,
input: serde_json::Value,
content: String,
is_error: bool,
},
/// Rate-limit / credit snapshot from the response headers (sent first, when present).
Quota(Quota),
Done {
+2 -1
View File
@@ -20,7 +20,8 @@ hx-tools = { version = "0.1.0", path = "../hx-tools" }
hx-mcp = { version = "0.1.0", path = "../hx-mcp" }
hx-tui = { version = "0.1.0", path = "../hx-tui" }
serde = { version = "1.0.229", features = ["derive"] }
tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "signal", "io-std", "io-util"] }
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"
+795
View File
@@ -0,0 +1,795 @@
//! Headless Agent Client Protocol server: `hx serve --acp --cwd <dir> --session <id>`.
//!
//! JSON-RPC 2.0, one message per line on stdio; the orchestrator is the client.
//! Standard ACP: `initialize`, `session/new|load`, `session/prompt`, `session/cancel`,
//! `session/update` (notifications out), `session/request_permission` (request out).
//! Orchestrator extensions: in `hx/step`, `hx/message`, `hx/interrupt`, `hx/compact`;
//! out `hx/step_result`, `hx/intent`, `hx/edit`, `hx/usage`, `hx/decision`, `hx/plan`.
//!
//! The model reports step outcome, decisions and plan in a closing ```hx-step JSON block
//! (see [`PROMPT`]); that works the same for every provider, including the `claude` CLI whose
//! tools hx does not own.
use crate::rpc::emit;
use anyhow::Result;
use async_trait::async_trait;
use hx_ai::{Pricing, StreamEvent, Usage};
use hx_core::agent::{AbortHandle, Agent, Error};
use hx_core::hook::{Event, Hook, HookAction};
use hx_core::permit::Decision;
use serde_json::{Value, json};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::SeqCst};
use std::sync::{Arc, Mutex as StdMutex};
use std::time::Duration;
use tokio::io::AsyncBufReadExt;
use tokio::sync::{Mutex, oneshot};
const PROMPT: &str = r#"
# Headless step
You run as one step of an automated pipeline. Nobody answers questions while you work: decide
yourself and state assumptions. If you cannot go on without a human answer, stop and ask it.
Lines starting with "Messages since your last step" are hints from the orchestrator; follow them.
End every step with exactly one fenced block, last in your reply:
```hx-step
{"status": "done" | "blocked" | "needs_input",
"summary": "what you did, 1-3 sentences",
"catch": "blocked only: one name from the catch list of the step, else omit",
"question": "the one question you need answered (needs_input only)",
"decisions": ["choices worth recording, e.g. token bucket over sliding window"],
"plan": {"steps": ["..."], "files": ["paths you will touch"]}}
```
`decisions` and `plan` are optional; give `plan` in planning steps. Put free text in `summary`,
never in `catch`."#;
/// Server options from the command line and the finished agent setup.
pub struct Opts {
pub session: String,
pub cwd: PathBuf,
pub pricing: Option<Pricing>,
}
/// Outgoing messages and requests waiting for the client's answer.
struct Link {
sid: String,
next: AtomicU64,
pending: StdMutex<HashMap<u64, oneshot::Sender<Value>>>,
}
impl Link {
fn notify(&self, method: &str, params: Value) {
emit(&json!({"jsonrpc": "2.0", "method": method, "params": params}));
}
fn update(&self, u: Value) {
self.notify(
"session/update",
json!({"sessionId": self.sid, "update": u}),
);
}
/// The client's whole reply message; None when the connection closed first.
async fn request(&self, method: &str, params: Value) -> Option<Value> {
let id = self.next.fetch_add(1, SeqCst);
let (tx, rx) = oneshot::channel();
self.pending
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(id, tx);
emit(&json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}));
rx.await.ok()
}
fn resolve(&self, id: &Value, msg: Value) {
let tx = id.as_u64().and_then(|n| {
self.pending
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(&n)
});
if let Some(tx) = tx {
let _ = tx.send(msg);
}
}
/// Unanswered requests fail (permissions are denied).
fn close(&self) {
self.pending
.lock()
.unwrap_or_else(|e| e.into_inner())
.clear();
}
}
fn respond(id: &Value, r: Result<Value, String>) {
if id.is_null() {
return;
}
emit(&match r {
Ok(v) => json!({"jsonrpc": "2.0", "id": id, "result": v}),
Err(e) => json!({"jsonrpc": "2.0", "id": id, "error": {"code": -32000, "message": e}}),
});
}
#[derive(Default)]
struct M {
step: Usage,
total: Usage,
/// context tokens of the last request
ctx: u64,
ctx_limit: Option<u64>,
cost_limit: Option<f64>,
/// why the run must end at the next turn boundary
stop: Option<String>,
/// hints from `hx/message`, injected at the next turn boundary
pending: Vec<String>,
/// a question the model tried to ask a human
question: Option<String>,
intent: String,
/// file contents before a write/edit call, by tool call id
before: HashMap<String, Option<String>>,
}
/// Turns bus events into ACP notifications and enforces the step limits.
struct Meter {
link: Arc<Link>,
abort: AbortHandle,
cwd: PathBuf,
pricing: Option<Pricing>,
/// context limit reported when the step sets none
window: u64,
st: StdMutex<M>,
}
fn kind(tool: &str) -> &'static str {
match tool {
"bash" => "execute",
"write" | "edit" => "edit",
"read" => "read",
"grep" | "find" | "ls" | "lsp" => "search",
"web_fetch" | "web_search" => "fetch",
_ => "other",
}
}
fn intent_of(name: &str, args: &Value) -> String {
let s = |k: &str| args[k].as_str().unwrap_or_default();
let short = |t: &str| {
t.lines()
.next()
.unwrap_or_default()
.chars()
.take(80)
.collect::<String>()
};
match name {
"bash" => format!("Running `{}`", short(s("command"))),
"edit" => format!("Editing {}", s("path")),
"write" => format!("Writing {}", s("path")),
"read" => format!("Reading {}", s("path")),
_ => format!("Using {name}"),
}
}
/// (added, removed) lines between two file contents.
fn line_diff(old: &str, new: &str) -> (usize, usize) {
use similar::{ChangeTag, TextDiff};
TextDiff::from_lines(old, new)
.iter_all_changes()
.fold((0, 0), |(a, r), c| match c.tag() {
ChangeTag::Insert => (a + 1, r),
ChangeTag::Delete => (a, r + 1),
ChangeTag::Equal => (a, r),
})
}
impl Meter {
fn m(&self) -> std::sync::MutexGuard<'_, M> {
self.st.lock().unwrap_or_else(|e| e.into_inner())
}
fn cost(&self, u: &Usage) -> f64 {
self.pricing.map_or(0.0, |p| u.cost(&p))
}
fn usage_note(&self, m: &M) {
self.link.notify(
"hx/usage",
json!({"used": m.ctx, "limit": m.ctx_limit.unwrap_or(self.window),
"cost": self.cost(&m.total)}),
);
}
fn path(&self, args: &Value) -> PathBuf {
self.cwd.join(args["path"].as_str().unwrap_or_default())
}
fn begin(&self, ctx: Option<u64>, cost: Option<f64>) {
let mut m = self.m();
m.step = Usage::default();
m.ctx_limit = ctx;
m.cost_limit = cost;
m.stop = None;
m.question = None;
}
/// Ask the run to end after the current tool round; the first reason wins.
fn stop(&self, why: impl Into<String>) {
let mut m = self.m();
m.stop.get_or_insert(why.into());
}
fn take(&self) -> (Option<String>, Option<String>) {
let mut m = self.m();
(m.stop.take(), m.question.take())
}
fn sync(&self, total: &Usage, ctx: Option<u64>) {
let mut m = self.m();
m.total = total.clone();
if let Some(c) = ctx {
m.ctx = c;
}
self.usage_note(&m);
}
fn say(&self, m: &mut M, text: String) {
if m.intent != text {
self.link.notify("hx/intent", json!(text));
m.intent = text;
}
}
}
#[async_trait]
impl Hook for Meter {
async fn on(&self, ev: &Event) -> HookAction {
match ev {
Event::Stream(StreamEvent::TextDelta { text }) => {
self.link.update(json!({
"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": text}}))
}
Event::Stream(StreamEvent::ThinkingDelta { text }) => {
self.link.update(json!({
"sessionUpdate": "agent_thought_chunk", "content": {"type": "text", "text": text}}))
}
Event::Stream(StreamEvent::Done { usage, .. }) => {
let mut m = self.m();
m.step.add(usage);
m.total.add(usage);
m.ctx = usage.input_tokens + usage.cache_read_tokens + usage.cache_write_tokens;
if let Some(l) = m.ctx_limit.filter(|l| m.ctx >= *l) {
let why = format!(
"context limit reached ({}/{l} tokens); send hx/compact",
m.ctx
);
m.stop.get_or_insert(why);
}
if let Some(l) = m.cost_limit.filter(|l| self.cost(&m.step) >= *l) {
m.stop.get_or_insert(format!("cost limit ${l:.2} reached"));
}
self.usage_note(&m);
}
Event::SubUsage(u) => {
let mut m = self.m();
m.step.add(u);
m.total.add(u);
self.usage_note(&m);
}
Event::ToolCall { id, name, args } => {
let text = intent_of(name, args);
let mut m = self.m();
self.say(&mut m, text.clone());
if matches!(name.as_str(), "write" | "edit") {
m.before
.insert(id.clone(), std::fs::read_to_string(self.path(args)).ok());
}
drop(m);
self.link
.update(json!({"sessionUpdate": "tool_call", "toolCallId": id,
"title": text, "kind": kind(name), "status": "in_progress", "rawInput": args}));
}
Event::ToolResult {
id,
args,
content,
is_error,
..
} => {
let shown: String = content.chars().take(4000).collect();
self.link.update(
json!({"sessionUpdate": "tool_call_update", "toolCallId": id,
"status": if *is_error { "failed" } else { "completed" },
"content": [{"type": "content", "content": {"type": "text", "text": shown}}]}),
);
let old = self.m().before.remove(id);
if let (false, Some(old)) = (*is_error, old) {
let p = self.path(args);
if let Ok(new) = std::fs::read_to_string(&p) {
let (added, removed) = line_diff(old.as_deref().unwrap_or_default(), &new);
let rel = p.strip_prefix(&self.cwd).unwrap_or(&p);
self.link.notify(
"hx/edit",
json!({"path": rel, "added": added, "removed": removed}),
);
}
}
}
Event::TurnEnd | Event::AgentEnd => {
let mut m = self.m();
if m.stop.is_some() {
if matches!(ev, Event::TurnEnd) {
self.abort.abort();
}
} else if !m.pending.is_empty() {
return HookAction::Inject(format!(
"Messages since your last step:\n{}",
std::mem::take(&mut m.pending)
.iter()
.map(|h| format!("- {h}"))
.collect::<Vec<_>>()
.join("\n")
));
}
}
_ => {}
}
HookAction::Continue
}
}
/// Options shown to the client for a permission request.
fn options(always: bool) -> Value {
let mut o = vec![json!({"optionId": "allow_once", "name": "Allow", "kind": "allow_once"})];
if always {
o.push(json!({"optionId": "allow_always", "name": "Allow always", "kind": "allow_always"}));
}
o.push(json!({"optionId": "reject_once", "name": "Deny", "kind": "reject_once"}));
json!(o)
}
/// `Some(option id)` when the client picked one; None = cancelled, error or connection gone.
async fn permission(
link: &Link,
mut abort: tokio::sync::watch::Receiver<bool>,
call: Value,
always: bool,
) -> Option<String> {
let params = json!({"sessionId": link.sid, "toolCall": call, "options": options(always)});
let reply = tokio::select! {
r = link.request("session/request_permission", params) => r?,
_ = async { abort.wait_for(|a| *a).await.is_ok() } => return None,
};
let o = &reply["result"]["outcome"];
(o["outcome"] == "selected")
.then(|| o["optionId"].as_str().map(String::from))
.flatten()
}
/// Wire permission, yes/no and multiple-choice questions to the client.
fn install(agent: &Agent, link: &Arc<Link>, meter: &Arc<Meter>) {
let state = &agent.cx.state;
let abort = state.abort.get().cloned();
let calls = Arc::new(AtomicU64::new(0));
let rx = move || {
abort
.clone()
.unwrap_or_else(|| tokio::sync::watch::channel(false).1)
};
{
let (link, rx, calls) = (link.clone(), rx.clone(), calls.clone());
let _ = state.permit.set(Arc::new(move |r| {
let (link, rx) = (link.clone(), rx.clone());
let n = calls.fetch_add(1, SeqCst);
Box::pin(async move {
let call = json!({"toolCallId": format!("perm-{n}"),
"title": format!("{}: {}", r.tool, r.detail), "kind": kind(&r.tool),
"status": "pending", "rawInput": {"tool": r.tool, "detail": r.detail}});
// file tools have no rule; their "always" means all edits this session
let always = !r.rule.is_empty() || matches!(r.tool.as_str(), "write" | "edit");
match permission(&link, rx(), call, always).await.as_deref() {
Some("allow_once") => Decision::Once,
Some("allow_always") if matches!(r.tool.as_str(), "write" | "edit") => {
Decision::Edits
}
Some("allow_always") => Decision::Always,
_ => Decision::Deny,
}
})
}));
}
{
let (link, rx) = (link.clone(), rx.clone());
let _ = state.ask.set(Arc::new(move |q| {
let (link, rx) = (link.clone(), rx.clone());
let n = calls.fetch_add(1, SeqCst);
Box::pin(async move {
let call = json!({"toolCallId": format!("perm-{n}"), "title": q,
"kind": "other", "status": "pending"});
permission(&link, rx(), call, false).await.as_deref() == Some("allow_once")
})
}));
}
{
// no human to answer: remember the question, the step ends as needs_input
let meter = meter.clone();
let _ = state.choose.set(Arc::new(move |q| {
meter.m().question.get_or_insert(q.text);
Box::pin(async { None })
}));
}
}
fn text_of(v: &Value) -> Option<String> {
match v {
Value::Null => None,
Value::String(s) => (!s.trim().is_empty()).then(|| s.clone()),
// ACP content blocks
Value::Array(a) if a.iter().all(|b| b["text"].is_string()) => {
let t: Vec<_> = a.iter().filter_map(|b| b["text"].as_str()).collect();
Some(t.join("\n"))
}
o => serde_json::to_string_pretty(o).ok(),
}
}
/// instruction, context and prompt of an `hx/step` as one user message.
fn compose(p: &Value) -> String {
let mut parts = vec![];
parts.extend(text_of(&p["instruction"]));
parts.extend(text_of(&p["context"]).map(|c| format!("Context:\n{c}")));
parts.extend(text_of(&p["prompt"]));
parts.join("\n\n")
}
fn num(v: &Value, keys: &[&str]) -> Option<f64> {
keys.iter().find_map(|k| v[k].as_f64()).filter(|n| *n > 0.0)
}
/// The closing ```hx-step block of a reply.
fn report(text: &str) -> Option<(Value, &str)> {
let i = text.rfind("```hx-step")?;
let rest = &text[i + "```hx-step".len()..];
let end = rest.find("```")?;
Some((
serde_json::from_str(rest[..end].trim()).ok()?,
text[..i].trim(),
))
}
fn now() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs())
}
/// `hx/step_result` payload from the model's reply; sends `hx/decision` and `hx/plan` on the way.
fn outcome(link: &Link, reply: &str, question: Option<String>, catches: &[String]) -> Value {
let (rep, body) = report(reply).unwrap_or((Value::Null, reply.trim()));
for d in rep["decisions"].as_array().into_iter().flatten() {
let (text, state) = match d {
Value::String(s) => (s.as_str(), "made"),
o => (
o["text"].as_str().unwrap_or_default(),
o["state"].as_str().unwrap_or("made"),
),
};
if !text.is_empty() {
link.notify(
"hx/decision",
json!({"text": text, "state": state, "at": now()}),
);
}
}
if rep["plan"].is_object() {
link.notify(
"hx/plan",
json!({"steps": rep["plan"]["steps"], "files": rep["plan"]["files"]}),
);
}
let mut status = rep["status"]
.as_str()
.filter(|s| matches!(*s, "done" | "blocked" | "needs_input"))
.unwrap_or(if question.is_some() {
"needs_input"
} else {
"done"
});
let q = rep["question"].as_str().map(String::from).or(question);
if status == "needs_input" && q.is_none() {
status = "blocked";
}
let mut summary: String = rep["summary"]
.as_str()
.map_or_else(|| body.chars().take(1500).collect(), String::from);
// `catch` is a name from the step's catch list, only on blocked; anything else is free text
let mut catch = Value::Null;
if let (true, Some(c)) = (status == "blocked", rep["catch"].as_str()) {
if catches.iter().any(|n| n == c) {
catch = json!(c);
} else if !c.is_empty() {
summary = format!("{summary} ({c})");
}
}
json!({"status": status, "summary": summary, "catch": catch, "question": q})
}
/// Catch names the orchestrator offers in `hx/step` (`catches`, also inside `context`).
fn catch_names(p: &Value) -> Vec<String> {
[&p["catches"], &p["context"]["catches"]]
.iter()
.find_map(|v| v.as_array())
.into_iter()
.flatten()
.filter_map(|c| c.as_str().map(String::from))
.collect()
}
struct Srv {
link: Arc<Link>,
meter: Arc<Meter>,
agent: Arc<Mutex<Agent>>,
}
/// One step; returns the `hx/step_result` payload.
async fn step(s: &Srv, p: &Value) -> Value {
// no catch: a stop that is not one of the state's catches names its reason instead
let blocked = |reason: &str, why: String| {
json!({"status": "blocked", "summary": why, "catch": null, "reason": reason,
"question": null})
};
let mut prompt = compose(p);
if prompt.is_empty() {
return blocked("error", "empty step: no prompt".into());
}
let catches = catch_names(p);
if !catches.is_empty() {
prompt.push_str(&format!(
"\n\nValid `catch` names when status is blocked: {}. Use one only if it fits.",
catches.join(", ")
));
}
let lim = &p["limits"];
let wall = num(lim, &["wall_time_secs", "wall_time", "wall_secs"]);
s.meter.begin(
num(lim, &["context_tokens", "context"]).map(|n| n as u64),
num(lim, &["cost_usd", "cost"]),
);
let mut a = s.agent.lock().await;
let r = {
let run = a.run(prompt);
tokio::pin!(run);
let deadline = async {
match wall {
Some(w) => tokio::time::sleep(Duration::from_secs_f64(w)).await,
None => std::future::pending().await,
}
};
tokio::select! {
r = &mut run => r,
_ = deadline => {
s.meter.stop(format!("wall time limit {}s reached", wall.unwrap_or_default()));
// soft stop at the next turn boundary; a stuck tool gets a grace period
tokio::select! {
r = &mut run => r,
_ = tokio::time::sleep(Duration::from_secs(30)) => {
s.meter.abort.abort();
run.await
}
}
}
}
};
let (stop, question) = s.meter.take();
s.meter.sync(a.usage(), None);
match r {
Ok(m) => outcome(&s.link, &m.text(), question, &catches),
Err(Error::Aborted) => match stop {
Some(s) if s == "interrupted" => blocked("interrupted", s),
Some(s) => blocked("limit", s),
None => blocked("cancelled", "cancelled".into()),
},
Err(e) => blocked("error", e.to_string()),
}
}
pub async fn serve(mut agent: Agent, abort: AbortHandle, o: Opts) -> Result<()> {
let link = Arc::new(Link {
sid: o.session,
next: AtomicU64::new(1),
pending: Default::default(),
});
let meter = Arc::new(Meter {
link: link.clone(),
abort: abort.clone(),
cwd: o.cwd,
pricing: o.pricing,
window: agent.compact_at() as u64,
st: Default::default(),
});
// nobody to answer exit_plan; the step reports its plan instead
agent.tools.retain(|n| n != "exit_plan");
agent.append_system(PROMPT);
install(&agent, &link, &meter);
agent.bus.add_arc(meter.clone());
let srv = Arc::new(Srv {
link: link.clone(),
meter: meter.clone(),
agent: Arc::new(Mutex::new(agent)),
});
let busy = Arc::new(AtomicBool::new(false));
let mut tasks = vec![];
let mut lines = tokio::io::BufReader::new(tokio::io::stdin()).lines();
while let Some(l) = lines.next_line().await? {
let Ok(m) = serde_json::from_str::<Value>(&l) else {
emit(&json!({"jsonrpc": "2.0", "id": null,
"error": {"code": -32700, "message": "parse error"}}));
continue;
};
let (id, p) = (m["id"].clone(), m["params"].clone());
let Some(method) = m["method"].as_str() else {
// answer to one of our requests
link.resolve(&id, m);
continue;
};
match method {
"initialize" => respond(
&id,
Ok(json!({"protocolVersion": 1, "authMethods": [],
"agentCapabilities": {"loadSession": true, "promptCapabilities": {}},
"agentInfo": {"name": "hx", "version": env!("CARGO_PKG_VERSION")}})),
),
// the session id is fixed by --session
"session/new" | "session/load" => respond(&id, Ok(json!({"sessionId": link.sid}))),
"session/cancel" => abort.abort(),
"hx/interrupt" => {
if busy.load(SeqCst) {
meter.stop("interrupted");
}
respond(&id, Ok(json!({})));
}
"hx/message" => {
match text_of(&p)
.or_else(|| text_of(&p["text"]))
.or_else(|| text_of(&p["message"]))
{
Some(t) => {
meter.m().pending.push(t);
respond(&id, Ok(json!({})));
}
None => respond(&id, Err("message text required".into())),
}
}
"hx/compact" => {
if busy.swap(true, SeqCst) {
respond(&id, Err("busy: a step is running".into()));
continue;
}
let (srv, busy) = (srv.clone(), busy.clone());
tasks.push(tokio::spawn(async move {
let mut a = srv.agent.lock().await;
let r = a.compact_now().await;
srv.meter.sync(a.usage(), Some(a.context_tokens() as u64));
busy.store(false, SeqCst);
respond(
&id,
r.map(|c| json!({"compacted": c}))
.map_err(|e| e.to_string()),
);
}));
}
"hx/step" | "session/prompt" => {
if busy.swap(true, SeqCst) {
respond(&id, Err("busy: a step is running".into()));
continue;
}
let (srv, busy) = (srv.clone(), busy.clone());
let acp = method == "session/prompt";
tasks.push(tokio::spawn(async move {
let hints = std::mem::take(&mut srv.meter.m().pending);
let mut p = p;
if !hints.is_empty() {
let h = hints.iter().map(|h| format!("- {h}")).collect::<Vec<_>>();
p["instruction"] = json!(format!(
"Messages since your last step:\n{}\n\n{}",
h.join("\n"),
text_of(&p["instruction"]).unwrap_or_default()
));
}
let out = step(&srv, &p).await;
busy.store(false, SeqCst);
srv.link.notify("hx/step_result", out.clone());
respond(
&id,
Ok(if acp {
let cancelled = out["reason"] == "cancelled";
json!({"stopReason": if cancelled { "cancelled" } else { "end_turn" }})
} else {
out
}),
);
}));
}
other => respond(&id, Err(format!("method not found: {other}"))),
}
}
// client gone: stop the running step, deny open permission requests
abort.abort();
link.close();
for t in tasks {
let _ = t.await;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn report_block_is_parsed() {
let t = "did it\n```hx-step\n{\"status\":\"blocked\",\"catch\":\"x\"}\n```";
let (v, body) = report(t).unwrap();
assert_eq!((v["status"].as_str(), body), (Some("blocked"), "did it"));
assert!(report("no block").is_none());
assert!(report("```hx-step\nnot json\n```").is_none());
}
#[test]
fn step_prompt_and_limits() {
let p = json!({"instruction": "implement", "context": {"goal": "x"}, "prompt": "go"});
let c = compose(&p);
assert!(c.starts_with("implement\n\nContext:\n{"), "{c}");
assert!(c.ends_with("\n\ngo"));
assert_eq!(
num(&json!({"cost_usd": 2.5}), &["cost_usd", "cost"]),
Some(2.5)
);
assert_eq!(num(&json!({"cost_usd": 0}), &["cost_usd"]), None);
assert_eq!(
text_of(&json!([{"type": "text", "text": "a"}])),
Some("a".into())
);
}
#[test]
fn diff_counts_lines() {
assert_eq!(line_diff("a\nb\n", "a\nc\nd\n"), (2, 1));
assert_eq!(line_diff("", "x\n"), (1, 0));
}
#[test]
fn outcome_defaults() {
let l = Link {
sid: "s".into(),
next: AtomicU64::new(1),
pending: Default::default(),
};
assert_eq!(outcome(&l, "all good", None, &[])["status"], "done");
let o = outcome(&l, "hmm", Some("which db?".into()), &[]);
assert_eq!(
(o["status"].as_str(), o["question"].as_str()),
(Some("needs_input"), Some("which db?"))
);
// needs_input without a question cannot be answered
let r = "```hx-step\n{\"status\":\"needs_input\"}\n```";
assert_eq!(outcome(&l, r, None, &[])["status"], "blocked");
}
#[test]
fn catch_must_be_a_listed_name() {
let l = Link {
sid: "s".into(),
next: AtomicU64::new(1),
pending: Default::default(),
};
let names = catch_names(&json!({"context": {"catches": ["PlanInvalid", "ToolDenied"]}}));
let blocked = |c: &str| {
let r = format!(
"```hx-step\n{{\"status\":\"blocked\",\"summary\":\"s\",\"catch\":\"{c}\"}}\n```"
);
outcome(&l, &r, None, &names)
};
assert_eq!(blocked("ToolDenied")["catch"], "ToolDenied");
let o = blocked("made up");
assert_eq!(
(o["catch"].is_null(), o["summary"].as_str()),
(true, Some("s (made up)"))
);
// caveats on a done step are not a catch
let r = "```hx-step\n{\"status\":\"done\",\"catch\":\"ToolDenied\"}\n```";
assert!(outcome(&l, r, None, &names)["catch"].is_null());
}
}
+56 -1
View File
@@ -11,6 +11,7 @@ use hx_core::switch::Switcher;
use hx_core::tool::ToolCtx;
use std::io::Write;
mod acp;
mod rpc;
use std::sync::Arc;
@@ -97,6 +98,18 @@ enum Cmd {
#[command(subcommand)]
action: ConfigAction,
},
/// Run headless for an orchestrator: Agent Client Protocol (JSON-RPC) on stdio, no TUI.
Serve {
/// Speak ACP on stdio (the only protocol so far).
#[arg(long)]
acp: bool,
/// Working directory (the worktree to edit).
#[arg(long)]
cwd: std::path::PathBuf,
/// Session id; a later `hx serve` with the same id continues that conversation.
#[arg(long)]
session: String,
},
}
#[derive(Subcommand)]
@@ -580,7 +593,29 @@ fn session_dir(cwd: &std::path::Path) -> std::path::PathBuf {
async fn main() -> Result<()> {
trace("main");
let cli = Cli::parse();
let mut acp_id = None;
match cli.cmd {
Some(Cmd::Serve { acp, cwd, session }) => {
anyhow::ensure!(acp, "hx serve: --acp is required");
// file-name safe, so the id maps to one session file
let id: String = session
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || "-_.".contains(c) {
c
} else {
'_'
}
})
.collect();
anyhow::ensure!(
!id.trim_matches('.').is_empty(),
"hx serve: --session is empty"
);
std::env::set_current_dir(&cwd)
.map_err(|e| anyhow::anyhow!("--cwd {}: {e}", cwd.display()))?;
acp_id = Some(id);
}
Some(Cmd::Login { provider }) => {
auth::login(provider).await?;
eprintln!("logged in; credentials in {}", auth::store_path().display());
@@ -595,6 +630,7 @@ async fn main() -> Result<()> {
);
print!("{}", hx_core::stats::task_report(&Session::open(&session)?));
print!("{}", hx_core::stats::route_report(&session));
print!("{}", hx_core::stats::claude_report(&session));
print!("{}", hx_core::stats::sub_report(&session));
return Ok(());
}
@@ -871,6 +907,10 @@ async fn main() -> Result<()> {
let dir = session_dir(&cwd);
let query = cli.resume.as_deref().filter(|q| !q.is_empty());
let path = match (cli.session, cli.r#continue, query) {
_ if acp_id.is_some() => dir.join(format!(
"acp-{}.jsonl",
acp_id.as_deref().unwrap_or_default()
)),
(Some(p), _, _) => p,
(None, _, Some(q)) => {
let all = hx_core::session::list(&dir);
@@ -1096,10 +1136,25 @@ async fn main() -> Result<()> {
// claude asks here (via `hx mcp-serve`) before running its tools
let (p, cx) = (hx_core::approve::sock_path(), agent.cx.clone());
let _ = CLAUDE_CX.set(cx.clone());
let bus = agent.bus.clone();
// only -p has no prompt; `permissions = "deny" | "extensions-only"` closes it
let mode = hx_core::approve::Unanswered::from_config(cfg.permissions.as_deref());
tokio::spawn(async move {
let _ = hx_core::approve::serve(&p, cx).await;
let _ = hx_core::approve::serve(&p, cx, bus, mode).await;
});
}
if let Some(id) = acp_id {
// no TUI, no prompts: every permission question goes to the orchestrator
let opts = acp::Opts {
session: id,
cwd: cwd.clone(),
pricing: pricing(agent.model()),
};
let r = acp::serve(agent, abort, opts).await;
hx_core::herdr::release().await;
mgr.shutdown().await;
return r;
}
let Some(prompt) = cli.print else {
hx_tui::run(hx_tui::Setup {
agent,
+91 -2
View File
@@ -378,6 +378,49 @@ impl Agent {
Ok(())
}
/// A tool `claude_cli` ran itself: `ToolCall` (unless the permission bridge sent it before the
/// run) and `ToolResult`, in hx' vocabulary. Informational: the tool already ran.
async fn claude_tool(
&self,
id: String,
name: &str,
input: &serde_json::Value,
content: String,
is_error: bool,
) {
let (name, args) = crate::approve::hx_call(name, input);
let seen = self
.cx
.state
.claude_seen
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(&id);
if !seen {
self.emit(Event::ToolCall {
id: id.clone(),
name: name.clone(),
args: args.clone(),
})
.await;
}
crate::stats::log_claude_tool(
self.session.path(),
&name,
args.to_string().len(),
content.len(),
is_error,
);
self.emit(Event::ToolResult {
id,
name,
args,
content,
is_error,
})
.await;
}
async fn emit(&self, ev: Event) -> crate::hook::Outcome {
self.bus.emit(ev).await
}
@@ -390,7 +433,12 @@ impl Agent {
) -> Result<futures::stream::BoxStream<'static, hx_ai::Result<StreamEvent>>, Error> {
let mut wait = self.retry_ms;
for attempt in 1..=4 {
match self.provider.stream(req.clone()).await {
let mut ab = self.abort.clone();
let r = tokio::select! {
r = self.provider.stream(req.clone()) => r,
_ = async { ab.wait_for(|a| *a).await.is_ok() } => return Err(Error::Aborted),
};
match r {
Err(hx_ai::Error::Api { status, .. }) if attempt < 4 && transient(status) => {
self.emit(Event::Info(format!(
"api error {status}; retry {attempt}/3 in {wait}ms"
@@ -434,8 +482,12 @@ impl Agent {
if self.aborted() {
return Err(Error::Aborted);
}
let mut ab = self.abort.clone();
if self.window.should_compact(&self.session.messages())
&& self.compact(KEEP_MESSAGES).await?
&& tokio::select! {
r = self.compact(KEEP_MESSAGES) => r?,
_ = async { ab.wait_for(|a| *a).await.is_ok() } => return Err(Error::Aborted),
}
{
self.emit(Event::Info("context compacted".into())).await;
}
@@ -460,6 +512,10 @@ impl Agent {
if let StreamEvent::Done { message, stop, usage } = &ev {
done = Some((message.clone(), *stop, usage.clone()));
}
if let StreamEvent::ToolRun { id, name, input, content, is_error } = ev {
self.claude_tool(id, &name, &input, content, is_error).await;
continue;
}
self.emit(Event::Stream(ev)).await;
}
None => break,
@@ -872,6 +928,39 @@ mod tests {
(r, n)
}
struct Hang;
#[async_trait]
impl Provider for Hang {
async fn stream(
&self,
_: Request,
) -> hx_ai::Result<BoxStream<'static, hx_ai::Result<StreamEvent>>> {
std::future::pending().await
}
}
#[tokio::test]
async fn abort_ends_a_request_that_never_answers() {
let dir = tempfile::tempdir().unwrap();
let cx = ToolCtx {
cwd: dir.path().into(),
state: Default::default(),
};
let (mut a, h) = Agent::new(
Arc::new(Hang),
Registry::default(),
Session::open(dir.path().join("s.jsonl")).unwrap(),
cx,
);
let t = tokio::spawn(async move {
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
h.abort();
});
let r = tokio::time::timeout(std::time::Duration::from_secs(5), a.run("go")).await;
t.await.unwrap();
assert!(matches!(r, Ok(Err(Error::Aborted))));
}
#[tokio::test]
async fn transient_api_errors_are_retried() {
let (r, n) = flaky_run(1, 529).await;
+118 -5
View File
@@ -2,6 +2,7 @@
//! calls the `approve` tool of `hx mcp-serve`, which forwards the question over a Unix socket to the
//! hx process that owns the TUI; that one shows the usual permission prompt.
use crate::hook::{Bus, Event};
use crate::permit::Request;
use crate::tool::{Tool, ToolCtx, ToolResult, gate_why};
use async_trait::async_trait;
@@ -58,8 +59,64 @@ pub fn question(tool: &str, input: &Value) -> Option<Request> {
}
}
/// Answer permission questions on `path` until the process ends.
pub async fn serve(path: &Path, cx: ToolCtx) -> std::io::Result<()> {
/// `claude_cli` tool call in hx' vocabulary (`Bash` -> `bash {command}`); other tools keep claude's name.
pub fn hx_call(tool: &str, input: &Value) -> (String, Value) {
let s = |k: &str| input[k].as_str().unwrap_or_default().to_string();
let path = || {
s(if input["file_path"].is_string() {
"file_path"
} else {
"notebook_path"
})
};
match tool {
"Bash" => ("bash".into(), json!({"command": s("command")})),
"Write" => ("write".into(), json!({"path": path()})),
"Edit" | "MultiEdit" | "NotebookEdit" => ("edit".into(), json!({"path": path()})),
"Read" => ("read".into(), json!({"path": path()})),
t => (t.into(), input.clone()),
}
}
/// What the bridge does with a call nobody answered (no permission prompt, `-p`).
/// `permissions` in config.toml: absent = allow (compatible), "deny", "extensions-only".
#[derive(Clone, Copy, Default, PartialEq, Debug)]
pub enum Unanswered {
#[default]
Allow,
Deny,
/// allow only while a live extension guards `tool_call`
ExtensionsOnly,
}
impl Unanswered {
/// Unknown values (typos) deny: this is a safety setting, failing open would hide the mistake.
/// `ask`, `auto` and `yolo` are the interactive modes and leave `-p` as it was.
pub fn from_config(s: Option<&str>) -> Self {
match s {
None | Some("ask" | "auto" | "yolo") => Self::Allow,
Some("extensions-only") => Self::ExtensionsOnly,
Some(_) => Self::Deny,
}
}
fn check(self, bus: &Bus) -> Result<(), String> {
match self {
Self::Allow => Ok(()),
Self::Deny => Err("no permission prompt available (permissions = \"deny\")".into()),
Self::ExtensionsOnly => match bus.guards() {
(n, true) if n > 0 => Ok(()),
_ => Err(
"no live extension guards tool_call (permissions = \"extensions-only\")".into(),
),
},
}
}
}
/// Answer permission questions on `path` until the process ends. Every question is first sent to
/// `bus` as a `ToolCall` (extensions can block it), then goes through the usual prompt.
pub async fn serve(path: &Path, cx: ToolCtx, bus: Bus, mode: Unanswered) -> std::io::Result<()> {
let _ = std::fs::remove_file(path);
let l = UnixListener::bind(path)?;
#[cfg(unix)]
@@ -69,7 +126,7 @@ pub async fn serve(path: &Path, cx: ToolCtx) -> std::io::Result<()> {
}
loop {
let (c, _) = l.accept().await?;
let cx = cx.clone();
let (cx, bus) = (cx.clone(), bus.clone());
tokio::spawn(async move {
let (r, mut w) = c.into_split();
let mut line = String::new();
@@ -79,7 +136,39 @@ pub async fn serve(path: &Path, cx: ToolCtx) -> std::io::Result<()> {
let v: Value = serde_json::from_str(&line).unwrap_or_default();
// hx tools run by `codemode` inside mcp-serve ask for their own permission
let mut input = None;
let ok = if v["tool_name"] == "ExitPlanMode" {
let tool = v["tool_name"].as_str().unwrap_or_default();
let unprompted = |cx: &ToolCtx| {
if cx.state.permit.get().is_none() {
mode.check(&bus)
} else {
Ok(())
}
};
let mut blocked = None;
if tool != "AskUserQuestion" && v.get("permit").is_none() {
let (name, args) = hx_call(tool, &v["input"]);
let id = v["tool_use_id"].as_str().unwrap_or_default();
if !id.is_empty() {
cx.state
.claude_seen
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(id.into());
}
let o = bus
.emit(Event::ToolCall {
id: id.into(),
name,
args,
})
.await;
blocked = o.blocked.map(|r| format!("blocked: {r}"));
}
let ok = if let Some(r) = blocked {
Err(r)
} else if let Err(r) = unprompted(&cx) {
Err(r)
} else if tool == "ExitPlanMode" {
exit_plan(&cx, v["input"]["plan"].as_str().unwrap_or_default()).await
} else if v["tool_name"] == "AskUserQuestion" {
// claude's own question tool: show hx's popup, hand the answers back as input
@@ -270,6 +359,30 @@ mod tests {
assert_eq!(question("Foo", &json!({})).unwrap().rule, "claude:Foo");
}
#[test]
fn claude_calls_use_hx_names() {
assert_eq!(
hx_call("Bash", &json!({"command": "ls", "x": 1})),
("bash".into(), json!({"command": "ls"}))
);
assert_eq!(
hx_call("MultiEdit", &json!({"file_path": "a"})),
("edit".into(), json!({"path": "a"}))
);
assert_eq!(hx_call("Read", &json!({"file_path": "a"})).0, "read");
assert_eq!(
hx_call("WebFetch", &json!({"url": "u"})),
("WebFetch".into(), json!({"url": "u"}))
);
assert_eq!(Unanswered::from_config(Some("deny")), Unanswered::Deny);
assert_eq!(Unanswered::from_config(None), Unanswered::Allow);
assert_eq!(Unanswered::from_config(Some("auto")), Unanswered::Allow);
assert_eq!(
Unanswered::from_config(Some("extrensions-only")),
Unanswered::Deny
);
}
#[tokio::test]
async fn ask_user_question_uses_popup() {
let cx = ToolCtx {
@@ -321,7 +434,7 @@ mod tests {
let path =
std::env::temp_dir().join(format!("hx-approve-test-{}.sock", std::process::id()));
let (p, c) = (path.clone(), cx.clone());
tokio::spawn(async move { serve(&p, c).await });
tokio::spawn(async move { serve(&p, c, Bus::default(), Unanswered::Allow).await });
while !path.exists() {
tokio::task::yield_now().await;
}
+6
View File
@@ -161,6 +161,12 @@ impl Extension {
#[async_trait]
impl Hook for Extension {
fn guard(&self) -> Option<bool> {
self.subscribe
.iter()
.any(|s| s == "tool_call" || s == "*")
.then(|| self.alive.load(Ordering::SeqCst))
}
async fn on(&self, ev: &Event) -> HookAction {
if !self.subscribe.iter().any(|s| s == ev.kind() || s == "*") {
return HookAction::Continue;
+20 -5
View File
@@ -100,11 +100,16 @@ pub enum HookAction {
#[async_trait]
pub trait Hook: Send + Sync {
async fn on(&self, ev: &Event) -> HookAction;
/// `Some(alive)` if this hook guards `tool_call` (extensions subscribed to it).
fn guard(&self) -> Option<bool> {
None
}
}
/// Clones share the hook list (the permission bridge emits on the agent's bus).
#[derive(Default, Clone)]
pub struct Bus {
hooks: Vec<Arc<dyn Hook>>,
hooks: Arc<std::sync::RwLock<Vec<Arc<dyn Hook>>>>,
}
/// Aggregate outcome of dispatching one event to all hooks.
@@ -117,19 +122,29 @@ pub struct Outcome {
impl Bus {
pub fn add_arc(&mut self, h: Arc<dyn Hook>) -> &mut Self {
self.hooks.push(h);
self.hooks
.write()
.unwrap_or_else(|e| e.into_inner())
.push(h);
self
}
pub fn add(&mut self, h: impl Hook + 'static) -> &mut Self {
self.hooks.push(Arc::new(h));
self
self.add_arc(Arc::new(h))
}
/// (number of `tool_call` guards, all of them alive).
pub fn guards(&self) -> (usize, bool) {
let hooks = self.hooks.read().unwrap_or_else(|e| e.into_inner());
let g: Vec<bool> = hooks.iter().filter_map(|h| h.guard()).collect();
(g.len(), g.iter().all(|a| *a))
}
/// Hooks run in registration order. First `Block` wins; `Mutate` is visible to later hooks.
pub async fn emit(&self, ev: Event) -> Outcome {
let mut ev = ev;
let mut o = Outcome::default();
for h in &self.hooks {
let hooks = self.hooks.read().unwrap_or_else(|e| e.into_inner()).clone();
for h in &hooks {
match h.on(&ev).await {
HookAction::Continue => {}
HookAction::Block(r) => {
+2
View File
@@ -86,6 +86,8 @@ pub struct State {
/// ponytail: keyed by command text, so two identical commands running at once share a tail;
/// key by call id once ToolCtx carries it.
pub live: Mutex<HashMap<String, String>>,
/// `claude_cli` tool_use ids the permission bridge already put on the bus.
pub claude_seen: Mutex<std::collections::HashSet<String>>,
/// Structured last lens report for side panels.
pub lens: Mutex<LensView>,
}
+28 -2
View File
@@ -371,7 +371,20 @@ impl Router {
}
};
let prefer = self.cur.map_or(start, |(k, _)| k);
let (kind, model) = pick_for(tier, prefer, avoid, models, &self.cfg)?;
let (mut kind, mut model) = pick_for(tier, prefer, avoid, models, &self.cfg)?;
// the history must fit the window (a 1M session cannot go down to a 200k Haiku)
let mut tier = tier;
while (hx_ai::models::window(models, &model) as usize) * 9 / 10 < sig.ctx {
let up = match tier {
Tier::Fast => Tier::Balanced,
Tier::Balanced => Tier::Deep,
_ => break,
};
let Some((k, m)) = pick_for(up, kind, avoid, models, &self.cfg) else {
break;
};
(tier, kind, model) = (up, k, m);
}
// no Fable in the catalog: it ran as Deep
let tier = if tier == Tier::Max && Tier::of(&model) != Some(Tier::Max) {
Tier::Deep
@@ -485,7 +498,7 @@ mod tests {
ModelInfo {
id: id.into(),
kind,
context_window: 1,
context_window: 1_000_000,
}
}
@@ -635,6 +648,19 @@ mod tests {
);
}
#[test]
fn history_too_big_for_the_window_skips_the_small_tier() {
let mut r = Router::new(Cfg::default());
let mut light = signals("commit", &[]);
assert_eq!(light.tier, Tier::Fast);
light.ctx = 250_000;
let mut c = cat();
c[2].context_window = 200_000;
c[1].context_window = 1_000_000;
let p = r.route(&light, Kind::Claude, None, &c).unwrap();
assert_eq!(p.model, "claude-sonnet-5-5");
}
#[test]
fn effort_follows_score_and_provider() {
assert_eq!(effort_for(-2, Kind::Claude), Effort::Off);
+67
View File
@@ -46,6 +46,57 @@ pub fn task_report(s: &Session) -> String {
)
}
/// Append one `claude_cli` tool run to `<session>.claude` (claude runs the tools itself, so they
/// are not session messages). Best effort.
pub fn log_claude_tool(
session: &std::path::Path,
name: &str,
args: usize,
result: usize,
err: bool,
) {
use std::io::Write;
if let Ok(mut f) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(session.with_extension("claude"))
{
let _ = writeln!(
f,
"{}",
serde_json::json!({"name": name, "args": args, "result": result, "error": err})
);
}
}
/// Tools claude ran itself (`<session>.claude`): calls, errors/blocks, argument and result bytes per tool.
pub fn claude_report(session: &std::path::Path) -> String {
let Ok(t) = std::fs::read_to_string(session.with_extension("claude")) else {
return String::new();
};
let mut by: std::collections::BTreeMap<String, [u64; 4]> = Default::default();
for v in t
.lines()
.filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok())
{
let e = by
.entry(v["name"].as_str().unwrap_or("?").into())
.or_default();
e[0] += 1;
e[1] += u64::from(v["error"] == true);
e[2] += v["args"].as_u64().unwrap_or(0);
e[3] += v["result"].as_u64().unwrap_or(0);
}
let mut s = String::from("claude tool calls (run by claude, not in the message history):\n");
for (n, [c, e, a, r]) in by {
let _ = writeln!(
s,
" {n}: {c} calls, {e} errors/blocked, args {a} B, results {r} B"
);
}
s
}
/// One line per subagent log in `<session>.sub/` (empty when there are none).
/// Auto-mode choices from `<session>.route`: turns per tier, how often the tier was held back
/// or forced, and how often the next prompt had to go up again (a pick that was too low).
@@ -406,6 +457,22 @@ pub fn report(s: &Session) -> String {
#[cfg(test)]
mod tests {
#[test]
fn claude_tools_are_counted() {
let p = std::env::temp_dir().join(format!("hx-claude-stats-{}.jsonl", std::process::id()));
let c = p.with_extension("claude");
let _ = std::fs::remove_file(&c);
assert_eq!(super::claude_report(&p), "");
super::log_claude_tool(&p, "bash", 10, 100, false);
super::log_claude_tool(&p, "bash", 10, 20, true);
let r = super::claude_report(&p);
let _ = std::fs::remove_file(&c);
assert!(
r.contains("bash: 2 calls, 1 errors/blocked, args 20 B, results 120 B"),
"{r}"
);
}
use super::*;
use hx_ai::{Message, Usage};
+83
View File
@@ -0,0 +1,83 @@
"""Fake orchestrator for `hx serve --acp`: drives hx over stdio and checks the protocol.
Usage: python3 tests/acp_client.py HX_BIN REPO SESSION_ID PORT
Scenario (against tests/fake_anthropic.py with acp_turns.json):
run 1: step with context limit 1 -> permission asked, edit done, step ends blocked (limit)
step 2 -> done, decision + plan reported
run 2 (new process, same session) -> step 3 sees the earlier conversation
"""
import json, subprocess, sys, urllib.request
hx, repo, sid, port = sys.argv[1:5]
seen = [] # every notification and request from hx, in order
class Hx:
def __init__(self):
self.p = subprocess.Popen([hx, "serve", "--acp", "--cwd", repo, "--session", sid],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
self.n = 0
def send(self, m):
self.p.stdin.write(json.dumps({"jsonrpc": "2.0", **m}) + "\n")
self.p.stdin.flush()
def call(self, method, params):
self.n += 1
self.send({"id": self.n, "method": method, "params": params})
while True:
line = self.p.stdout.readline()
assert line, "hx closed stdout"
m = json.loads(line)
if "method" in m:
seen.append(m)
if "id" in m: # permission request: allow once
assert m["method"] == "session/request_permission", m
self.send({"id": m["id"], "result": {"outcome": {"outcome": "selected", "optionId": "allow_once"}}})
elif m.get("id") == self.n:
assert "error" not in m, m
return m["result"]
def close(self):
self.p.stdin.close()
assert self.p.wait(timeout=30) == 0
def notes(method):
return [m["params"] for m in seen if m["method"] == method]
a = Hx()
init = a.call("initialize", {"protocolVersion": 1})
assert init["agentInfo"]["name"] == "hx", init
assert a.call("session/new", {"cwd": repo, "mcpServers": []})["sessionId"] == sid
r = a.call("hx/step", {"prompt": "write hello.txt", "instruction": "implement", "context": {"goal": "demo"},
"limits": {"context_tokens": 1}})
assert r["status"] == "blocked" and r["catch"] is None and r["reason"] == "limit" and "context limit" in r["summary"], r
perm = [m for m in seen if m["method"] == "session/request_permission"]
assert perm and perm[0]["params"]["options"][0]["optionId"] == "allow_once", perm
assert open(f"{repo}/hello.txt").read() == "hi from hx\n"
assert {"path": "hello.txt", "added": 1, "removed": 0} in notes("hx/edit"), notes("hx/edit")
assert any("hello.txt" in i for i in notes("hx/intent")), notes("hx/intent")
assert notes("hx/usage") and notes("hx/usage")[0]["used"] > 0, notes("hx/usage")
assert notes("hx/step_result")[0] == r
a.call("hx/message", "prefer small commits")
r = a.call("hx/step", {"prompt": "now summarize"})
assert r["status"] == "done" and r["summary"] == "wrote hello.txt", r
assert [d["text"] for d in notes("hx/decision")] == ["token bucket over sliding window"]
assert notes("hx/plan") == [{"steps": ["write", "test"], "files": ["hello.txt"]}], notes("hx/plan")
assert a.call("hx/interrupt", {}) == {}
a.close()
b = Hx()
b.call("initialize", {"protocolVersion": 1})
r = b.call("hx/step", {"prompt": "what did you do before?"})
assert r["status"] == "done", r
b.close()
log = json.load(urllib.request.urlopen(f"http://127.0.0.1:{port}/"))
text = json.dumps(log[-1]["body"]["messages"])
assert "write hello.txt" in text and "wrote hello.txt" in text, "session not continued"
assert "prefer small commits" in json.dumps(log[1]["body"]["messages"]), "hint not delivered"
print("acp e2e ok")
+15
View File
@@ -0,0 +1,15 @@
#!/bin/sh
# ACP e2e: `hx serve --acp` driven by a fake orchestrator (tests/acp_client.py) against a fake Anthropic API:
# permission requests, hx/edit|usage|intent|decision|plan|step_result, limits, hx/message, session continuation.
set -eu
root=$(cd "$(dirname "$0")/.." && pwd)
tmp=$(mktemp -d)
trap 'kill $srv 2>/dev/null; rm -rf "$tmp"' EXIT
port=$((20000 + $$ % 20000))
python3 "$root/tests/fake_anthropic.py" $port "$root/tests/acp_turns.json" & srv=$!
mkdir -p "$tmp/home/.hx" "$tmp/repo"
echo '{"claude":{"access":"fake-token","refresh":"r","expires":99999999999999}}' > "$tmp/home/.hx/auth.json"
printf 'claude_cli = false\n[lsp]\nmode = "off"\ntests = "off"\n' > "$tmp/home/.hx/config.toml"
sleep 0.5
export HOME="$tmp/home" HX_BASE_URL="http://127.0.0.1:$port"
python3 "$root/tests/acp_client.py" "$root/target/debug/hx" "$tmp/repo" demo-1 $port
+5
View File
@@ -0,0 +1,5 @@
[
[["tool_use", {"id": "t1", "name": "Write", "input": {"path": "hello.txt", "content": "hi from hx\n"}}]],
[["text", "Done.\n```hx-step\n{\"status\":\"done\",\"summary\":\"wrote hello.txt\",\"decisions\":[\"token bucket over sliding window\"],\"plan\":{\"steps\":[\"write\",\"test\"],\"files\":[\"hello.txt\"]}}\n```"]],
[["text", "```hx-step\n{\"status\":\"done\",\"summary\":\"as before\"}\n```"]]
]
+25
View File
@@ -13,4 +13,29 @@ export HOME="$tmp/home" HX_CLAUDE_BIN="$root/tests/fake_claude.py" FAKE_CLAUDE_L
grep -q "claude Bash: echo hi-from-tool" "$tmp/out" && grep -q "approve: allow" "$tmp/out" || { echo "FAIL text"; cat "$tmp/out" "$tmp/err"; exit 1; }
grep -q '"--permission-prompt-tool"' "$tmp/argv" && grep -q '"--mcp-config"' "$tmp/argv" && grep -q '"stream-json"' "$tmp/argv" || { echo "FAIL argv"; cat "$tmp/argv"; exit 1; }
grep -q "cm-ok" "$tmp/out" || { echo "FAIL codemode"; cat "$tmp/out" "$tmp/err"; exit 1; }
# bridge goes through the bus: an extension blocks a secret Read and `curl`; tool events reach NDJSON
cd "$tmp/repo"
export FAKE_ASK=1
timeout 20 "$root/target/debug/hx" -p "go" --mode json -s "$tmp/s2.jsonl" > "$tmp/o2" 2> "$tmp/e2" || { echo "FAIL ask run"; cat "$tmp/e2"; exit 1; }
python3 - "$tmp/o2" allow <<'PY' || { echo "FAIL events (no extension)"; exit 1; }
import json, sys
ev = [json.loads(l) for l in open(sys.argv[1]) if l.startswith("{")]
calls = [(e["name"], e["id"]) for e in ev if e["type"] == "tool_call"]
res = [e for e in ev if e["type"] == "tool_result"]
assert calls == [("read", "t1"), ("bash", "t2")], calls
assert [r["is_error"] for r in res] == [False, False] and "allow" in res[1]["content"], res
PY
"$root/target/debug/hx" stats "$tmp/s2.jsonl" | grep -q "bash: 1 calls, 0 errors" || { echo "FAIL stats"; "$root/target/debug/hx" stats "$tmp/s2.jsonl"; exit 1; }
printf 'claude_cli = []\n[lsp]\nmode = "off"\ntests = "off"\n[[extensions]]\ncommand = ["python3", "%s/tests/ext_block_all.py"]\n' "$root" > "$tmp/home/.hx/config.toml"
timeout 20 "$root/target/debug/hx" -p "go" --mode json -s "$tmp/s3.jsonl" > "$tmp/o3" 2> "$tmp/e3" || { echo "FAIL ext run"; cat "$tmp/e3"; exit 1; }
python3 - "$tmp/o3" <<'PY' || { echo "FAIL events (extension)"; cat "$tmp/e3"; exit 1; }
import json, sys
ev = [json.loads(l) for l in open(sys.argv[1]) if l.startswith("{")]
res = [e for e in ev if e["type"] == "tool_result"]
assert len(res) == 2 and all(r["is_error"] and "blocked: guard: " in r["content"] for r in res), res
PY
# a dead guard must not leave the run open under permissions = "extensions-only"
printf 'claude_cli = []\npermissions = "extensions-only"\n[lsp]\nmode = "off"\ntests = "off"\n' > "$tmp/home/.hx/config.toml"
timeout 20 "$root/target/debug/hx" -p "go" --mode json -s "$tmp/s4.jsonl" > "$tmp/o4" 2> "$tmp/e4" || { echo "FAIL deny run"; cat "$tmp/e4"; exit 1; }
grep -q 'extensions-only' "$tmp/o4" && ! grep -q '"content":"allow' "$tmp/o4" || { echo "FAIL extensions-only"; cat "$tmp/o4"; exit 1; }
echo "claude cli e2e ok"
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env python3
"""Test extension: subscribes to tool_call, blocks `read` of secrets and `bash` curl."""
import json, sys
for line in sys.stdin:
m = json.loads(line)
if m["method"] == "initialize":
r = {"subscribe": ["tool_call"], "tools": []}
else:
e = m["params"]["event"]
bad = (e["name"] == "read" and ".ssh" in e["args"]["path"]) or (e["name"] == "bash" and "curl" in e["args"]["command"])
r = {"action": "block", "reason": "guard: " + e["name"]} if bad else {"action": "continue"}
print(json.dumps({"jsonrpc": "2.0", "id": m["id"], "result": r}), flush=True)
+23
View File
@@ -6,6 +6,29 @@ if "--version" in sys.argv:
print("fake"); sys.exit(0)
def out(o): print(json.dumps(o), flush=True)
reply = "hello from claude"
if os.environ.get("FAKE_ASK"): # ask hx about a secret Read and `curl x` (ids t1/t2); report the answers
import subprocess
cfg = json.loads(sys.argv[sys.argv.index("--mcp-config") + 1])["mcpServers"]["hx"]
p = subprocess.Popen([cfg["command"], *cfg["args"]], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
text=True, env={**os.environ, **cfg["env"]})
asks = [("t1", "Read", {"file_path": "/home/u/.ssh/id_rsa"}), ("t2", "Bash", {"command": "curl x"})]
p.stdin.write(json.dumps({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}) + "\n")
p.stdin.flush()
p.stdout.readline()
ans = []
for i, (tid, n, inp) in enumerate(asks): # one at a time: deterministic order
p.stdin.write(json.dumps({"jsonrpc": "2.0", "id": 10 + i, "method": "tools/call", "params": {"name": "approve",
"arguments": {"tool_name": n, "input": inp, "tool_use_id": tid}}}) + "\n")
p.stdin.flush()
ans.append(json.loads(json.loads(p.stdout.readline())["result"]["content"][0]["text"]))
p.stdin.close()
out({"type": "system", "subtype": "init", "session_id": "S1"})
for (tid, n, inp), a in zip(asks, ans):
out({"type": "assistant", "session_id": "S1", "message": {"content": [{"type": "tool_use", "id": tid, "name": n, "input": inp}]}})
out({"type": "user", "session_id": "S1", "message": {"content": [{"type": "tool_result", "tool_use_id": tid,
"content": a["behavior"] + ": " + a.get("message", ""), "is_error": a["behavior"] == "deny"}]}})
out({"type": "result", "session_id": "S1", "is_error": False, "result": "done", "usage": {"input_tokens": 1, "output_tokens": 1}})
sys.exit(0)
if "--permission-prompt-tool" in sys.argv: # act like claude: ask hx whether `rm -rf x` may run
import subprocess
cfg = json.loads(sys.argv[sys.argv.index("--mcp-config") + 1])["mcpServers"]["hx"]