From 1f2486a5997c2400dce8468ea76fb3264350c7c4 Mon Sep 17 00:00:00 2001 From: Johannes Kresner Date: Sat, 14 Nov 2026 13:13:49 +0100 Subject: [PATCH] Route hx limit stops to on_budget, accept _hx/ methods, send catches A blocked step result with reason "limit" and no catch now takes the same path as an orchestrator budget stop. Other blocked reasons keep the normal catch path. hx/step context now lists the state's catch names so hx can pick a valid one. Co-Authored-By: Claude Sonnet 5.5 --- src/acp.rs | 8 ++++ src/runner.rs | 101 ++++++++++++++++++++++++++++++++++++++----- tests/fake_acp_hx.py | 8 ++++ 3 files changed, 107 insertions(+), 10 deletions(-) diff --git a/src/acp.rs b/src/acp.rs index 7a27365..f0fae9c 100644 --- a/src/acp.rs +++ b/src/acp.rs @@ -44,6 +44,8 @@ pub struct StepResult { /// done | blocked | needs_input pub status: String, pub catch: Option, + /// Why a step is `blocked` without a catch; `"limit"` means hx hit a limit passed in `hx/step`. + pub reason: Option, pub question: Option, pub summary: String, } @@ -145,6 +147,11 @@ impl Acp { let Some(method) = m["method"].as_str() else { return Ok(None); // a late response (e.g. the ack of hx/step) }; + // ACP reserves a leading `_` for custom methods: `_hx/intent` is the same as `hx/intent` + let method = method + .strip_prefix('_') + .filter(|r| r.starts_with("hx/")) + .unwrap_or(method); let params = &m["params"]; if m.get("id").is_some() { // a request from hx @@ -166,6 +173,7 @@ impl Acp { return Ok(Some(StepResult { status: s("status").unwrap_or_default(), catch: s("catch"), + reason: s("reason"), question: s("question"), summary: s("summary").unwrap_or_default(), })); diff --git a/src/runner.rs b/src/runner.rs index 6e76e40..bb5213e 100644 --- a/src/runner.rs +++ b/src/runner.rs @@ -184,6 +184,20 @@ impl<'a> Ctl<'a> { } } + /// Goes to `on_budget`, or ends the session as failed when the machine has none. + fn stop_for_budget(&self, detail: String) { + self.set_stop(match &self.on_budget { + Some(s) => Stop::Goto { + state: s.clone(), + why: "budget".into(), + }, + None => Stop::End { + status: "failed", + reason: format!("budget: {detail}"), + }, + }); + } + fn stopped(&self) -> bool { self.stop.borrow().is_some() } @@ -275,16 +289,7 @@ impl<'a> Ctl<'a> { "budget", json!({"what": x.what, "used": x.used, "limit": x.limit}), )?; - self.set_stop(match &self.on_budget { - Some(s) => Stop::Goto { - state: s.clone(), - why: "budget".into(), - }, - None => Stop::End { - status: "failed", - reason: format!("budget: {} {} > {}", x.what, x.used, x.limit), - }, - }); + self.stop_for_budget(format!("{} {} > {}", x.what, x.used, x.limit)); p.interrupt = true; } } @@ -661,6 +666,7 @@ fn run_agent(cx: &mut Ctx, st: &State, step: &Step) -> Result { loop { let context = json!({ "state": st.name, "last_failure": last_failure(cx.db, &cx.s.id)?, "hint": hint, + "catches": st.catch.keys().collect::>(), }); let mut sink = DbSink { db: cx.db, @@ -699,6 +705,16 @@ fn run_agent(cx: &mut Ctx, st: &State, step: &Step) -> Result { out: r.summary, catch: None, }), + "blocked" if r.catch.is_none() && r.reason.as_deref() == Some("limit") => { + // hx stopped on a limit from hx/step: same path as an orchestrator budget + cx.db.emit( + &cx.s.id, + "budget", + json!({"what": "hx limit", "used": "reached", "limit": r.summary}), + )?; + cx.ctl.stop_for_budget(format!("hx limit: {}", r.summary)); + Err(Stopped.into()) + } "blocked" => Ok(StepRes { ok: false, exit: None, @@ -1422,6 +1438,10 @@ next = "done" .filter(|m| m["method"] == "hx/step") .collect(); assert_eq!(steps.len(), 3); + assert_eq!( + steps[0]["params"]["context"]["catches"], + json!(["PlanInvalid"]) + ); let ctx = &steps[2]["params"]["context"]["last_failure"]; assert_eq!(ctx["state"], "build"); assert!(ctx["output"].as_str().unwrap().contains("boom-output")); @@ -1896,6 +1916,67 @@ next = "done" let _ = std::fs::remove_dir_all(&e.dir); } + const LIMIT_MACHINE: &str = r#"name = "m" +on_abort = "aborted" +on_budget = "stuck" +[[state]] +name = "a" +kind = "start" +steps = [{ name = "ag", run = "agent", prompt = "implement" }] +next = "done" +"#; + + #[test] + fn hx_blocked_with_reason_limit_goes_to_on_budget() { + let e = env("hx-limit"); + let m = ctl_machine(LIMIT_MACHINE); + create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); + let p = fake("FAKE_MODE=limit"); + assert_eq!( + run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(), + "escalated" + ); + let ev = e.db.events(Some("s1"), 0).unwrap(); + assert_eq!(ev.iter().filter(|v| v.kind == "budget").count(), 1); + let g = ev.iter().find(|v| v.kind == "goto").unwrap(); + assert_eq!( + (g.payload["to"].as_str(), g.payload["why"].as_str()), + (Some("stuck"), Some("budget")) + ); + let _ = std::fs::remove_dir_all(&e.dir); + } + + #[test] + fn hx_blocked_with_another_reason_is_not_a_budget() { + let e = env("hx-error"); + let m = ctl_machine(LIMIT_MACHINE); + create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); + let p = fake("FAKE_MODE=error"); + assert_eq!( + run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(), + "failed" + ); + let ev = e.db.events(Some("s1"), 0).unwrap(); + assert!(ev.iter().all(|v| v.kind != "budget" && v.kind != "goto")); + let _ = std::fs::remove_dir_all(&e.dir); + } + + #[test] + fn underscore_prefixed_hx_methods_are_accepted() { + let e = env("underscore"); + let m = one_step(r#"{ name = "ag", run = "agent", prompt = "implement" }"#); + create(&e.db, &e.dir.join("wt"), "t", "", "m").unwrap(); + let p = fake("FAKE_UNDERSCORE=1"); + assert_eq!( + run_session(&e.db, &m, "s1", &e.repo, "", &p).unwrap(), + "merged" + ); + let kinds = kinds(&e.db, "s1"); + assert!(kinds.contains(&"intent".to_string()) && kinds.contains(&"edit".to_string())); + assert_eq!(e.db.decision_count("s1").unwrap(), 1); + let _ = std::fs::remove_dir_all(&e.dir); + } + #[test] fn a_budget_without_on_budget_fails_the_session() { let e = env("budget-fail"); diff --git a/tests/fake_acp_hx.py b/tests/fake_acp_hx.py index 09df6c5..afadd94 100644 --- a/tests/fake_acp_hx.py +++ b/tests/fake_acp_hx.py @@ -8,7 +8,10 @@ Behaviour per `hx/step`, chosen with FAKE_MODE (orch passes FAKE_* through the p permission asks session/request_permission first and records the answer in permission.txt slow works until hx/interrupt (records hx/message and hx/compact in messages.txt / compact.txt), then answers done; a retried step with context.hint finishes at once + limit step_result blocked, no catch, reason "limit" (hx hit a limit from hx/step) + error step_result blocked, no catch, reason "error" crash exits without a step_result +FAKE_UNDERSCORE=1 sends every custom method as `_hx/...`. FAKE_USAGE="ctx_used,ctx_limit,cost" makes every step report that usage first. Every received message is appended to FAKE_LOG when set. Each step also appends its prompt kind to steps.txt. """ @@ -29,6 +32,8 @@ def send(o): def note(method, params): + if os.environ.get("FAKE_UNDERSCORE") and method.startswith("hx/"): + method = "_" + method send({"method": method, "params": params}) @@ -85,6 +90,9 @@ def step(params): if mode == "needs_input" and not params.get("context", {}).get("hint"): note("hx/step_result", {"status": "needs_input", "question": "Which provider?"}) return + if mode in ("limit", "error"): # blocked without a catch, only the reason differs + note("hx/step_result", {"status": "blocked", "reason": mode, "summary": f"hit the {mode}"}) + return blocked = mode == "blocked" if mode == "block_once" and not os.path.exists(os.path.join(cwd, ".fake_blocked")): open(os.path.join(cwd, ".fake_blocked"), "w").close()