Compare commits
24
Commits
f1b3ee0607
..
v0.2.1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
061649cb07 | ||
|
|
9d8b7dfbd8 | ||
|
|
179e5cddc7 | ||
|
|
05165d7b8f | ||
|
|
c06381117b | ||
|
|
9fbcf4a62c | ||
|
|
b84b6ab23a | ||
|
|
161c33fe6c | ||
|
|
3f1acd045b | ||
|
|
c849463805 | ||
|
|
742f2a124a | ||
|
|
aec92ff5a5 | ||
|
|
5408db83a9 | ||
|
|
77e32bbc78 | ||
|
|
79cf5fcda1 | ||
|
|
05dbb8e63f | ||
|
|
e119dc2f0d | ||
|
|
0184627f27 | ||
|
|
5d4cdbf10d | ||
|
|
4949a4b558 | ||
|
|
fa8641f803 | ||
|
|
8a9d8fe607 | ||
|
|
36e99fc8af | ||
|
|
1da3d52190 |
No files matched your search
Generated
+1
@@ -1054,6 +1054,7 @@ dependencies = [
|
||||
"hx-tui",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"similar",
|
||||
"tokio",
|
||||
"toml",
|
||||
]
|
||||
|
||||
@@ -15,6 +15,12 @@ hx -r # pick a session to resume
|
||||
hx -r parser # resume the session whose title best matches "parser"
|
||||
```
|
||||
|
||||
## Dependencies
|
||||
|
||||
- Rust toolchain (to build from source; `cmake` and `perl` may be needed for the TLS stack).
|
||||
- `git`.
|
||||
- Linux: [`bubblewrap`](https://github.com/containers/bubblewrap) (`bwrap`) on `PATH` (`apt install bubblewrap`, `pacman -S bubblewrap`, `dnf install bubblewrap`). The Nix package wraps `hx` so it is provided automatically.
|
||||
|
||||
TUI: `enter` send, `shift-enter`/`alt-enter`/`ctrl-j` newline (or end a line with `\` and press enter), `esc` abort, `ctrl-o` expand tool output.
|
||||
|
||||
Shift-enter needs a terminal that reports it; hx turns on the kitty keyboard protocol when the terminal answers the probe. Works in ghostty, kitty, WezTerm (`enable_kitty_keyboard = true`), iTerm2, foot, Alacritty 0.13+, Windows Terminal (map shift-enter to `\u001b[13;2u`) and zellij 0.41+. tmux 3.2+ needs `set -g extended-keys on` and `set -g extended-keys-format csi-u`. Elsewhere use `alt-enter`, `ctrl-j` or a trailing `\`. `/keys` prints every key as hx receives it, to see what a terminal or multiplexer (e.g. herdr) passes through. Long input lines wrap; the box grows up to 10 rows.
|
||||
@@ -44,6 +50,8 @@ Lens findings and affected-test results appear after each turn as a `┄ lens
|
||||
|
||||
Config: `~/.hx/config.toml`, overridden per project by `.hx/config.toml`. `hx config init [--project] [--force]` writes a fully commented sample with every key. Example:
|
||||
|
||||
**Session storage:** `sessions_dir` in config (or `HX_SESSIONS_DIR`, wins) moves sessions off `~/.hx/sessions`, e.g. to a synced or mounted cloud folder (rclone, Nextcloud, Syncthing). `~` expands; an unwritable path is an error, no silent fallback. `sessions_host = true` prefixes project folders with the host name so machines sharing one folder stay apart. Sessions are append-only JSONL: one hx per session file.
|
||||
|
||||
```toml
|
||||
provider = "claude" # or "codex"
|
||||
# claude_model = "claude-sonnet-5-5" # default: the account's latest Sonnet
|
||||
@@ -108,7 +116,7 @@ Permissions: only writes ask. `write`/`edit` and unknown `bash` commands prompt;
|
||||
|
||||
Auto permissions (`--auto`, `permissions = "auto"`, `/auto [on|off|log]`): nothing prompts for the usual work, and dangerous calls are refused without asking. A refused call returns `blocked by auto mode: <reason>` to the model (also over a stored "always" rule); `/auto log` lists the last 20. Per call, in order: (1) rules block `rm -rf` of home/root/project root/outside the project, `sudo`, raw disk writes and filesystem creation, download piped to a shell, force push, push to main/master, sending `.env`/keys over the network, `npm|cargo publish`, `docker push`, `kubectl delete`, `terraform destroy`, SQL `DROP`, writes to `/etc`, `~/.ssh`, shell rc files, `.git/hooks`; (2) rules allow routine work inside the project (build/test/format, local git, `mkdir`/`mv`/`cp`/`rm` in the project, `write`/`edit` of project files); (3) everything else (unknown binaries, `curl`, `python -c`, `$(..)`, redirects, paths outside the project) goes to one cheap-model request (Haiku/Luna, ~300 input tokens, 20 s timeout) that answers ALLOW or BLOCK; if that fails or is unavailable the normal prompt appears. `--yolo` / `/yolo` still skip everything. With the `claude_cli` provider claude's tools appear on the event bus (`tool_call` / `tool_result`; hx names `bash{command}`, `write|edit|read{path}`, other tools under claude's name), so extensions can block them (a `block` denies the call with its reason) and NDJSON / `hx stats` see them. Reads are asked too (`--settings` `permissions.ask`; Bash too, claude auto-runs read-only commands like `ls` without asking otherwise). In `-p` there is no prompt and everything is allowed, unless `permissions = "deny"` (every unanswered call is denied) or `permissions = "extensions-only"` (allowed only while a live `tool_call` extension exists). The same rules apply to claude's tool calls, but no model judge runs (unclear ones ask). Pattern rules are not a sandbox: combine with `[sandbox]` for confinement.
|
||||
|
||||
The model can call `task(prompt, kind)` (or `task(prompts=[…], kind)` to fan out: one subagent per prompt, parallel, answers returned numbered; a lone task blocks the parent, so the tool description steers the model to batches) to run a subagent with a fresh context and get back only its final answer (cut at 8 KB), so big searches don't fill the main context. `explore` (default) is read-only (`read`, `lsp`, `bash`) on the provider's cheapest model (`explore_model` in config); `general` has the parent's tools and model, and the lens runs on its edits. Up to 3 run in parallel, none can start another, a parent abort stops them. Their sessions are written to `<session>.sub/`; `hx stats` shows `task` usage (calls, lone vs. batched turns) and lists them and the footer token counts include them. **Overview:** while any subagent exists, a list sits above the footer (bottom right: spinner/✓, id, kind, task, time, calls, tokens). `ctrl-g` focuses it (`↑↓`, `enter` opens, `esc` closes); the detail view shows that agent's live transcript. Typing there messages the agent: while it runs the text is delivered at its next turn end (like steering the main agent), after it finished it continues that agent's conversation. `ctrl-c` aborts that agent only; `ctrl-s` sends its last answer to the main chat as `[subagent N] …`. NDJSON/RPC carry no per-agent events yet.
|
||||
Each `task` call asks for permission (`[a]` allows that kind for the project); `subagents = false` or `--no-subagents` removes the tool. The model can call `task(prompt, kind)` (or `task(prompts=[…], kind)` to fan out: one subagent per prompt, parallel, answers returned numbered; a lone task blocks the parent, so the tool description steers the model to batches) to run a subagent with a fresh context and get back only its final answer (cut at 8 KB), so big searches don't fill the main context. `explore` (default) is read-only (`read`, `lsp`, `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.
|
||||
|
||||
A child starts with a cold prompt cache and costs tokens of its own: it saves *main-context* size, not total tokens.
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"version": "0.1.9",
|
||||
"version": "0.1.16",
|
||||
"sha256": {
|
||||
"aarch64-apple-darwin": "0987c70a428b29e799ad76cad33efef37b524cde1a8cfcafd551a87073b21bb8",
|
||||
"x86_64-unknown-linux-musl": "eb2b885e37df32f8878af85fb6b15513486d5583c9b0b4c71f2a2f500c9b9b97"
|
||||
"aarch64-apple-darwin": "5750c046c3e592cbdc9b658ba9c499d44287e85fc0d47052d9cfbf0d9383cc77",
|
||||
"x86_64-unknown-linux-musl": "93f0727fdb7cd47d682f7f37996a4060a948886a0a126ba6105c5c45d121053a"
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,14 @@ pub type Spawner = Arc<
|
||||
+ Sync,
|
||||
>;
|
||||
|
||||
/// hx plan mode is on: claude runs with `--permission-mode plan`, else its `ExitPlanMode` is rejected.
|
||||
// ponytail: process-wide flag; make it per-provider if two claude providers ever run at once.
|
||||
static PLAN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
|
||||
pub fn set_plan(on: bool) {
|
||||
PLAN.store(on, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub struct ClaudeCli {
|
||||
spawner: Option<Spawner>,
|
||||
bin: String,
|
||||
@@ -205,6 +213,9 @@ impl Provider for ClaudeCli {
|
||||
]);
|
||||
}
|
||||
}
|
||||
if PLAN.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
cmd.args(["--permission-mode", "plan"]);
|
||||
}
|
||||
cmd.args(&self.args)
|
||||
.arg("--")
|
||||
.arg(prompt(&req.messages, sid.is_some()))
|
||||
|
||||
@@ -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"
|
||||
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -5,11 +5,14 @@
|
||||
# model = "claude-sonnet-5-5" # model for the chosen provider; "auto" = pick per prompt (see [auto])
|
||||
# claude_model = "claude-sonnet-5-5" # default: the account's latest Sonnet
|
||||
# codex_model = "gpt-5.6-sol" # default: Codex's top-listed model
|
||||
# subagents = false # do not offer the `task` tool (default true; every call asks first)
|
||||
# explore_model = "claude-haiku-4-5" # read-only `task` subagents; default: cheapest tier of the provider
|
||||
# remember_model = true # reuse the last model picked with /model or /provider
|
||||
# compact_at = 900000 # auto-compact at this many tokens; default: 90% of the context window
|
||||
# max_tokens = 16384
|
||||
# permissions = "ask" # ask | auto (refuse dangerous calls, run safe ones) | yolo (nothing asks)
|
||||
# sessions_dir = "~/Nextcloud/hx-sessions" # default ~/.hx/sessions; point at a synced/mounted cloud folder (env HX_SESSIONS_DIR wins)
|
||||
# sessions_host = false # true: prefix project folders with the host name (machines sharing one sessions_dir)
|
||||
# mouse = true # wheel scrolling; false keeps terminal text selection
|
||||
# codemode = false # `codemode` tool: JS scripts that call other tools in a sandbox
|
||||
# system_prompt = "..." # replaces the built-in prompt; AGENTS.md is still appended
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -48,6 +49,9 @@ struct Cli {
|
||||
/// prompt (also `permissions = "auto"`).
|
||||
#[arg(long, conflicts_with = "yolo")]
|
||||
auto: bool,
|
||||
/// Do not offer the `task` subagent tool to the model.
|
||||
#[arg(long)]
|
||||
no_subagents: bool,
|
||||
/// Run bash, LSP servers and lens runners in a sandbox (bwrap / seatbelt).
|
||||
#[arg(long, conflicts_with = "no_sandbox")]
|
||||
sandbox: bool,
|
||||
@@ -97,6 +101,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)]
|
||||
@@ -147,10 +163,16 @@ struct Config {
|
||||
max_tokens: Option<u32>,
|
||||
/// Model for read-only `task` subagents; default: the provider's cheapest tier (Haiku / Luna).
|
||||
explore_model: Option<String>,
|
||||
/// Register the `task` subagent tool (default true; each call still asks the user). `--no-subagents` = off.
|
||||
subagents: Option<bool>,
|
||||
/// Add the `codemode` tool: JS scripts that call the other tools (default false).
|
||||
codemode: Option<bool>,
|
||||
/// Capture the mouse for wheel scrolling (default true; false = terminal selection works without shift).
|
||||
mouse: Option<bool>,
|
||||
/// Where sessions live (default `~/.hx/sessions`); `~` expands. Point at a synced/mounted cloud folder. `HX_SESSIONS_DIR` wins.
|
||||
sessions_dir: Option<String>,
|
||||
/// Prefix session folders with the host name, so machines sharing `sessions_dir` stay apart (default false).
|
||||
sessions_host: Option<bool>,
|
||||
/// Reuse the last model chosen with /model or /provider (default true).
|
||||
remember_model: Option<bool>,
|
||||
/// `/model auto`: tier pins (`fast`, `balanced`, `deep` = model ids) and `down_after`.
|
||||
@@ -223,8 +245,11 @@ impl Config {
|
||||
compact_at: o.compact_at.or(c.compact_at),
|
||||
max_tokens: o.max_tokens.or(c.max_tokens),
|
||||
explore_model: o.explore_model.or(c.explore_model),
|
||||
subagents: o.subagents.or(c.subagents),
|
||||
codemode: o.codemode.or(c.codemode),
|
||||
mouse: o.mouse.or(c.mouse),
|
||||
sessions_dir: o.sessions_dir.or(c.sessions_dir),
|
||||
sessions_host: o.sessions_host.or(c.sessions_host),
|
||||
remember_model: o.remember_model.or(c.remember_model),
|
||||
auto: o.auto.or(c.auto),
|
||||
permissions: o.permissions.or(c.permissions),
|
||||
@@ -572,15 +597,62 @@ impl<H: Hook> Hook for ArcHook<H> {
|
||||
}
|
||||
}
|
||||
|
||||
fn session_dir(cwd: &std::path::Path) -> std::path::PathBuf {
|
||||
hx_core::session::dir(&context::hx_home(), cwd)
|
||||
fn session_dir(cwd: &std::path::Path, cfg: &Config) -> Result<std::path::PathBuf> {
|
||||
let home = context::hx_home();
|
||||
let root = match std::env::var("HX_SESSIONS_DIR")
|
||||
.ok()
|
||||
.or(cfg.sessions_dir.clone())
|
||||
{
|
||||
Some(s) if !s.is_empty() => match s.strip_prefix('~') {
|
||||
Some(r) => std::env::var_os("HOME")
|
||||
.map(std::path::PathBuf::from)
|
||||
.unwrap_or_default()
|
||||
.join(r.trim_start_matches('/')),
|
||||
None => s.into(),
|
||||
},
|
||||
_ => home.join("sessions"),
|
||||
};
|
||||
let host = cfg.sessions_host.unwrap_or(false).then(|| {
|
||||
["HOSTNAME", "HOST", "COMPUTERNAME"]
|
||||
.iter()
|
||||
.find_map(|k| std::env::var(k).ok())
|
||||
.or_else(|| std::fs::read_to_string("/etc/hostname").ok())
|
||||
.map_or("host".into(), |h| h.trim().to_string())
|
||||
});
|
||||
let dir = hx_core::session::dir(&root, cwd, host.as_deref());
|
||||
// fail loud: a silent fallback would leave sessions off the cloud folder
|
||||
std::fs::create_dir_all(&dir)
|
||||
.map_err(|e| anyhow::anyhow!("sessions dir {}: {e}", dir.display()))?;
|
||||
Ok(dir)
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
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());
|
||||
@@ -669,7 +741,9 @@ async fn main() -> Result<()> {
|
||||
];
|
||||
rows.extend(skill_rows);
|
||||
let mut specs = reg.specs();
|
||||
specs.push(hx_core::subagent::spec());
|
||||
if !cli.no_subagents && cfg.subagents != Some(false) {
|
||||
specs.push(hx_core::subagent::spec());
|
||||
}
|
||||
specs.sort_by_key(|t| {
|
||||
std::cmp::Reverse(serde_json::to_string(t).map_or(0, |s| s.len()))
|
||||
});
|
||||
@@ -869,9 +943,13 @@ async fn main() -> Result<()> {
|
||||
}
|
||||
.unwrap_or_else(|| hx_ai::models::default_for(kind, &models))
|
||||
});
|
||||
let dir = session_dir(&cwd);
|
||||
let dir = session_dir(&cwd, &cfg)?;
|
||||
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);
|
||||
@@ -1013,10 +1091,10 @@ async fn main() -> Result<()> {
|
||||
mgr.warm(probe).await;
|
||||
}
|
||||
trace("lens");
|
||||
{
|
||||
if !cli.no_subagents && cfg.subagents != Some(false) {
|
||||
// children get the parent's tools as of now (no `task`, so no recursion)
|
||||
let mut general = agent.tools.clone();
|
||||
general.retain(|n| n != "ask_user");
|
||||
general.retain(|n| n != "ask_user" && n != "exit_plan");
|
||||
let mut explore = agent.tools.clone();
|
||||
explore.retain(|n| hx_core::subagent::EXPLORE_TOOLS.contains(&n));
|
||||
let role = |model: String, tools, base: &str| hx_core::subagent::Role {
|
||||
@@ -1104,6 +1182,18 @@ async fn main() -> Result<()> {
|
||||
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,
|
||||
|
||||
@@ -433,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"
|
||||
@@ -477,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;
|
||||
}
|
||||
@@ -919,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;
|
||||
|
||||
@@ -42,7 +42,12 @@ pub fn question(tool: &str, input: &Value) -> Option<Request> {
|
||||
detail: s("file_path"),
|
||||
rule: String::new(),
|
||||
}),
|
||||
"Grep" | "Glob" | "LS" | "TodoWrite" | "NotebookRead" | "Task" | "Agent" => None,
|
||||
"Grep" | "Glob" | "LS" | "TodoWrite" | "NotebookRead" => None,
|
||||
"Task" | "Agent" => Some(Request {
|
||||
tool: "task".into(),
|
||||
detail: format!("subagent: {}", s("description")),
|
||||
rule: "task:claude".into(),
|
||||
}),
|
||||
t if t.starts_with("mcp__hx__") => None,
|
||||
"WebFetch" => Some(crate::permit::request(
|
||||
"web_fetch",
|
||||
@@ -168,6 +173,8 @@ pub async fn serve(path: &Path, cx: ToolCtx, bus: Bus, mode: Unanswered) -> std:
|
||||
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
|
||||
input = ask(&cx, &v["input"]).await;
|
||||
@@ -210,6 +217,38 @@ pub async fn serve(path: &Path, cx: ToolCtx, bus: Bus, mode: Unanswered) -> std:
|
||||
}
|
||||
}
|
||||
|
||||
/// claude's `ExitPlanMode`: the TUI shows the whole plan, then asks. Implement ends hx plan mode too.
|
||||
async fn exit_plan(cx: &ToolCtx, plan: &str) -> Result<(), String> {
|
||||
let q = crate::Question {
|
||||
text: "Implement this plan?".into(),
|
||||
options: vec![
|
||||
("Implement".into(), "leave plan mode and start".into()),
|
||||
(
|
||||
"Keep planning".into(),
|
||||
"stay read-only; type feedback below".into(),
|
||||
),
|
||||
],
|
||||
multi: false,
|
||||
other: true,
|
||||
plan: Some(plan.into()),
|
||||
};
|
||||
match cx.state.choose(q).await {
|
||||
Ok(Some(v)) if v.first().is_some_and(|s| s == "Implement") => {
|
||||
cx.state
|
||||
.allow
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.set_plan(false);
|
||||
Ok(())
|
||||
}
|
||||
Ok(Some(v)) if v.first().is_some_and(|s| s != "Keep planning") => Err(format!(
|
||||
"plan not approved, user feedback: {}. Revise and present the plan again.",
|
||||
v.join(", ")
|
||||
)),
|
||||
_ => Err("plan not approved; keep planning and ask what to change".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Run each `AskUserQuestion` question through the popup; `input` plus `answers` (question -> label(s)).
|
||||
/// None = no frontend or dismissed.
|
||||
async fn ask(cx: &ToolCtx, input: &Value) -> Option<Value> {
|
||||
@@ -227,6 +266,7 @@ async fn ask(cx: &ToolCtx, input: &Value) -> Option<Value> {
|
||||
options: options.collect(),
|
||||
multi: q["multiSelect"].as_bool().unwrap_or(false),
|
||||
other: true,
|
||||
plan: None,
|
||||
})
|
||||
.await
|
||||
.ok()??;
|
||||
@@ -362,6 +402,24 @@ mod tests {
|
||||
assert_eq!(ask(&cx, &inp).await.unwrap()["answers"]["Which?"], "B");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn exit_plan_shows_plan_and_implement_ends_plan_mode() {
|
||||
let cx = ToolCtx {
|
||||
cwd: ".".into(),
|
||||
state: Default::default(),
|
||||
};
|
||||
cx.state.allow.lock().unwrap().set_plan(true);
|
||||
let seen = std::sync::Arc::new(std::sync::Mutex::new(None));
|
||||
let s = seen.clone();
|
||||
let _ = cx.state.choose.set(std::sync::Arc::new(move |q| {
|
||||
*s.lock().unwrap() = q.plan.clone();
|
||||
Box::pin(async { Some(vec!["Keep planning".to_string()]) })
|
||||
}));
|
||||
assert!(exit_plan(&cx, "# P\nstep 1").await.is_err());
|
||||
assert_eq!(seen.lock().unwrap().as_deref(), Some("# P\nstep 1"));
|
||||
assert!(cx.state.allow.lock().unwrap().plan_on());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn socket_round_trip_allows_and_denies() {
|
||||
use crate::permit::Decision;
|
||||
|
||||
@@ -82,6 +82,11 @@ pub fn builtins(models: &[&str]) -> Vec<CmdSpec> {
|
||||
"auto permissions: refuse dangerous calls, run safe ones",
|
||||
Enum(vec!["on".into(), "off".into(), "log".into()]),
|
||||
),
|
||||
b(
|
||||
"plan",
|
||||
"plan mode: read-only research, then the full plan for approval",
|
||||
Enum(vec!["on".into(), "off".into()]),
|
||||
),
|
||||
b("yolo", "toggle: run every tool without asking", None),
|
||||
b(
|
||||
"sandbox",
|
||||
|
||||
@@ -43,6 +43,8 @@ pub struct Question {
|
||||
pub multi: bool,
|
||||
/// offer a free-text "Other" row
|
||||
pub other: bool,
|
||||
/// Long markdown (a plan) the frontend shows in full in the transcript before asking.
|
||||
pub plan: Option<String>,
|
||||
}
|
||||
|
||||
/// Shows a [`Question`]; resolves to the chosen labels / typed text, None when dismissed.
|
||||
|
||||
@@ -198,7 +198,7 @@ pub fn needs_permit(tool: &str, args: &serde_json::Value) -> bool {
|
||||
match tool {
|
||||
"bash" => !readonly_cmd(a("command").trim()),
|
||||
"read" => secret(a("path")),
|
||||
"web_fetch" => true,
|
||||
"web_fetch" | "task" => true,
|
||||
_ => gated(tool),
|
||||
}
|
||||
}
|
||||
@@ -261,6 +261,25 @@ pub fn request(tool: &str, args: &serde_json::Value) -> Request {
|
||||
rule: format!("web:{host}"),
|
||||
};
|
||||
}
|
||||
if tool == "task" {
|
||||
let kind = args["kind"].as_str().unwrap_or("explore");
|
||||
let ps: Vec<&str> = match args["prompts"].as_array() {
|
||||
Some(a) => a.iter().filter_map(|v| v.as_str()).collect(),
|
||||
None => vec![args["prompt"].as_str().unwrap_or_default()],
|
||||
};
|
||||
let first: String = ps
|
||||
.first()
|
||||
.copied()
|
||||
.unwrap_or_default()
|
||||
.chars()
|
||||
.take(120)
|
||||
.collect();
|
||||
return Request {
|
||||
tool: tool.into(),
|
||||
detail: format!("{} {kind} subagent(s): {first}", ps.len()),
|
||||
rule: format!("task:{kind}"),
|
||||
};
|
||||
}
|
||||
if tool != "bash" {
|
||||
return Request {
|
||||
tool: tool.into(),
|
||||
@@ -328,6 +347,8 @@ pub struct Allow {
|
||||
all_edits: bool,
|
||||
yolo: bool,
|
||||
auto: bool,
|
||||
/// Plan mode: read-only until the user approves a plan.
|
||||
plan: bool,
|
||||
/// Last calls auto mode refused (newest last), for `/auto`.
|
||||
blocks: Vec<String>,
|
||||
file: Option<PathBuf>,
|
||||
@@ -345,6 +366,7 @@ impl Allow {
|
||||
all_edits: false,
|
||||
yolo: false,
|
||||
auto: false,
|
||||
plan: false,
|
||||
blocks: Vec::new(),
|
||||
file: Some(file),
|
||||
}
|
||||
@@ -381,6 +403,15 @@ impl Allow {
|
||||
self.yolo
|
||||
}
|
||||
|
||||
pub fn plan_on(&self) -> bool {
|
||||
self.plan
|
||||
}
|
||||
|
||||
pub fn set_plan(&mut self, on: bool) {
|
||||
self.plan = on;
|
||||
hx_ai::claude_cli::set_plan(on);
|
||||
}
|
||||
|
||||
pub fn auto_on(&self) -> bool {
|
||||
self.auto
|
||||
}
|
||||
@@ -455,6 +486,13 @@ mod tests {
|
||||
assert_eq!(bash("go test $(id)").rule, "");
|
||||
assert_eq!(request("edit", &json!({"path": "a.rs"})).rule, "");
|
||||
assert!(gated("bash") && !gated("read"));
|
||||
let t = serde_json::json!({"prompts": ["a", "b"], "kind": "general"});
|
||||
assert!(needs_permit("task", &t));
|
||||
let r = request("task", &t);
|
||||
assert_eq!(
|
||||
(r.rule.as_str(), r.detail.starts_with("2 general")),
|
||||
("task:general", true)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -173,14 +173,18 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// `<hx home>/sessions/<slug of cwd>`.
|
||||
pub fn dir(home: &Path, cwd: &Path) -> PathBuf {
|
||||
let slug: String = cwd
|
||||
.to_string_lossy()
|
||||
/// `<root>/<slug of cwd>`, with `<host>-` in front when `host` is set (shared roots).
|
||||
pub fn dir(root: &Path, cwd: &Path, host: Option<&str>) -> PathBuf {
|
||||
let cwd = cwd.to_string_lossy();
|
||||
let slug: String = host
|
||||
.into_iter()
|
||||
.chain([cwd.trim_matches('/')])
|
||||
.collect::<Vec<_>>()
|
||||
.join("/")
|
||||
.chars()
|
||||
.map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
|
||||
.collect();
|
||||
home.join("sessions").join(slug.trim_matches('-'))
|
||||
root.join(slug.trim_matches('-'))
|
||||
}
|
||||
|
||||
/// A fresh, not yet created session file in `dir` (created on first append).
|
||||
@@ -279,7 +283,7 @@ pub fn list(dir: &Path) -> Vec<Meta> {
|
||||
v
|
||||
}
|
||||
|
||||
/// Sessions of every project under `<hx home>/sessions`, newest first.
|
||||
/// Sessions of every project under the sessions root, newest first.
|
||||
pub fn list_all(root: &Path) -> Vec<Meta> {
|
||||
let mut v: Vec<Meta> = std::fs::read_dir(root)
|
||||
.into_iter()
|
||||
@@ -370,8 +374,12 @@ mod tests {
|
||||
.collect();
|
||||
assert_eq!(t, [("newer", "other"), ("fix parser", "proj")]);
|
||||
assert_eq!(
|
||||
dir(Path::new("/h"), Path::new("/a/b c")),
|
||||
Path::new("/h/sessions/a-b-c")
|
||||
dir(Path::new("/h"), Path::new("/a/b c"), None),
|
||||
Path::new("/h/a-b-c")
|
||||
);
|
||||
assert_eq!(
|
||||
dir(Path::new("/h"), Path::new("/a/b"), Some("box")),
|
||||
Path::new("/h/box-a-b")
|
||||
);
|
||||
let n = new_path(&proj);
|
||||
assert!(n.starts_with(&proj) && !n.exists());
|
||||
|
||||
@@ -96,6 +96,7 @@ pub struct Subs {
|
||||
list: Mutex<Vec<Arc<Sub>>>,
|
||||
/// (child id, event) for the UI; set by interactive frontends
|
||||
pub events: OnceLock<mpsc::UnboundedSender<(usize, Event)>>,
|
||||
watching: std::sync::atomic::AtomicBool,
|
||||
}
|
||||
|
||||
const KEEP: usize = 20;
|
||||
@@ -107,6 +108,36 @@ impl Subs {
|
||||
pub fn get(&self, id: usize) -> Option<Arc<Sub>> {
|
||||
self.list().into_iter().find(|s| s.sh.id == id)
|
||||
}
|
||||
/// Abort every running child (also those continued in the background after their task ended).
|
||||
pub fn abort_all(&self) {
|
||||
for s in self.list() {
|
||||
if s.sh.status() == Status::Running {
|
||||
s.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn any_running(&self) -> bool {
|
||||
self.list().iter().any(|s| s.sh.status() == Status::Running)
|
||||
}
|
||||
/// Once per session: every parent abort reaches all running children. The parent flag resets
|
||||
/// after each run, so the loop re-arms.
|
||||
fn watch(&self, state: &Arc<crate::State>) {
|
||||
let Some(mut rx) = state.abort.get().cloned() else {
|
||||
return;
|
||||
};
|
||||
if self.watching.swap(true, Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
let st = state.clone();
|
||||
tokio::spawn(async move {
|
||||
while rx.wait_for(|a| *a).await.is_ok() {
|
||||
st.subs.abort_all();
|
||||
if rx.wait_for(|a| !*a).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
fn add(&self, s: Arc<Sub>) {
|
||||
let mut l = self.list.lock().unwrap_or_else(|e| e.into_inner());
|
||||
l.push(s);
|
||||
@@ -252,7 +283,7 @@ impl Task {
|
||||
pub fn spec() -> ToolSpec {
|
||||
ToolSpec {
|
||||
name: "task".into(),
|
||||
description: "Run a subagent in a fresh context; you get back only its final answer. kind=explore (default): read-only research on a cheaper model; use it for searching/reading that would fill your context (many files or >10k tokens). kind=general: same tools as you, may edit. The subagent sees nothing of this conversation: make every prompt self-contained. You are blocked until it answers, so a single task you then wait on only pays off when the search would put >10k tokens in your context; otherwise do it yourself. Prefer splitting work into 2+ independent subtasks: pass `prompts` (array) or several task calls in one turn, they run in parallel. Not for small lookups.".into(),
|
||||
description: "Run a subagent in a fresh context; you get back only its final answer. The user is asked to approve every call: use it only when the user asked for subagents or parallel work, or when a search would clearly put >10k tokens in your context. Do ordinary discovery (read, grep, lsp, bash) yourself in this session. kind=explore (default): read-only research on a cheaper model. kind=general: same tools as you, may edit. The subagent sees nothing of this conversation: make every prompt self-contained. You are blocked until it answers. For 2+ independent subtasks pass `prompts` (array); they run in parallel.".into(),
|
||||
input_schema: json!({"type":"object","properties":{
|
||||
"prompt":{"type":"string"},
|
||||
"prompts":{"type":"array","items":{"type":"string"},"description":"several independent subtasks: one subagent each, run in parallel, answers returned numbered"},
|
||||
@@ -357,23 +388,12 @@ impl Task {
|
||||
sem: self.sem.clone(),
|
||||
});
|
||||
cx.state.subs.add(sub.clone());
|
||||
// parent abort stops the child
|
||||
let bridge = cx.state.abort.get().cloned().map(|mut rx| {
|
||||
let s = sub.clone();
|
||||
tokio::spawn(async move {
|
||||
if rx.wait_for(|a| *a).await.is_ok() {
|
||||
s.abort();
|
||||
}
|
||||
})
|
||||
});
|
||||
cx.state.subs.watch(&cx.state);
|
||||
// waiting for a slot may have outlasted an abort
|
||||
if aborted() {
|
||||
sub.abort();
|
||||
}
|
||||
let r = sub.drive(prompt.to_string()).await;
|
||||
if let Some(b) = bridge {
|
||||
b.abort();
|
||||
}
|
||||
let u = sh.usage.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
||||
let tok = u.input_tokens + u.cache_read_tokens + u.cache_write_tokens + u.output_tokens;
|
||||
let stats = format!(
|
||||
@@ -682,4 +702,41 @@ mod tests {
|
||||
assert_eq!(reqs[1].messages.len(), 3);
|
||||
assert_eq!(cx.state.sub_usage.lock().unwrap().input_tokens, 2000);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn parent_abort_reaches_background_child() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let p = Arc::new(Script(
|
||||
Mutex::new(vec![text("a"), call("read", json!({}))]),
|
||||
Default::default(),
|
||||
));
|
||||
let t = Task::new(
|
||||
role(&p, "cheap"),
|
||||
role(&p, "main"),
|
||||
d.path().join("s.sub"),
|
||||
2,
|
||||
);
|
||||
let (parent, h) = Agent::new(
|
||||
p.clone(),
|
||||
Registry::default(),
|
||||
Session::open(d.path().join("p.jsonl")).unwrap(),
|
||||
ToolCtx {
|
||||
cwd: d.path().into(),
|
||||
state: Default::default(),
|
||||
},
|
||||
);
|
||||
let cx = parent.cx.clone();
|
||||
t.call(json!({"prompt":"one"}), &cx).await;
|
||||
let sub = cx.state.subs.get(1).unwrap();
|
||||
sub.prompt("two".into());
|
||||
assert!(cx.state.subs.any_running());
|
||||
h.abort();
|
||||
for _ in 0..100 {
|
||||
if sub.sh.status() == Status::Aborted {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
|
||||
}
|
||||
assert_eq!(sub.sh.status(), Status::Aborted);
|
||||
}
|
||||
}
|
||||
@@ -93,6 +93,16 @@ pub async fn gate_why(cx: &ToolCtx, req: crate::permit::Request) -> Result<(), S
|
||||
use crate::danger::{Verdict, classify};
|
||||
use crate::permit::Decision;
|
||||
const DENIED: &str = "denied by the user; do not retry, ask what to do instead";
|
||||
if matches!(req.tool.as_str(), "bash" | "write" | "edit")
|
||||
&& cx
|
||||
.state
|
||||
.allow
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.plan_on()
|
||||
{
|
||||
return Err("blocked by plan mode: read-only until the plan is approved. Explore with read/grep/ls, then call exit_plan with the full plan.".into());
|
||||
}
|
||||
let Some(ask) = cx.state.permit.get() else {
|
||||
return Ok(());
|
||||
};
|
||||
@@ -263,6 +273,27 @@ mod tests {
|
||||
assert!(d.is_error && d.content.contains("denied"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn plan_mode_blocks_writes_even_without_prompt() {
|
||||
let c = cx();
|
||||
c.state.allow.lock().unwrap().set_plan(true);
|
||||
let e = gate_why(
|
||||
&c,
|
||||
crate::permit::request("bash", &json!({"command":"touch x"})),
|
||||
)
|
||||
.await;
|
||||
assert!(e.unwrap_err().contains("plan mode"));
|
||||
c.state.allow.lock().unwrap().set_plan(false);
|
||||
assert!(
|
||||
gate_why(
|
||||
&c,
|
||||
crate::permit::request("bash", &json!({"command":"touch x"}))
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn auto_mode_blocks_allows_judges_without_prompting() {
|
||||
use crate::danger::Judge;
|
||||
|
||||
@@ -66,6 +66,7 @@ pub fn registry() -> Registry {
|
||||
.add(Edit)
|
||||
.add(Bash)
|
||||
.add(AskUser)
|
||||
.add(ExitPlan)
|
||||
.add(MemoryWrite)
|
||||
.add(MemoryForget)
|
||||
.add(skill::Skill);
|
||||
@@ -313,6 +314,7 @@ impl Tool for AskUser {
|
||||
options,
|
||||
multi: a["multi"].as_bool().unwrap_or(false),
|
||||
other: true,
|
||||
plan: None,
|
||||
};
|
||||
match cx.state.choose(q).await {
|
||||
Err(e) => ToolResult::err(e),
|
||||
@@ -324,6 +326,52 @@ impl Tool for AskUser {
|
||||
}
|
||||
}
|
||||
|
||||
/// Plan mode's end: the TUI shows the plan in full, the user approves or sends feedback.
|
||||
pub struct ExitPlan;
|
||||
#[async_trait]
|
||||
impl Tool for ExitPlan {
|
||||
fn spec(&self) -> ToolSpec {
|
||||
spec(
|
||||
"exit_plan",
|
||||
"Only in plan mode: present your finished plan (markdown, complete) for approval. Plan mode ends once the user approves.",
|
||||
json!({"type":"object","properties":{"plan":{"type":"string"}},"required":["plan"]}),
|
||||
)
|
||||
}
|
||||
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
|
||||
let on = || cx.state.allow.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if !on().plan_on() {
|
||||
return ToolResult::ok("not in plan mode; just do the work");
|
||||
}
|
||||
let q = hx_core::Question {
|
||||
text: "Implement this plan?".into(),
|
||||
options: vec![
|
||||
("Implement".into(), "leave plan mode and start".into()),
|
||||
(
|
||||
"Keep planning".into(),
|
||||
"stay read-only; type feedback below".into(),
|
||||
),
|
||||
],
|
||||
multi: false,
|
||||
other: true,
|
||||
plan: a["plan"].as_str().map(Into::into),
|
||||
};
|
||||
match cx.state.choose(q).await {
|
||||
Ok(Some(v)) if v.first().is_some_and(|s| s == "Implement") => {
|
||||
on().set_plan(false);
|
||||
ToolResult::ok("plan approved; plan mode is off, implement it now")
|
||||
}
|
||||
Ok(Some(v)) if v.first().is_some_and(|s| s != "Keep planning") => {
|
||||
ToolResult::ok(format!(
|
||||
"plan not approved, user feedback: {}. Revise and call exit_plan again.",
|
||||
v.join(", ")
|
||||
))
|
||||
}
|
||||
// no frontend (print mode) or dismissed: stay in plan mode
|
||||
_ => ToolResult::ok("plan not approved; keep planning and ask what to change"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes of running bash output kept for the live view.
|
||||
const LIVE_TAIL: usize = 2048;
|
||||
|
||||
|
||||
@@ -19,6 +19,8 @@ pub struct Choose {
|
||||
picked: Vec<bool>,
|
||||
/// Some while typing an own answer
|
||||
typing: Option<String>,
|
||||
/// opened straight into the text input: esc dismisses instead of showing the list
|
||||
direct: bool,
|
||||
}
|
||||
|
||||
impl Choose {
|
||||
@@ -28,9 +30,18 @@ impl Choose {
|
||||
q,
|
||||
sel: 0,
|
||||
typing: None,
|
||||
direct: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Free-text question: starts in the input, no option list.
|
||||
pub fn input(q: Question) -> Self {
|
||||
let mut c = Self::new(q);
|
||||
c.typing = Some(String::new());
|
||||
c.direct = true;
|
||||
c
|
||||
}
|
||||
|
||||
fn rows(&self) -> usize {
|
||||
self.q.options.len() + usize::from(self.q.other)
|
||||
}
|
||||
@@ -57,6 +68,7 @@ impl Choose {
|
||||
let picked = if self.q.multi { self.labels() } else { vec![] };
|
||||
if let Some(t) = &mut self.typing {
|
||||
match k.code {
|
||||
KeyCode::Esc if self.direct => return Act::Done(None),
|
||||
KeyCode::Esc => self.typing = None,
|
||||
KeyCode::Backspace => {
|
||||
t.pop();
|
||||
@@ -286,6 +298,7 @@ mod tests {
|
||||
],
|
||||
multi,
|
||||
other: true,
|
||||
plan: None,
|
||||
})
|
||||
}
|
||||
fn k(c: KeyCode) -> KeyEvent {
|
||||
@@ -314,6 +327,23 @@ mod tests {
|
||||
assert!(c.is_other());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn input_starts_typing_and_esc_dismisses() {
|
||||
let q = || Question {
|
||||
text: "why?".into(),
|
||||
options: vec![],
|
||||
multi: false,
|
||||
other: true,
|
||||
plan: None,
|
||||
};
|
||||
let mut c = Choose::input(q());
|
||||
c.key(k(KeyCode::Char('h')));
|
||||
c.key(k(KeyCode::Char('i')));
|
||||
assert!(matches!(c.key(k(KeyCode::Enter)), Act::Done(Some(v)) if v == ["hi"]));
|
||||
let mut c = Choose::input(q());
|
||||
assert!(matches!(c.key(k(KeyCode::Esc)), Act::Done(None)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_toggle_and_other_text() {
|
||||
let mut c = q(true);
|
||||
@@ -405,6 +435,7 @@ mod tests {
|
||||
],
|
||||
multi: false,
|
||||
other: true,
|
||||
plan: None,
|
||||
});
|
||||
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(200, 50)).unwrap();
|
||||
term.draw(|f| c.draw(f, 45)).unwrap();
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
//! Full-screen read-only text view with scrolling and a row of action keys. Used for plan approval;
|
||||
//! meant to be reused for diffs (`lines` are plain styled lines).
|
||||
|
||||
use crate::{scroll::Scroll, theme};
|
||||
use crossterm::event::{KeyCode, KeyEvent};
|
||||
use ratatui::layout::Rect;
|
||||
use ratatui::text::{Line, Span};
|
||||
use ratatui::widgets::{Block, Clear, Paragraph, Wrap};
|
||||
|
||||
pub enum Act {
|
||||
None,
|
||||
/// An action key was pressed: its label.
|
||||
Pick(String),
|
||||
}
|
||||
|
||||
pub struct DocView {
|
||||
title: String,
|
||||
lines: Vec<Line<'static>>,
|
||||
scroll: Scroll,
|
||||
/// (key, label); esc picks the one with key `\x1b`
|
||||
actions: Vec<(KeyCode, &'static str, &'static str)>,
|
||||
}
|
||||
|
||||
impl DocView {
|
||||
/// `actions`: (key, key name shown, label returned/shown).
|
||||
pub fn new(
|
||||
title: impl Into<String>,
|
||||
lines: Vec<Line<'static>>,
|
||||
actions: Vec<(KeyCode, &'static str, &'static str)>,
|
||||
) -> Self {
|
||||
let mut scroll = Scroll::default();
|
||||
scroll.start();
|
||||
Self {
|
||||
title: title.into(),
|
||||
lines,
|
||||
scroll,
|
||||
actions,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn key(&mut self, k: KeyEvent) -> Act {
|
||||
if let Some((_, _, l)) = self.actions.iter().find(|(c, _, _)| *c == k.code) {
|
||||
return Act::Pick((*l).into());
|
||||
}
|
||||
let (p, h) = (self.scroll.page(), self.scroll.half_page());
|
||||
match k.code {
|
||||
KeyCode::Char('j') | KeyCode::Down => self.scroll.down(1),
|
||||
KeyCode::Char('k') | KeyCode::Up => self.scroll.up(1),
|
||||
KeyCode::PageDown | KeyCode::Char(' ') => self.scroll.down(p),
|
||||
KeyCode::PageUp | KeyCode::Char('b') => self.scroll.up(p),
|
||||
KeyCode::Char('d') => self.scroll.down(h),
|
||||
KeyCode::Char('u') => self.scroll.up(h),
|
||||
KeyCode::Char('g') | KeyCode::Home => self.scroll.start(),
|
||||
KeyCode::Char('G') | KeyCode::End => self.scroll.end(),
|
||||
_ => {}
|
||||
}
|
||||
Act::None
|
||||
}
|
||||
|
||||
pub fn wheel(&mut self, up: bool) {
|
||||
if up {
|
||||
self.scroll.up(3)
|
||||
} else {
|
||||
self.scroll.down(3)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn draw(&mut self, f: &mut ratatui::Frame) {
|
||||
let th = theme::t();
|
||||
let a = f.area();
|
||||
let (w, h) = (a.width * 9 / 10, a.height * 9 / 10);
|
||||
let r = Rect::new(a.x + (a.width - w) / 2, a.y + (a.height - h) / 2, w, h);
|
||||
let mut hint = vec![Span::styled(" ", th.dim())];
|
||||
for (_, name, label) in &self.actions {
|
||||
hint.push(Span::styled(format!("{name} "), th.accent()));
|
||||
hint.push(Span::styled(format!("{label} · "), th.dim()));
|
||||
}
|
||||
hint.push(Span::styled("j/k pgup/pgdn g/G scroll ", th.dim()));
|
||||
let block = Block::bordered()
|
||||
.border_style(th.dim())
|
||||
.title(Span::styled(format!(" {} ", self.title), th.accent()))
|
||||
.title_bottom(Line::from(hint));
|
||||
let inner = block.inner(r);
|
||||
f.render_widget(Clear, r);
|
||||
f.render_widget(block, r);
|
||||
let p = Paragraph::new(self.lines.clone()).wrap(Wrap { trim: false });
|
||||
let total = p.line_count(inner.width).min(u16::MAX as usize) as u16;
|
||||
let top = self.scroll.resolve(total, inner.height);
|
||||
f.render_widget(p.scroll((top, 0)), inner);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crossterm::event::{KeyEventKind, KeyEventState, KeyModifiers};
|
||||
|
||||
fn k(c: KeyCode) -> KeyEvent {
|
||||
KeyEvent {
|
||||
code: c,
|
||||
modifiers: KeyModifiers::NONE,
|
||||
kind: KeyEventKind::Press,
|
||||
state: KeyEventState::NONE,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_text_scrolls_and_keys_pick() {
|
||||
let lines = (0..100).map(|i| Line::raw(format!("line {i}"))).collect();
|
||||
let mut v = DocView::new("plan", lines, vec![(KeyCode::Enter, "enter", "Implement")]);
|
||||
let show = |v: &mut DocView| {
|
||||
let mut t = ratatui::Terminal::new(ratatui::backend::TestBackend::new(60, 20)).unwrap();
|
||||
t.draw(|f| v.draw(f)).unwrap();
|
||||
format!("{}", t.backend())
|
||||
};
|
||||
let s = show(&mut v);
|
||||
assert!(s.contains("line 0") && !s.contains("line 60"), "{s}");
|
||||
v.key(k(KeyCode::Char('G')));
|
||||
assert!(show(&mut v).contains("line 99"));
|
||||
assert!(matches!(v.key(k(KeyCode::Enter)), Act::Pick(l) if l == "Implement"));
|
||||
}
|
||||
}
|
||||
+102
-3
@@ -3,6 +3,7 @@
|
||||
pub mod agents;
|
||||
pub mod btw_view;
|
||||
pub mod choose;
|
||||
pub mod doc_view;
|
||||
pub mod editor;
|
||||
pub mod permit_view;
|
||||
pub mod picker;
|
||||
@@ -172,6 +173,12 @@ struct App {
|
||||
tokio::sync::oneshot::Sender<hx_core::permit::Decision>,
|
||||
)>,
|
||||
review: Option<review::Review>,
|
||||
/// plan view and where the chosen label goes (Implement / Keep planning / Feedback)
|
||||
doc: Option<(
|
||||
doc_view::DocView,
|
||||
hx_core::Question,
|
||||
tokio::sync::oneshot::Sender<Option<Vec<String>>>,
|
||||
)>,
|
||||
/// `/keys`: show every key as hx receives it until esc
|
||||
probe: bool,
|
||||
/// keyboard protocol was switched on (shift-enter is distinguishable)
|
||||
@@ -382,6 +389,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
choose: None,
|
||||
perm: None,
|
||||
review: None,
|
||||
doc: None,
|
||||
probe: false,
|
||||
kbd,
|
||||
stats: None,
|
||||
@@ -496,6 +504,22 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
let _ = reply.send(d);
|
||||
}
|
||||
}
|
||||
TEvent::Key(k) if k.kind != KeyEventKind::Release && app.doc.is_some() => {
|
||||
if let Some((v, _, _)) = &mut app.doc
|
||||
&& let doc_view::Act::Pick(l) = v.key(k)
|
||||
&& let Some((_, mut q, reply)) = app.doc.take()
|
||||
{
|
||||
if l == "Feedback" {
|
||||
q.plan = None;
|
||||
q.text = "What should change in the plan?".into();
|
||||
q.options = vec![];
|
||||
app.choose = Some((choose::Choose::input(q), reply));
|
||||
} else {
|
||||
app.t.push(Item::Info(format!("plan: {l}")));
|
||||
let _ = reply.send(Some(vec![l]));
|
||||
}
|
||||
}
|
||||
}
|
||||
TEvent::Key(k) if k.kind != KeyEventKind::Release && app.choose.is_some() => {
|
||||
if let Some((c, _)) = &mut app.choose
|
||||
&& let choose::Act::Done(ans) = c.key(k)
|
||||
@@ -539,7 +563,24 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
match u {
|
||||
Ui::Ask(q, reply) => app.ask = Some((q, reply)),
|
||||
Ui::Permit(r, reply) => app.perm = Some((permit_view::Prompt::new(r), reply)),
|
||||
Ui::Choose(q, reply) => app.choose = Some((choose::Choose::new(q), reply)),
|
||||
Ui::Choose(q, reply) => {
|
||||
if let Some(p) = &q.plan {
|
||||
let mut md = vec![];
|
||||
transcript::markdown(p, &mut md);
|
||||
let v = doc_view::DocView::new(
|
||||
"plan",
|
||||
md,
|
||||
vec![
|
||||
(KeyCode::Enter, "enter", "Implement"),
|
||||
(KeyCode::Char('f'), "f", "Feedback"),
|
||||
(KeyCode::Esc, "esc", "Keep planning"),
|
||||
],
|
||||
);
|
||||
app.doc = Some((v, q, reply));
|
||||
} else {
|
||||
app.choose = Some((choose::Choose::new(q), reply))
|
||||
}
|
||||
}
|
||||
Ui::Ev(e) => {
|
||||
if let Event::SubUsage(u) = &e {
|
||||
app.st.usage.add(u);
|
||||
@@ -908,7 +949,10 @@ fn chat_buf(app: &App) -> (Buffer, Vec<bool>) {
|
||||
let lines = app.t.lines(app.expanded, w);
|
||||
let mut cont = vec![];
|
||||
for l in &lines {
|
||||
let n = Paragraph::new(l.clone()).wrap(Wrap { trim: false }).line_count(w).max(1);
|
||||
let n = Paragraph::new(l.clone())
|
||||
.wrap(Wrap { trim: false })
|
||||
.line_count(w)
|
||||
.max(1);
|
||||
cont.push(false);
|
||||
cont.extend(std::iter::repeat(true).take(n - 1));
|
||||
}
|
||||
@@ -942,6 +986,7 @@ fn select_mouse(app: &mut App, m: crossterm::event::MouseEvent) {
|
||||
|| app.sessions.is_some()
|
||||
|| app.choose.is_some()
|
||||
|| app.review.is_some()
|
||||
|| app.doc.is_some()
|
||||
|| app.perm.is_some()
|
||||
{
|
||||
return;
|
||||
@@ -1015,6 +1060,9 @@ fn select_mouse(app: &mut App, m: crossterm::event::MouseEvent) {
|
||||
fn wheel(app: &mut App, m: crossterm::event::MouseEvent, up: bool) {
|
||||
let s = if let Some(agents::View::Detail { scroll, .. }) = &mut app.agents {
|
||||
scroll
|
||||
} else if let Some((v, _, _)) = &mut app.doc {
|
||||
v.wheel(up);
|
||||
return;
|
||||
} else if app.picker.is_some() || app.sessions.is_some() || app.choose.is_some() {
|
||||
return;
|
||||
} else if app.panel.is_some() && inside(app.areas.panel, m.column, m.row) {
|
||||
@@ -1193,6 +1241,8 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option<String> {
|
||||
if app.busy {
|
||||
app.queue.clear();
|
||||
abort.abort();
|
||||
} else if app.state.subs.any_running() {
|
||||
app.state.subs.abort_all();
|
||||
} else if app.ed.buf.is_empty() {
|
||||
app.quit = true;
|
||||
} else {
|
||||
@@ -1206,6 +1256,7 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option<String> {
|
||||
app.queue.clear();
|
||||
abort.abort();
|
||||
}
|
||||
KeyCode::Esc if app.state.subs.any_running() => app.state.subs.abort_all(),
|
||||
KeyCode::Char('o') if ctrl => app.expanded = !app.expanded,
|
||||
KeyCode::Esc if app.panel.is_some() => app.panel = None,
|
||||
KeyCode::Char('j') if ctrl => app.ed.insert("\n"),
|
||||
@@ -1334,7 +1385,7 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
||||
let (c, arg) = cmd
|
||||
.split_once(' ')
|
||||
.map_or((cmd, ""), |(a, b)| (a, b.trim()));
|
||||
if app.busy && !matches!(c, "quit" | "btw" | "yolo" | "auto") {
|
||||
if app.busy && !matches!(c, "quit" | "btw" | "yolo" | "auto" | "plan") {
|
||||
app.t.push(Item::Error("busy; esc to abort first".into()));
|
||||
return;
|
||||
}
|
||||
@@ -1486,6 +1537,24 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
||||
drop(al);
|
||||
app.t.push(Item::Info(m));
|
||||
}
|
||||
"plan" => {
|
||||
let mut al = app.state.allow.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let on = match arg {
|
||||
"on" => true,
|
||||
"off" => false,
|
||||
_ => !al.plan_on(),
|
||||
};
|
||||
al.set_plan(on);
|
||||
drop(al);
|
||||
app.t.push(Item::Info(
|
||||
if on {
|
||||
"plan on: read-only; the plan is shown in full for approval when ready"
|
||||
} else {
|
||||
"plan off"
|
||||
}
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
"yolo" => {
|
||||
let on = app
|
||||
.state
|
||||
@@ -1683,6 +1752,32 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
||||
)));
|
||||
line = r.prompt;
|
||||
}
|
||||
// a prompt starting with the word `plan` turns plan mode on
|
||||
if line
|
||||
.split_whitespace()
|
||||
.next()
|
||||
.is_some_and(|w| w.eq_ignore_ascii_case("plan"))
|
||||
{
|
||||
let mut al = app.state.allow.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if !al.plan_on() {
|
||||
al.set_plan(true);
|
||||
drop(al);
|
||||
app.t.push(Item::Info(
|
||||
"plan on (prompt starts with `plan`): read-only until the plan is approved".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
if app
|
||||
.state
|
||||
.allow
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.plan_on()
|
||||
{
|
||||
line = format!(
|
||||
"[plan mode: read-only. Research, then call exit_plan with the complete plan.]\n{line}"
|
||||
);
|
||||
}
|
||||
app.busy = true;
|
||||
app.since = Instant::now();
|
||||
app.run_tokens = (0, 0);
|
||||
@@ -1929,6 +2024,9 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
|
||||
if let Some(r) = &app.review {
|
||||
r.draw(f);
|
||||
}
|
||||
if let Some((v, _, _)) = &mut app.doc {
|
||||
v.draw(f);
|
||||
}
|
||||
if let Some((p, _)) = &app.perm {
|
||||
p.draw(f, input.y);
|
||||
}
|
||||
@@ -2643,6 +2741,7 @@ mod tests {
|
||||
choose: None,
|
||||
perm: None,
|
||||
review: None,
|
||||
doc: None,
|
||||
probe: false,
|
||||
kbd: false,
|
||||
stats: None,
|
||||
|
||||
@@ -555,7 +555,7 @@ fn advance(cur: Option<usize>, l: &str) -> Option<usize> {
|
||||
}
|
||||
|
||||
/// Minimal markdown: fenced code, headings, bullets, inline `code` and **bold**.
|
||||
fn markdown(s: &str, out: &mut Vec<Line<'static>>) {
|
||||
pub(crate) fn markdown(s: &str, out: &mut Vec<Line<'static>>) {
|
||||
let mut code = false;
|
||||
for l in s.lines() {
|
||||
if l.trim_start().starts_with("```") {
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@
|
||||
packages = [
|
||||
pkgs.git
|
||||
pkgs.stdenv.cc
|
||||
];
|
||||
] ++ lib.optional pkgs.stdenv.hostPlatform.isLinux pkgs.bubblewrap;
|
||||
|
||||
languages.rust.enable = true;
|
||||
}
|
||||
@@ -31,8 +31,12 @@
|
||||
# ponytail: tests skipped (need git/network); enable when hermetic.
|
||||
doCheck = false;
|
||||
# rustls may build aws-lc-sys (cmake) depending on feature set.
|
||||
nativeBuildInputs = [ pkgs.cmake pkgs.perl ];
|
||||
nativeBuildInputs = [ pkgs.cmake pkgs.perl ] ++ pkgs.lib.optionals pkgs.stdenv.hostPlatform.isLinux [ pkgs.makeWrapper ];
|
||||
dontUseCmakeConfigure = true;
|
||||
# bubblewrap sandbox runtime dependency (Linux only).
|
||||
postInstall = pkgs.lib.optionalString pkgs.stdenv.hostPlatform.isLinux ''
|
||||
wrapProgram $out/bin/hx --suffix PATH : ${pkgs.lib.makeBinPath [ pkgs.bubblewrap ]}
|
||||
'';
|
||||
meta = {
|
||||
description = "Minimal Rust coding agent using existing subscriptions";
|
||||
license = pkgs.lib.licenses.unlicense;
|
||||
@@ -67,7 +71,7 @@
|
||||
|
||||
devShells = forAll (pkgs: {
|
||||
default = pkgs.mkShell {
|
||||
packages = with pkgs; [ cargo rustc clippy rustfmt rust-analyzer git ];
|
||||
packages = with pkgs; [ cargo rustc clippy rustfmt rust-analyzer git ] ++ pkgs.lib.optional pkgs.stdenv.hostPlatform.isLinux pkgs.bubblewrap;
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
@@ -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")
|
||||
Executable
+15
@@ -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
|
||||
@@ -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```"]]
|
||||
]
|
||||
Reference in new issue
Block a user