Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0184627f27 | ||
|
|
5d4cdbf10d | ||
|
|
4949a4b558 | ||
|
|
fa8641f803 | ||
|
|
8a9d8fe607 | ||
|
|
36e99fc8af | ||
|
|
1da3d52190 | ||
|
|
f1b3ee0607 | ||
|
|
ddf8bcd92c | ||
|
|
7e0031da2f | ||
|
|
4e4d996a6f | ||
|
|
25936457c9 | ||
|
|
71f05d9a0d | ||
|
|
6978aad27a | ||
|
|
6ebf1c3180 | ||
|
|
15d42c279c | ||
|
|
7218d1433b | ||
|
|
fa0ff339f6 | ||
|
|
93bd2693c5 | ||
|
|
e6ac633bf3 | ||
|
|
ed9a9184d0 | ||
|
|
d4c7df4f96 |
No files matched your search
@@ -106,7 +106,7 @@ fable = false # same as /fable on|off
|
|||||||
|
|
||||||
Permissions: only writes ask. `write`/`edit` and unknown `bash` commands prompt; `read` and read-only `bash` (`ls cat head tail wc grep rg fd pwd echo stat file du df which tree diff`, `git status|log|diff|show|branch|blame|ls-files|rev-parse`) run freely, unless chained/redirected or a path looks secret (`.env*`, `.ssh/`, `.aws/`, `*.pem`, `*.key`, `id_rsa*`, `.netrc`, `.git-credentials`, `auth.json`), which asks first. `--yolo` skips all prompts; `/yolo` toggles it live (also while a turn runs), `!` on a permission prompt allows it and turns yolo on.
|
Permissions: only writes ask. `write`/`edit` and unknown `bash` commands prompt; `read` and read-only `bash` (`ls cat head tail wc grep rg fd pwd echo stat file du df which tree diff`, `git status|log|diff|show|branch|blame|ls-files|rev-parse`) run freely, unless chained/redirected or a path looks secret (`.env*`, `.ssh/`, `.aws/`, `*.pem`, `*.key`, `id_rsa*`, `.netrc`, `.git-credentials`, `auth.json`), which asks first. `--yolo` skips all prompts; `/yolo` toggles it live (also while a turn runs), `!` on a permission prompt allows it and turns yolo on.
|
||||||
|
|
||||||
Auto permissions (`--auto`, `permissions = "auto"`, `/auto [on|off|log]`): nothing prompts for the usual work, and dangerous calls are refused without asking. A refused call returns `blocked by auto mode: <reason>` to the model (also over a stored "always" rule); `/auto log` lists the last 20. Per call, in order: (1) rules block `rm -rf` of home/root/project root/outside the project, `sudo`, raw disk writes and filesystem creation, download piped to a shell, force push, push to main/master, sending `.env`/keys over the network, `npm|cargo publish`, `docker push`, `kubectl delete`, `terraform destroy`, SQL `DROP`, writes to `/etc`, `~/.ssh`, shell rc files, `.git/hooks`; (2) rules allow routine work inside the project (build/test/format, local git, `mkdir`/`mv`/`cp`/`rm` in the project, `write`/`edit` of project files); (3) everything else (unknown binaries, `curl`, `python -c`, `$(..)`, redirects, paths outside the project) goes to one cheap-model request (Haiku/Luna, ~300 input tokens, 20 s timeout) that answers ALLOW or BLOCK; if that fails or is unavailable the normal prompt appears. `--yolo` / `/yolo` still skip everything. With the `claude_cli` provider the same rules apply to claude's tool calls, but no model judge runs (unclear ones ask). Pattern rules are not a sandbox: combine with `[sandbox]` for confinement.
|
Auto permissions (`--auto`, `permissions = "auto"`, `/auto [on|off|log]`): nothing prompts for the usual work, and dangerous calls are refused without asking. A refused call returns `blocked by auto mode: <reason>` to the model (also over a stored "always" rule); `/auto log` lists the last 20. Per call, in order: (1) rules block `rm -rf` of home/root/project root/outside the project, `sudo`, raw disk writes and filesystem creation, download piped to a shell, force push, push to main/master, sending `.env`/keys over the network, `npm|cargo publish`, `docker push`, `kubectl delete`, `terraform destroy`, SQL `DROP`, writes to `/etc`, `~/.ssh`, shell rc files, `.git/hooks`; (2) rules allow routine work inside the project (build/test/format, local git, `mkdir`/`mv`/`cp`/`rm` in the project, `write`/`edit` of project files); (3) everything else (unknown binaries, `curl`, `python -c`, `$(..)`, redirects, paths outside the project) goes to one cheap-model request (Haiku/Luna, ~300 input tokens, 20 s timeout) that answers ALLOW or BLOCK; if that fails or is unavailable the normal prompt appears. `--yolo` / `/yolo` still skip everything. With the `claude_cli` provider claude's tools appear on the event bus (`tool_call` / `tool_result`; hx names `bash{command}`, `write|edit|read{path}`, other tools under claude's name), so extensions can block them (a `block` denies the call with its reason) and NDJSON / `hx stats` see them. Reads are asked too (`--settings` `permissions.ask`; Bash too, claude auto-runs read-only commands like `ls` without asking otherwise). In `-p` there is no prompt and everything is allowed, unless `permissions = "deny"` (every unanswered call is denied) or `permissions = "extensions-only"` (allowed only while a live `tool_call` extension exists). The same rules apply to claude's tool calls, but no model judge runs (unclear ones ask). Pattern rules are not a sandbox: combine with `[sandbox]` for confinement.
|
||||||
|
|
||||||
The model can call `task(prompt, kind)` (or `task(prompts=[…], kind)` to fan out: one subagent per prompt, parallel, answers returned numbered; a lone task blocks the parent, so the tool description steers the model to batches) to run a subagent with a fresh context and get back only its final answer (cut at 8 KB), so big searches don't fill the main context. `explore` (default) is read-only (`read`, `lsp`, `bash`) on the provider's cheapest model (`explore_model` in config); `general` has the parent's tools and model, and the lens runs on its edits. Up to 3 run in parallel, none can start another, a parent abort stops them. Their sessions are written to `<session>.sub/`; `hx stats` shows `task` usage (calls, lone vs. batched turns) and lists them and the footer token counts include them. **Overview:** while any subagent exists, a list sits above the footer (bottom right: spinner/✓, id, kind, task, time, calls, tokens). `ctrl-g` focuses it (`↑↓`, `enter` opens, `esc` closes); the detail view shows that agent's live transcript. Typing there messages the agent: while it runs the text is delivered at its next turn end (like steering the main agent), after it finished it continues that agent's conversation. `ctrl-c` aborts that agent only; `ctrl-s` sends its last answer to the main chat as `[subagent N] …`. NDJSON/RPC carry no per-agent events yet.
|
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.
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"version": "0.1.5",
|
"version": "0.1.10",
|
||||||
"sha256": {
|
"sha256": {
|
||||||
"aarch64-apple-darwin": "106d0f4156b687a7a5e1ef8cdd9fcf5f00408afdb320f93e885acdd892b353a1",
|
"aarch64-apple-darwin": "b0192269b031068f5799ac61b70d85f9e5364b17d1634701084f76b3707bf063",
|
||||||
"x86_64-unknown-linux-musl": "2a86641064692c52c4455b327856be772ff75f93572bdad5836e2a5124f6c3ba"
|
"x86_64-unknown-linux-musl": "e42f35a2df69ceeed24004ec1ab5cb7c043133fda2f7acd52a5b7fe62ce04109"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -25,6 +25,14 @@ pub type Spawner = Arc<
|
|||||||
+ Sync,
|
+ 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 {
|
pub struct ClaudeCli {
|
||||||
spawner: Option<Spawner>,
|
spawner: Option<Spawner>,
|
||||||
bin: String,
|
bin: String,
|
||||||
@@ -115,6 +123,18 @@ fn tool_line(b: &Value) -> String {
|
|||||||
format!("{name}: {d}")
|
format!("{name}: {d}")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Tool result content: a string or a list of `{type: "text", text}` blocks.
|
||||||
|
fn result_text(c: &Value) -> String {
|
||||||
|
match c.as_array() {
|
||||||
|
Some(a) => a
|
||||||
|
.iter()
|
||||||
|
.filter_map(|b| b["text"].as_str())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\n"),
|
||||||
|
None => c.as_str().unwrap_or_default().to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn usage(u: &Value) -> Usage {
|
fn usage(u: &Value) -> Usage {
|
||||||
let n = |k: &str| u[k].as_u64().unwrap_or(0);
|
let n = |k: &str| u[k].as_u64().unwrap_or(0);
|
||||||
Usage {
|
Usage {
|
||||||
@@ -184,9 +204,18 @@ impl Provider for ClaudeCli {
|
|||||||
let cfg = json!({"mcpServers": {"hx": {"command": c, "args": a, "env": env}}});
|
let cfg = json!({"mcpServers": {"hx": {"command": c, "args": a, "env": env}}});
|
||||||
cmd.args(["--mcp-config", &cfg.to_string()]);
|
cmd.args(["--mcp-config", &cfg.to_string()]);
|
||||||
if !env.is_null() {
|
if !env.is_null() {
|
||||||
|
// reads in the project run without a prompt by default; "ask" sends them to hx too
|
||||||
|
// ponytail: unverified against a real claude (not installed on the dev box)
|
||||||
cmd.args(["--permission-prompt-tool", "mcp__hx__approve"]);
|
cmd.args(["--permission-prompt-tool", "mcp__hx__approve"]);
|
||||||
|
cmd.args([
|
||||||
|
"--settings",
|
||||||
|
r#"{"permissions":{"ask":["Bash","Read","Grep","Glob","LS"]}}"#,
|
||||||
|
]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if PLAN.load(std::sync::atomic::Ordering::Relaxed) {
|
||||||
|
cmd.args(["--permission-mode", "plan"]);
|
||||||
|
}
|
||||||
cmd.args(&self.args)
|
cmd.args(&self.args)
|
||||||
.arg("--")
|
.arg("--")
|
||||||
.arg(prompt(&req.messages, sid.is_some()))
|
.arg(prompt(&req.messages, sid.is_some()))
|
||||||
@@ -212,6 +241,8 @@ impl Provider for ClaudeCli {
|
|||||||
// usage of the last API request: the real context size (`result` sums all requests)
|
// usage of the last API request: the real context size (`result` sums all requests)
|
||||||
let mut last: Option<Value> = None;
|
let mut last: Option<Value> = None;
|
||||||
let mut quota = Quota::default();
|
let mut quota = Quota::default();
|
||||||
|
// tool_use blocks by id, completed by the `user` message carrying the result
|
||||||
|
let mut uses: std::collections::HashMap<String, (String, Value)> = Default::default();
|
||||||
while let Ok(Some(l)) = lines.next_line().await {
|
while let Ok(Some(l)) = lines.next_line().await {
|
||||||
let Ok(v) = serde_json::from_str::<Value>(&l) else {
|
let Ok(v) = serde_json::from_str::<Value>(&l) else {
|
||||||
continue;
|
continue;
|
||||||
@@ -250,12 +281,37 @@ impl Provider for ClaudeCli {
|
|||||||
}
|
}
|
||||||
for b in v["message"]["content"].as_array().into_iter().flatten() {
|
for b in v["message"]["content"].as_array().into_iter().flatten() {
|
||||||
if b["type"] == "tool_use" {
|
if b["type"] == "tool_use" {
|
||||||
|
uses.insert(
|
||||||
|
b["id"].as_str().unwrap_or_default().into(),
|
||||||
|
(
|
||||||
|
b["name"].as_str().unwrap_or("tool").into(),
|
||||||
|
b["input"].clone(),
|
||||||
|
),
|
||||||
|
);
|
||||||
let _ = tx.send(Ok(StreamEvent::TextDelta {
|
let _ = tx.send(Ok(StreamEvent::TextDelta {
|
||||||
text: format!("\n[claude {}]\n", tool_line(b)),
|
text: format!("\n[claude {}]\n", tool_line(b)),
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Some("user") => {
|
||||||
|
for b in v["message"]["content"].as_array().into_iter().flatten() {
|
||||||
|
let id = b["tool_use_id"].as_str().unwrap_or_default();
|
||||||
|
if b["type"] != "tool_result" {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some((name, input)) = uses.remove(id) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let _ = tx.send(Ok(StreamEvent::ToolRun {
|
||||||
|
id: id.into(),
|
||||||
|
name,
|
||||||
|
input,
|
||||||
|
content: result_text(&b["content"]),
|
||||||
|
is_error: b["is_error"].as_bool().unwrap_or(false),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
Some("rate_limit_event") => {
|
Some("rate_limit_event") => {
|
||||||
if let Some(w) = window(&v) {
|
if let Some(w) = window(&v) {
|
||||||
quota.windows.retain(|x| x.label != w.label);
|
quota.windows.retain(|x| x.label != w.label);
|
||||||
|
|||||||
@@ -258,6 +258,15 @@ pub enum StreamEvent {
|
|||||||
id: String,
|
id: String,
|
||||||
name: String,
|
name: String,
|
||||||
},
|
},
|
||||||
|
/// A tool the provider ran itself (`claude_cli`): raw tool name and input plus its result.
|
||||||
|
/// The agent turns it into `ToolCall` / `ToolResult` events; it is not part of the message.
|
||||||
|
ToolRun {
|
||||||
|
id: String,
|
||||||
|
name: String,
|
||||||
|
input: serde_json::Value,
|
||||||
|
content: String,
|
||||||
|
is_error: bool,
|
||||||
|
},
|
||||||
/// Rate-limit / credit snapshot from the response headers (sent first, when present).
|
/// Rate-limit / credit snapshot from the response headers (sent first, when present).
|
||||||
Quota(Quota),
|
Quota(Quota),
|
||||||
Done {
|
Done {
|
||||||
|
|||||||
+28
-13
@@ -474,6 +474,17 @@ fn pricing(model: &str) -> Option<hx_ai::Pricing> {
|
|||||||
static COMPAT: std::sync::OnceLock<hx_ai::openai_compat::Config> = std::sync::OnceLock::new();
|
static COMPAT: std::sync::OnceLock<hx_ai::openai_compat::Config> = std::sync::OnceLock::new();
|
||||||
/// `codemode` from config: also offer the codemode tool to claude.
|
/// `codemode` from config: also offer the codemode tool to claude.
|
||||||
static CODEMODE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
static CODEMODE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||||
|
/// claude_cli sees only the `hx mcp-serve` tools: MCP is script-only with codemode, else `mcp__hx__*`.
|
||||||
|
fn via() -> hx_mcp::Via {
|
||||||
|
match (
|
||||||
|
CLAUDE_CLI.get().is_some(),
|
||||||
|
CODEMODE.get().copied().unwrap_or(false),
|
||||||
|
) {
|
||||||
|
(true, true) => hx_mcp::Via::Codemode,
|
||||||
|
(true, false) => hx_mcp::Via::ClaudeCli,
|
||||||
|
_ => hx_mcp::Via::Direct,
|
||||||
|
}
|
||||||
|
}
|
||||||
/// `claude_cli` from config: extra args for the `claude` binary.
|
/// `claude_cli` from config: extra args for the `claude` binary.
|
||||||
static CLAUDE_CLI: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
|
static CLAUDE_CLI: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
|
||||||
|
|
||||||
@@ -584,6 +595,7 @@ async fn main() -> Result<()> {
|
|||||||
);
|
);
|
||||||
print!("{}", hx_core::stats::task_report(&Session::open(&session)?));
|
print!("{}", hx_core::stats::task_report(&Session::open(&session)?));
|
||||||
print!("{}", hx_core::stats::route_report(&session));
|
print!("{}", hx_core::stats::route_report(&session));
|
||||||
|
print!("{}", hx_core::stats::claude_report(&session));
|
||||||
print!("{}", hx_core::stats::sub_report(&session));
|
print!("{}", hx_core::stats::sub_report(&session));
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
@@ -749,21 +761,21 @@ async fn main() -> Result<()> {
|
|||||||
.permit
|
.permit
|
||||||
.set(hx_core::approve::remote_permit(p.into()));
|
.set(hx_core::approve::remote_permit(p.into()));
|
||||||
}
|
}
|
||||||
if std::env::var_os("HX_CODEMODE").is_some() {
|
// claude keeps its own tools; hx's MCP servers are added directly, or only through `codemode`
|
||||||
// claude keeps its own tools; only `codemode` is added, and scripts may call the hx tools
|
|
||||||
let cfg = Config::load(&cwd)?;
|
let cfg = Config::load(&cwd)?;
|
||||||
let hub = Arc::new(
|
let mut servers =
|
||||||
hx_mcp::Hub::start(
|
hx_mcp::config::load(&context::hx_home(), &cwd).map_err(anyhow::Error::msg)?;
|
||||||
hx_mcp::config::load(&context::hx_home(), &cwd)
|
// a server entry that is hx itself would spawn mcp-serve recursively
|
||||||
.map_err(anyhow::Error::msg)?,
|
servers.retain(|_, s| !s.args.iter().any(|a| a == "mcp-serve"));
|
||||||
)
|
let hub = Arc::new(hx_mcp::Hub::start(servers).await);
|
||||||
.await,
|
if std::env::var_os("HX_CODEMODE").is_some() {
|
||||||
);
|
|
||||||
let mut all = hx_tools::registry();
|
let mut all = hx_tools::registry();
|
||||||
hx_tools::web::register(&mut all, web_search(&cfg));
|
hx_tools::web::register(&mut all, web_search(&cfg));
|
||||||
hub.register(&mut all);
|
hub.register(&mut all);
|
||||||
all.add(hx_lens::LspTool::new(mgr.clone()));
|
all.add(hx_lens::LspTool::new(mgr.clone()));
|
||||||
reg.add(hx_tools::codemode::Codemode::new(&all));
|
reg.add(hx_tools::codemode::Codemode::new(&all));
|
||||||
|
} else {
|
||||||
|
hub.register(&mut reg);
|
||||||
}
|
}
|
||||||
hx_mcp::serve::serve(
|
hx_mcp::serve::serve(
|
||||||
reg,
|
reg,
|
||||||
@@ -917,7 +929,7 @@ async fn main() -> Result<()> {
|
|||||||
mcp.wait_all(std::time::Duration::from_secs(1)).await;
|
mcp.wait_all(std::time::Duration::from_secs(1)).await;
|
||||||
trace("mcp");
|
trace("mcp");
|
||||||
mcp.register(&mut agent.tools);
|
mcp.register(&mut agent.tools);
|
||||||
let idx = mcp.system_prompt();
|
let idx = mcp.system_prompt_for(via());
|
||||||
if !idx.is_empty() {
|
if !idx.is_empty() {
|
||||||
agent.append_system(&idx);
|
agent.append_system(&idx);
|
||||||
}
|
}
|
||||||
@@ -1004,7 +1016,7 @@ async fn main() -> Result<()> {
|
|||||||
{
|
{
|
||||||
// children get the parent's tools as of now (no `task`, so no recursion)
|
// children get the parent's tools as of now (no `task`, so no recursion)
|
||||||
let mut general = agent.tools.clone();
|
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();
|
let mut explore = agent.tools.clone();
|
||||||
explore.retain(|n| hx_core::subagent::EXPLORE_TOOLS.contains(&n));
|
explore.retain(|n| hx_core::subagent::EXPLORE_TOOLS.contains(&n));
|
||||||
let role = |model: String, tools, base: &str| hx_core::subagent::Role {
|
let role = |model: String, tools, base: &str| hx_core::subagent::Role {
|
||||||
@@ -1085,8 +1097,11 @@ async fn main() -> Result<()> {
|
|||||||
// claude asks here (via `hx mcp-serve`) before running its tools
|
// claude asks here (via `hx mcp-serve`) before running its tools
|
||||||
let (p, cx) = (hx_core::approve::sock_path(), agent.cx.clone());
|
let (p, cx) = (hx_core::approve::sock_path(), agent.cx.clone());
|
||||||
let _ = CLAUDE_CX.set(cx.clone());
|
let _ = CLAUDE_CX.set(cx.clone());
|
||||||
|
let bus = agent.bus.clone();
|
||||||
|
// only -p has no prompt; `permissions = "deny" | "extensions-only"` closes it
|
||||||
|
let mode = hx_core::approve::Unanswered::from_config(cfg.permissions.as_deref());
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let _ = hx_core::approve::serve(&p, cx).await;
|
let _ = hx_core::approve::serve(&p, cx, bus, mode).await;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
let Some(prompt) = cli.print else {
|
let Some(prompt) = cli.print else {
|
||||||
@@ -1151,7 +1166,7 @@ async fn main() -> Result<()> {
|
|||||||
.unwrap_or(context::DEFAULT_PROMPT),
|
.unwrap_or(context::DEFAULT_PROMPT),
|
||||||
context::prompt_tail(&context::hx_home(), &cwd)
|
context::prompt_tail(&context::hx_home(), &cwd)
|
||||||
);
|
);
|
||||||
let idx = mcp.system_prompt();
|
let idx = mcp.system_prompt_for(via());
|
||||||
if !idx.is_empty() {
|
if !idx.is_empty() {
|
||||||
sys.push_str("\n\n");
|
sys.push_str("\n\n");
|
||||||
sys.push_str(&idx);
|
sys.push_str(&idx);
|
||||||
|
|||||||
@@ -378,6 +378,49 @@ impl Agent {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A tool `claude_cli` ran itself: `ToolCall` (unless the permission bridge sent it before the
|
||||||
|
/// run) and `ToolResult`, in hx' vocabulary. Informational: the tool already ran.
|
||||||
|
async fn claude_tool(
|
||||||
|
&self,
|
||||||
|
id: String,
|
||||||
|
name: &str,
|
||||||
|
input: &serde_json::Value,
|
||||||
|
content: String,
|
||||||
|
is_error: bool,
|
||||||
|
) {
|
||||||
|
let (name, args) = crate::approve::hx_call(name, input);
|
||||||
|
let seen = self
|
||||||
|
.cx
|
||||||
|
.state
|
||||||
|
.claude_seen
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|e| e.into_inner())
|
||||||
|
.remove(&id);
|
||||||
|
if !seen {
|
||||||
|
self.emit(Event::ToolCall {
|
||||||
|
id: id.clone(),
|
||||||
|
name: name.clone(),
|
||||||
|
args: args.clone(),
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
crate::stats::log_claude_tool(
|
||||||
|
self.session.path(),
|
||||||
|
&name,
|
||||||
|
args.to_string().len(),
|
||||||
|
content.len(),
|
||||||
|
is_error,
|
||||||
|
);
|
||||||
|
self.emit(Event::ToolResult {
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
args,
|
||||||
|
content,
|
||||||
|
is_error,
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
|
||||||
async fn emit(&self, ev: Event) -> crate::hook::Outcome {
|
async fn emit(&self, ev: Event) -> crate::hook::Outcome {
|
||||||
self.bus.emit(ev).await
|
self.bus.emit(ev).await
|
||||||
}
|
}
|
||||||
@@ -417,6 +460,10 @@ impl Agent {
|
|||||||
/// An abort ends this run only; the next `run` starts un-aborted.
|
/// An abort ends this run only; the next `run` starts un-aborted.
|
||||||
pub async fn run(&mut self, prompt: impl Into<String>) -> Result<Message, Error> {
|
pub async fn run(&mut self, prompt: impl Into<String>) -> Result<Message, Error> {
|
||||||
let r = self.run_inner(prompt.into()).await;
|
let r = self.run_inner(prompt.into()).await;
|
||||||
|
self.emit(Event::RunEnd {
|
||||||
|
aborted: matches!(r, Err(Error::Aborted)),
|
||||||
|
})
|
||||||
|
.await;
|
||||||
self.abort_tx
|
self.abort_tx
|
||||||
.send_if_modified(|a| std::mem::replace(a, false));
|
.send_if_modified(|a| std::mem::replace(a, false));
|
||||||
r
|
r
|
||||||
@@ -456,6 +503,10 @@ impl Agent {
|
|||||||
if let StreamEvent::Done { message, stop, usage } = &ev {
|
if let StreamEvent::Done { message, stop, usage } = &ev {
|
||||||
done = Some((message.clone(), *stop, usage.clone()));
|
done = Some((message.clone(), *stop, usage.clone()));
|
||||||
}
|
}
|
||||||
|
if let StreamEvent::ToolRun { id, name, input, content, is_error } = ev {
|
||||||
|
self.claude_tool(id, &name, &input, content, is_error).await;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
self.emit(Event::Stream(ev)).await;
|
self.emit(Event::Stream(ev)).await;
|
||||||
}
|
}
|
||||||
None => break,
|
None => break,
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
//! calls the `approve` tool of `hx mcp-serve`, which forwards the question over a Unix socket to the
|
//! calls the `approve` tool of `hx mcp-serve`, which forwards the question over a Unix socket to the
|
||||||
//! hx process that owns the TUI; that one shows the usual permission prompt.
|
//! hx process that owns the TUI; that one shows the usual permission prompt.
|
||||||
|
|
||||||
|
use crate::hook::{Bus, Event};
|
||||||
use crate::permit::Request;
|
use crate::permit::Request;
|
||||||
use crate::tool::{Tool, ToolCtx, ToolResult, gate_why};
|
use crate::tool::{Tool, ToolCtx, ToolResult, gate_why};
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
@@ -58,8 +59,64 @@ pub fn question(tool: &str, input: &Value) -> Option<Request> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Answer permission questions on `path` until the process ends.
|
/// `claude_cli` tool call in hx' vocabulary (`Bash` -> `bash {command}`); other tools keep claude's name.
|
||||||
pub async fn serve(path: &Path, cx: ToolCtx) -> std::io::Result<()> {
|
pub fn hx_call(tool: &str, input: &Value) -> (String, Value) {
|
||||||
|
let s = |k: &str| input[k].as_str().unwrap_or_default().to_string();
|
||||||
|
let path = || {
|
||||||
|
s(if input["file_path"].is_string() {
|
||||||
|
"file_path"
|
||||||
|
} else {
|
||||||
|
"notebook_path"
|
||||||
|
})
|
||||||
|
};
|
||||||
|
match tool {
|
||||||
|
"Bash" => ("bash".into(), json!({"command": s("command")})),
|
||||||
|
"Write" => ("write".into(), json!({"path": path()})),
|
||||||
|
"Edit" | "MultiEdit" | "NotebookEdit" => ("edit".into(), json!({"path": path()})),
|
||||||
|
"Read" => ("read".into(), json!({"path": path()})),
|
||||||
|
t => (t.into(), input.clone()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the bridge does with a call nobody answered (no permission prompt, `-p`).
|
||||||
|
/// `permissions` in config.toml: absent = allow (compatible), "deny", "extensions-only".
|
||||||
|
#[derive(Clone, Copy, Default, PartialEq, Debug)]
|
||||||
|
pub enum Unanswered {
|
||||||
|
#[default]
|
||||||
|
Allow,
|
||||||
|
Deny,
|
||||||
|
/// allow only while a live extension guards `tool_call`
|
||||||
|
ExtensionsOnly,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Unanswered {
|
||||||
|
/// Unknown values (typos) deny: this is a safety setting, failing open would hide the mistake.
|
||||||
|
/// `ask`, `auto` and `yolo` are the interactive modes and leave `-p` as it was.
|
||||||
|
pub fn from_config(s: Option<&str>) -> Self {
|
||||||
|
match s {
|
||||||
|
None | Some("ask" | "auto" | "yolo") => Self::Allow,
|
||||||
|
Some("extensions-only") => Self::ExtensionsOnly,
|
||||||
|
Some(_) => Self::Deny,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check(self, bus: &Bus) -> Result<(), String> {
|
||||||
|
match self {
|
||||||
|
Self::Allow => Ok(()),
|
||||||
|
Self::Deny => Err("no permission prompt available (permissions = \"deny\")".into()),
|
||||||
|
Self::ExtensionsOnly => match bus.guards() {
|
||||||
|
(n, true) if n > 0 => Ok(()),
|
||||||
|
_ => Err(
|
||||||
|
"no live extension guards tool_call (permissions = \"extensions-only\")".into(),
|
||||||
|
),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Answer permission questions on `path` until the process ends. Every question is first sent to
|
||||||
|
/// `bus` as a `ToolCall` (extensions can block it), then goes through the usual prompt.
|
||||||
|
pub async fn serve(path: &Path, cx: ToolCtx, bus: Bus, mode: Unanswered) -> std::io::Result<()> {
|
||||||
let _ = std::fs::remove_file(path);
|
let _ = std::fs::remove_file(path);
|
||||||
let l = UnixListener::bind(path)?;
|
let l = UnixListener::bind(path)?;
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
@@ -69,7 +126,7 @@ pub async fn serve(path: &Path, cx: ToolCtx) -> std::io::Result<()> {
|
|||||||
}
|
}
|
||||||
loop {
|
loop {
|
||||||
let (c, _) = l.accept().await?;
|
let (c, _) = l.accept().await?;
|
||||||
let cx = cx.clone();
|
let (cx, bus) = (cx.clone(), bus.clone());
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let (r, mut w) = c.into_split();
|
let (r, mut w) = c.into_split();
|
||||||
let mut line = String::new();
|
let mut line = String::new();
|
||||||
@@ -79,7 +136,41 @@ pub async fn serve(path: &Path, cx: ToolCtx) -> std::io::Result<()> {
|
|||||||
let v: Value = serde_json::from_str(&line).unwrap_or_default();
|
let v: Value = serde_json::from_str(&line).unwrap_or_default();
|
||||||
// hx tools run by `codemode` inside mcp-serve ask for their own permission
|
// hx tools run by `codemode` inside mcp-serve ask for their own permission
|
||||||
let mut input = None;
|
let mut input = None;
|
||||||
let ok = if v["tool_name"] == "AskUserQuestion" {
|
let tool = v["tool_name"].as_str().unwrap_or_default();
|
||||||
|
let unprompted = |cx: &ToolCtx| {
|
||||||
|
if cx.state.permit.get().is_none() {
|
||||||
|
mode.check(&bus)
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let mut blocked = None;
|
||||||
|
if tool != "AskUserQuestion" && v.get("permit").is_none() {
|
||||||
|
let (name, args) = hx_call(tool, &v["input"]);
|
||||||
|
let id = v["tool_use_id"].as_str().unwrap_or_default();
|
||||||
|
if !id.is_empty() {
|
||||||
|
cx.state
|
||||||
|
.claude_seen
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|e| e.into_inner())
|
||||||
|
.insert(id.into());
|
||||||
|
}
|
||||||
|
let o = bus
|
||||||
|
.emit(Event::ToolCall {
|
||||||
|
id: id.into(),
|
||||||
|
name,
|
||||||
|
args,
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
blocked = o.blocked.map(|r| format!("blocked: {r}"));
|
||||||
|
}
|
||||||
|
let ok = if let Some(r) = blocked {
|
||||||
|
Err(r)
|
||||||
|
} else if let Err(r) = unprompted(&cx) {
|
||||||
|
Err(r)
|
||||||
|
} else if tool == "ExitPlanMode" {
|
||||||
|
exit_plan(&cx, v["input"]["plan"].as_str().unwrap_or_default()).await
|
||||||
|
} else if v["tool_name"] == "AskUserQuestion" {
|
||||||
// claude's own question tool: show hx's popup, hand the answers back as input
|
// claude's own question tool: show hx's popup, hand the answers back as input
|
||||||
input = ask(&cx, &v["input"]).await;
|
input = ask(&cx, &v["input"]).await;
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -121,6 +212,38 @@ pub async fn serve(path: &Path, cx: ToolCtx) -> std::io::Result<()> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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)).
|
/// Run each `AskUserQuestion` question through the popup; `input` plus `answers` (question -> label(s)).
|
||||||
/// None = no frontend or dismissed.
|
/// None = no frontend or dismissed.
|
||||||
async fn ask(cx: &ToolCtx, input: &Value) -> Option<Value> {
|
async fn ask(cx: &ToolCtx, input: &Value) -> Option<Value> {
|
||||||
@@ -138,6 +261,7 @@ async fn ask(cx: &ToolCtx, input: &Value) -> Option<Value> {
|
|||||||
options: options.collect(),
|
options: options.collect(),
|
||||||
multi: q["multiSelect"].as_bool().unwrap_or(false),
|
multi: q["multiSelect"].as_bool().unwrap_or(false),
|
||||||
other: true,
|
other: true,
|
||||||
|
plan: None,
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.ok()??;
|
.ok()??;
|
||||||
@@ -235,6 +359,30 @@ mod tests {
|
|||||||
assert_eq!(question("Foo", &json!({})).unwrap().rule, "claude:Foo");
|
assert_eq!(question("Foo", &json!({})).unwrap().rule, "claude:Foo");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn claude_calls_use_hx_names() {
|
||||||
|
assert_eq!(
|
||||||
|
hx_call("Bash", &json!({"command": "ls", "x": 1})),
|
||||||
|
("bash".into(), json!({"command": "ls"}))
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
hx_call("MultiEdit", &json!({"file_path": "a"})),
|
||||||
|
("edit".into(), json!({"path": "a"}))
|
||||||
|
);
|
||||||
|
assert_eq!(hx_call("Read", &json!({"file_path": "a"})).0, "read");
|
||||||
|
assert_eq!(
|
||||||
|
hx_call("WebFetch", &json!({"url": "u"})),
|
||||||
|
("WebFetch".into(), json!({"url": "u"}))
|
||||||
|
);
|
||||||
|
assert_eq!(Unanswered::from_config(Some("deny")), Unanswered::Deny);
|
||||||
|
assert_eq!(Unanswered::from_config(None), Unanswered::Allow);
|
||||||
|
assert_eq!(Unanswered::from_config(Some("auto")), Unanswered::Allow);
|
||||||
|
assert_eq!(
|
||||||
|
Unanswered::from_config(Some("extrensions-only")),
|
||||||
|
Unanswered::Deny
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn ask_user_question_uses_popup() {
|
async fn ask_user_question_uses_popup() {
|
||||||
let cx = ToolCtx {
|
let cx = ToolCtx {
|
||||||
@@ -249,6 +397,24 @@ mod tests {
|
|||||||
assert_eq!(ask(&cx, &inp).await.unwrap()["answers"]["Which?"], "B");
|
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]
|
#[tokio::test]
|
||||||
async fn socket_round_trip_allows_and_denies() {
|
async fn socket_round_trip_allows_and_denies() {
|
||||||
use crate::permit::Decision;
|
use crate::permit::Decision;
|
||||||
@@ -268,7 +434,7 @@ mod tests {
|
|||||||
let path =
|
let path =
|
||||||
std::env::temp_dir().join(format!("hx-approve-test-{}.sock", std::process::id()));
|
std::env::temp_dir().join(format!("hx-approve-test-{}.sock", std::process::id()));
|
||||||
let (p, c) = (path.clone(), cx.clone());
|
let (p, c) = (path.clone(), cx.clone());
|
||||||
tokio::spawn(async move { serve(&p, c).await });
|
tokio::spawn(async move { serve(&p, c, Bus::default(), Unanswered::Allow).await });
|
||||||
while !path.exists() {
|
while !path.exists() {
|
||||||
tokio::task::yield_now().await;
|
tokio::task::yield_now().await;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -82,6 +82,11 @@ pub fn builtins(models: &[&str]) -> Vec<CmdSpec> {
|
|||||||
"auto permissions: refuse dangerous calls, run safe ones",
|
"auto permissions: refuse dangerous calls, run safe ones",
|
||||||
Enum(vec!["on".into(), "off".into(), "log".into()]),
|
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("yolo", "toggle: run every tool without asking", None),
|
||||||
b(
|
b(
|
||||||
"sandbox",
|
"sandbox",
|
||||||
|
|||||||
@@ -161,6 +161,12 @@ impl Extension {
|
|||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl Hook for Extension {
|
impl Hook for Extension {
|
||||||
|
fn guard(&self) -> Option<bool> {
|
||||||
|
self.subscribe
|
||||||
|
.iter()
|
||||||
|
.any(|s| s == "tool_call" || s == "*")
|
||||||
|
.then(|| self.alive.load(Ordering::SeqCst))
|
||||||
|
}
|
||||||
async fn on(&self, ev: &Event) -> HookAction {
|
async fn on(&self, ev: &Event) -> HookAction {
|
||||||
if !self.subscribe.iter().any(|s| s == ev.kind() || s == "*") {
|
if !self.subscribe.iter().any(|s| s == ev.kind() || s == "*") {
|
||||||
return HookAction::Continue;
|
return HookAction::Continue;
|
||||||
|
|||||||
@@ -26,6 +26,10 @@ pub enum Event {
|
|||||||
TurnEnd,
|
TurnEnd,
|
||||||
/// Model finished without tool calls. `Inject` makes the agent continue.
|
/// Model finished without tool calls. `Inject` makes the agent continue.
|
||||||
AgentEnd,
|
AgentEnd,
|
||||||
|
/// A run ended for any reason (done, error, abort). Fires after the last turn.
|
||||||
|
RunEnd {
|
||||||
|
aborted: bool,
|
||||||
|
},
|
||||||
/// Streaming output from the model (UI).
|
/// Streaming output from the model (UI).
|
||||||
Stream(StreamEvent),
|
Stream(StreamEvent),
|
||||||
Message(Message),
|
Message(Message),
|
||||||
@@ -57,6 +61,7 @@ impl Event {
|
|||||||
"content": content, "is_error": is_error}),
|
"content": content, "is_error": is_error}),
|
||||||
Event::TurnEnd => json!({"type": "turn_end"}),
|
Event::TurnEnd => json!({"type": "turn_end"}),
|
||||||
Event::AgentEnd => json!({"type": "agent_end"}),
|
Event::AgentEnd => json!({"type": "agent_end"}),
|
||||||
|
Event::RunEnd { aborted } => json!({"type": "run_end", "aborted": aborted}),
|
||||||
Event::Stream(e) => json!({"type": "stream", "event": e}),
|
Event::Stream(e) => json!({"type": "stream", "event": e}),
|
||||||
Event::Message(m) => json!({"type": "message", "message": m}),
|
Event::Message(m) => json!({"type": "message", "message": m}),
|
||||||
Event::Info(t) => json!({"type": "info", "text": t}),
|
Event::Info(t) => json!({"type": "info", "text": t}),
|
||||||
@@ -74,6 +79,7 @@ impl Event {
|
|||||||
Event::ToolResult { .. } => "tool_result",
|
Event::ToolResult { .. } => "tool_result",
|
||||||
Event::TurnEnd => "turn_end",
|
Event::TurnEnd => "turn_end",
|
||||||
Event::AgentEnd => "agent_end",
|
Event::AgentEnd => "agent_end",
|
||||||
|
Event::RunEnd { .. } => "run_end",
|
||||||
Event::Stream(_) => "stream",
|
Event::Stream(_) => "stream",
|
||||||
Event::Message(_) => "message",
|
Event::Message(_) => "message",
|
||||||
Event::Info(_) => "info",
|
Event::Info(_) => "info",
|
||||||
@@ -94,11 +100,16 @@ pub enum HookAction {
|
|||||||
#[async_trait]
|
#[async_trait]
|
||||||
pub trait Hook: Send + Sync {
|
pub trait Hook: Send + Sync {
|
||||||
async fn on(&self, ev: &Event) -> HookAction;
|
async fn on(&self, ev: &Event) -> HookAction;
|
||||||
|
/// `Some(alive)` if this hook guards `tool_call` (extensions subscribed to it).
|
||||||
|
fn guard(&self) -> Option<bool> {
|
||||||
|
None
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Clones share the hook list (the permission bridge emits on the agent's bus).
|
||||||
#[derive(Default, Clone)]
|
#[derive(Default, Clone)]
|
||||||
pub struct Bus {
|
pub struct Bus {
|
||||||
hooks: Vec<Arc<dyn Hook>>,
|
hooks: Arc<std::sync::RwLock<Vec<Arc<dyn Hook>>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Aggregate outcome of dispatching one event to all hooks.
|
/// Aggregate outcome of dispatching one event to all hooks.
|
||||||
@@ -111,19 +122,29 @@ pub struct Outcome {
|
|||||||
|
|
||||||
impl Bus {
|
impl Bus {
|
||||||
pub fn add_arc(&mut self, h: Arc<dyn Hook>) -> &mut Self {
|
pub fn add_arc(&mut self, h: Arc<dyn Hook>) -> &mut Self {
|
||||||
self.hooks.push(h);
|
self.hooks
|
||||||
|
.write()
|
||||||
|
.unwrap_or_else(|e| e.into_inner())
|
||||||
|
.push(h);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
pub fn add(&mut self, h: impl Hook + 'static) -> &mut Self {
|
pub fn add(&mut self, h: impl Hook + 'static) -> &mut Self {
|
||||||
self.hooks.push(Arc::new(h));
|
self.add_arc(Arc::new(h))
|
||||||
self
|
}
|
||||||
|
|
||||||
|
/// (number of `tool_call` guards, all of them alive).
|
||||||
|
pub fn guards(&self) -> (usize, bool) {
|
||||||
|
let hooks = self.hooks.read().unwrap_or_else(|e| e.into_inner());
|
||||||
|
let g: Vec<bool> = hooks.iter().filter_map(|h| h.guard()).collect();
|
||||||
|
(g.len(), g.iter().all(|a| *a))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Hooks run in registration order. First `Block` wins; `Mutate` is visible to later hooks.
|
/// Hooks run in registration order. First `Block` wins; `Mutate` is visible to later hooks.
|
||||||
pub async fn emit(&self, ev: Event) -> Outcome {
|
pub async fn emit(&self, ev: Event) -> Outcome {
|
||||||
let mut ev = ev;
|
let mut ev = ev;
|
||||||
let mut o = Outcome::default();
|
let mut o = Outcome::default();
|
||||||
for h in &self.hooks {
|
let hooks = self.hooks.read().unwrap_or_else(|e| e.into_inner()).clone();
|
||||||
|
for h in &hooks {
|
||||||
match h.on(&ev).await {
|
match h.on(&ev).await {
|
||||||
HookAction::Continue => {}
|
HookAction::Continue => {}
|
||||||
HookAction::Block(r) => {
|
HookAction::Block(r) => {
|
||||||
|
|||||||
@@ -43,6 +43,8 @@ pub struct Question {
|
|||||||
pub multi: bool,
|
pub multi: bool,
|
||||||
/// offer a free-text "Other" row
|
/// offer a free-text "Other" row
|
||||||
pub other: bool,
|
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.
|
/// Shows a [`Question`]; resolves to the chosen labels / typed text, None when dismissed.
|
||||||
@@ -84,6 +86,8 @@ pub struct State {
|
|||||||
/// ponytail: keyed by command text, so two identical commands running at once share a tail;
|
/// ponytail: keyed by command text, so two identical commands running at once share a tail;
|
||||||
/// key by call id once ToolCtx carries it.
|
/// key by call id once ToolCtx carries it.
|
||||||
pub live: Mutex<HashMap<String, String>>,
|
pub live: Mutex<HashMap<String, String>>,
|
||||||
|
/// `claude_cli` tool_use ids the permission bridge already put on the bus.
|
||||||
|
pub claude_seen: Mutex<std::collections::HashSet<String>>,
|
||||||
/// Structured last lens report for side panels.
|
/// Structured last lens report for side panels.
|
||||||
pub lens: Mutex<LensView>,
|
pub lens: Mutex<LensView>,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -328,6 +328,8 @@ pub struct Allow {
|
|||||||
all_edits: bool,
|
all_edits: bool,
|
||||||
yolo: bool,
|
yolo: bool,
|
||||||
auto: bool,
|
auto: bool,
|
||||||
|
/// Plan mode: read-only until the user approves a plan.
|
||||||
|
plan: bool,
|
||||||
/// Last calls auto mode refused (newest last), for `/auto`.
|
/// Last calls auto mode refused (newest last), for `/auto`.
|
||||||
blocks: Vec<String>,
|
blocks: Vec<String>,
|
||||||
file: Option<PathBuf>,
|
file: Option<PathBuf>,
|
||||||
@@ -345,6 +347,7 @@ impl Allow {
|
|||||||
all_edits: false,
|
all_edits: false,
|
||||||
yolo: false,
|
yolo: false,
|
||||||
auto: false,
|
auto: false,
|
||||||
|
plan: false,
|
||||||
blocks: Vec::new(),
|
blocks: Vec::new(),
|
||||||
file: Some(file),
|
file: Some(file),
|
||||||
}
|
}
|
||||||
@@ -381,6 +384,15 @@ impl Allow {
|
|||||||
self.yolo
|
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 {
|
pub fn auto_on(&self) -> bool {
|
||||||
self.auto
|
self.auto
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -46,6 +46,57 @@ pub fn task_report(s: &Session) -> String {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Append one `claude_cli` tool run to `<session>.claude` (claude runs the tools itself, so they
|
||||||
|
/// are not session messages). Best effort.
|
||||||
|
pub fn log_claude_tool(
|
||||||
|
session: &std::path::Path,
|
||||||
|
name: &str,
|
||||||
|
args: usize,
|
||||||
|
result: usize,
|
||||||
|
err: bool,
|
||||||
|
) {
|
||||||
|
use std::io::Write;
|
||||||
|
if let Ok(mut f) = std::fs::OpenOptions::new()
|
||||||
|
.create(true)
|
||||||
|
.append(true)
|
||||||
|
.open(session.with_extension("claude"))
|
||||||
|
{
|
||||||
|
let _ = writeln!(
|
||||||
|
f,
|
||||||
|
"{}",
|
||||||
|
serde_json::json!({"name": name, "args": args, "result": result, "error": err})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tools claude ran itself (`<session>.claude`): calls, errors/blocks, argument and result bytes per tool.
|
||||||
|
pub fn claude_report(session: &std::path::Path) -> String {
|
||||||
|
let Ok(t) = std::fs::read_to_string(session.with_extension("claude")) else {
|
||||||
|
return String::new();
|
||||||
|
};
|
||||||
|
let mut by: std::collections::BTreeMap<String, [u64; 4]> = Default::default();
|
||||||
|
for v in t
|
||||||
|
.lines()
|
||||||
|
.filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok())
|
||||||
|
{
|
||||||
|
let e = by
|
||||||
|
.entry(v["name"].as_str().unwrap_or("?").into())
|
||||||
|
.or_default();
|
||||||
|
e[0] += 1;
|
||||||
|
e[1] += u64::from(v["error"] == true);
|
||||||
|
e[2] += v["args"].as_u64().unwrap_or(0);
|
||||||
|
e[3] += v["result"].as_u64().unwrap_or(0);
|
||||||
|
}
|
||||||
|
let mut s = String::from("claude tool calls (run by claude, not in the message history):\n");
|
||||||
|
for (n, [c, e, a, r]) in by {
|
||||||
|
let _ = writeln!(
|
||||||
|
s,
|
||||||
|
" {n}: {c} calls, {e} errors/blocked, args {a} B, results {r} B"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
s
|
||||||
|
}
|
||||||
|
|
||||||
/// One line per subagent log in `<session>.sub/` (empty when there are none).
|
/// One line per subagent log in `<session>.sub/` (empty when there are none).
|
||||||
/// Auto-mode choices from `<session>.route`: turns per tier, how often the tier was held back
|
/// Auto-mode choices from `<session>.route`: turns per tier, how often the tier was held back
|
||||||
/// or forced, and how often the next prompt had to go up again (a pick that was too low).
|
/// or forced, and how often the next prompt had to go up again (a pick that was too low).
|
||||||
@@ -406,6 +457,22 @@ pub fn report(s: &Session) -> String {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
#[test]
|
||||||
|
fn claude_tools_are_counted() {
|
||||||
|
let p = std::env::temp_dir().join(format!("hx-claude-stats-{}.jsonl", std::process::id()));
|
||||||
|
let c = p.with_extension("claude");
|
||||||
|
let _ = std::fs::remove_file(&c);
|
||||||
|
assert_eq!(super::claude_report(&p), "");
|
||||||
|
super::log_claude_tool(&p, "bash", 10, 100, false);
|
||||||
|
super::log_claude_tool(&p, "bash", 10, 20, true);
|
||||||
|
let r = super::claude_report(&p);
|
||||||
|
let _ = std::fs::remove_file(&c);
|
||||||
|
assert!(
|
||||||
|
r.contains("bash: 2 calls, 1 errors/blocked, args 20 B, results 120 B"),
|
||||||
|
"{r}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use hx_ai::{Message, Usage};
|
use hx_ai::{Message, Usage};
|
||||||
|
|
||||||
|
|||||||
@@ -93,6 +93,16 @@ pub async fn gate_why(cx: &ToolCtx, req: crate::permit::Request) -> Result<(), S
|
|||||||
use crate::danger::{Verdict, classify};
|
use crate::danger::{Verdict, classify};
|
||||||
use crate::permit::Decision;
|
use crate::permit::Decision;
|
||||||
const DENIED: &str = "denied by the user; do not retry, ask what to do instead";
|
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 {
|
let Some(ask) = cx.state.permit.get() else {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
};
|
};
|
||||||
@@ -263,6 +273,27 @@ mod tests {
|
|||||||
assert!(d.is_error && d.content.contains("denied"));
|
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]
|
#[tokio::test]
|
||||||
async fn auto_mode_blocks_allows_judges_without_prompting() {
|
async fn auto_mode_blocks_allows_judges_without_prompting() {
|
||||||
use crate::danger::Judge;
|
use crate::danger::Judge;
|
||||||
|
|||||||
@@ -370,6 +370,21 @@ pub fn format_findings(v: &[&Finding]) -> String {
|
|||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl Hook for Lens {
|
impl Hook for Lens {
|
||||||
async fn on(&self, ev: &Event) -> HookAction {
|
async fn on(&self, ev: &Event) -> HookAction {
|
||||||
|
// Anything that changed on disk during the run is ours (bash, subagents, an aborted
|
||||||
|
// tool that already wrote), not the user's. Re-baseline the read-guard too.
|
||||||
|
if matches!(ev, Event::TurnEnd | Event::AgentEnd | Event::RunEnd { .. }) {
|
||||||
|
for p in self.watch.scan(&self.seq, Source::Agent) {
|
||||||
|
if let Some(st) = self.state.get() {
|
||||||
|
st.mark_seen(&p);
|
||||||
|
}
|
||||||
|
if matches!(ev, Event::RunEnd { aborted: true }) {
|
||||||
|
self.note(format!(
|
||||||
|
"{} changed by your aborted previous run (may be half-done); re-read it",
|
||||||
|
self.rel(&p)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
match ev {
|
match ev {
|
||||||
Event::ToolResult {
|
Event::ToolResult {
|
||||||
name,
|
name,
|
||||||
@@ -395,7 +410,7 @@ impl Hook for Lens {
|
|||||||
}
|
}
|
||||||
Event::TurnStart => {
|
Event::TurnStart => {
|
||||||
// edits made outside hx while the model was thinking
|
// edits made outside hx while the model was thinking
|
||||||
self.watch.scan(&self.seq);
|
self.watch.scan(&self.seq, Source::External);
|
||||||
HookAction::Continue
|
HookAction::Continue
|
||||||
}
|
}
|
||||||
Event::TurnEnd if self.mode == Mode::TurnEnd => self
|
Event::TurnEnd if self.mode == Mode::TurnEnd => self
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ pub enum Source {
|
|||||||
AgentEdit,
|
AgentEdit,
|
||||||
Format,
|
Format,
|
||||||
Autofix,
|
Autofix,
|
||||||
|
/// Changed during an agent run by something other than a file tool (bash, subagent, aborted tool).
|
||||||
|
Agent,
|
||||||
External,
|
External,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -30,14 +30,14 @@ impl Watch {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Record files whose mtime changed since last seen. Returns them.
|
/// Record files whose mtime changed since last seen. Returns them.
|
||||||
pub fn scan(&self, seq: &SeqLog) -> Vec<PathBuf> {
|
pub fn scan(&self, seq: &SeqLog, src: Source) -> Vec<PathBuf> {
|
||||||
let mut map = self.mtimes.lock().unwrap_or_else(|e| e.into_inner());
|
let mut map = self.mtimes.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
let mut changed = vec![];
|
let mut changed = vec![];
|
||||||
for (p, old) in map.iter_mut() {
|
for (p, old) in map.iter_mut() {
|
||||||
let now = mtime(p);
|
let now = mtime(p);
|
||||||
if now != *old {
|
if now != *old {
|
||||||
*old = now;
|
*old = now;
|
||||||
seq.bump(p, Source::External);
|
seq.bump(p, src);
|
||||||
changed.push(p.clone());
|
changed.push(p.clone());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -54,7 +54,7 @@ impl Watch {
|
|||||||
let mut t = tokio::time::interval(every);
|
let mut t = tokio::time::interval(every);
|
||||||
loop {
|
loop {
|
||||||
t.tick().await;
|
t.tick().await;
|
||||||
w.scan(&seq);
|
w.scan(&seq, Source::External);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -71,16 +71,31 @@ mod tests {
|
|||||||
std::fs::write(&f, "1").unwrap();
|
std::fs::write(&f, "1").unwrap();
|
||||||
let (w, s) = (Watch::default(), SeqLog::default());
|
let (w, s) = (Watch::default(), SeqLog::default());
|
||||||
w.track(f.clone());
|
w.track(f.clone());
|
||||||
assert!(w.scan(&s).is_empty());
|
assert!(w.scan(&s, Source::External).is_empty());
|
||||||
std::thread::sleep(Duration::from_millis(20));
|
std::thread::sleep(Duration::from_millis(20));
|
||||||
std::fs::write(&f, "2").unwrap();
|
std::fs::write(&f, "2").unwrap();
|
||||||
assert_eq!(w.scan(&s), std::slice::from_ref(&f));
|
assert_eq!(w.scan(&s, Source::External), std::slice::from_ref(&f));
|
||||||
assert!(w.scan(&s).is_empty());
|
assert!(w.scan(&s, Source::External).is_empty());
|
||||||
assert_eq!(s.project(), 1);
|
assert_eq!(s.project(), 1);
|
||||||
// our own write: re-baseline, no bump
|
// our own write: re-baseline, no bump
|
||||||
std::thread::sleep(Duration::from_millis(20));
|
std::thread::sleep(Duration::from_millis(20));
|
||||||
std::fs::write(&f, "3").unwrap();
|
std::fs::write(&f, "3").unwrap();
|
||||||
w.track(f);
|
w.track(f);
|
||||||
assert!(w.scan(&s).is_empty());
|
assert!(w.scan(&s, Source::External).is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn agent_scan_not_external() {
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
let f = d.path().join("a.rs");
|
||||||
|
std::fs::write(&f, "1").unwrap();
|
||||||
|
let (w, s) = (Watch::default(), SeqLog::default());
|
||||||
|
w.track(f.clone());
|
||||||
|
std::thread::sleep(Duration::from_millis(20));
|
||||||
|
std::fs::write(&f, "2").unwrap(); // e.g. bash sed, or an aborted edit
|
||||||
|
assert_eq!(w.scan(&s, Source::Agent).len(), 1);
|
||||||
|
// later turn start: nothing left to call external
|
||||||
|
assert!(w.scan(&s, Source::External).is_empty());
|
||||||
|
assert!(s.since(0).len() == 1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -135,6 +135,16 @@ async fn load(cfg: &Server) -> (State, Option<Arc<Client>>) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// How the model reaches the lazy MCP tools.
|
||||||
|
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum Via {
|
||||||
|
Direct,
|
||||||
|
/// claude_cli + codemode: only inside `codemode` scripts
|
||||||
|
Codemode,
|
||||||
|
/// claude_cli without codemode: `mcp__hx__*` tools served by `hx mcp-serve`
|
||||||
|
ClaudeCli,
|
||||||
|
}
|
||||||
|
|
||||||
impl Hub {
|
impl Hub {
|
||||||
/// Connect to all servers in parallel and wait for every one (CLI commands, tests).
|
/// Connect to all servers in parallel and wait for every one (CLI commands, tests).
|
||||||
pub async fn start(cfgs: BTreeMap<String, Server>) -> Self {
|
pub async fn start(cfgs: BTreeMap<String, Server>) -> Self {
|
||||||
@@ -395,10 +405,18 @@ impl Hub {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn system_prompt(&self) -> String {
|
pub fn system_prompt(&self) -> String {
|
||||||
|
self.system_prompt_for(Via::Direct)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn system_prompt_for(&self, via: Via) -> String {
|
||||||
let idx = self.index();
|
let idx = self.index();
|
||||||
let mut s = String::new();
|
let mut s = String::new();
|
||||||
if !idx.is_empty() {
|
if !idx.is_empty() {
|
||||||
s.push_str("# MCP tools\nCall with `mcp_call` (server, tool, arguments). Use `mcp_describe` first to get the argument schema.\n");
|
s.push_str(match via {
|
||||||
|
Via::Codemode => "# MCP tools\nNot top-level tools: reach them only through `codemode`. Inside a script: `await tools.mcp_call({server, tool, arguments})`; `await tools.mcp_describe({server, tool})` gives the argument schema (also `tools.mcp_read({server, uri})`).\n",
|
||||||
|
Via::ClaudeCli => "# MCP tools\nCall with the `mcp__hx__mcp_call` tool (server, tool, arguments). Use `mcp__hx__mcp_describe` first to get the argument schema (`mcp__hx__mcp_read` reads resources).\n",
|
||||||
|
Via::Direct => "# MCP tools\nCall with `mcp_call` (server, tool, arguments). Use `mcp_describe` first to get the argument schema.\n",
|
||||||
|
});
|
||||||
for (_, b) in idx {
|
for (_, b) in idx {
|
||||||
s.push_str(&b);
|
s.push_str(&b);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,6 +36,16 @@ async fn stdio_lazy_index_describe_call() {
|
|||||||
let sp = h.system_prompt();
|
let sp = h.system_prompt();
|
||||||
assert!(sp.contains("- f.echo: Echo a message back\n"), "{sp}");
|
assert!(sp.contains("- f.echo: Echo a message back\n"), "{sp}");
|
||||||
assert!(!sp.contains("second line"));
|
assert!(!sp.contains("second line"));
|
||||||
|
let cm = h.system_prompt_for(crate::Via::Codemode);
|
||||||
|
assert!(
|
||||||
|
cm.contains("only through `codemode`") && cm.contains("- f.echo:"),
|
||||||
|
"{cm}"
|
||||||
|
);
|
||||||
|
assert!(!sp.contains("codemode"));
|
||||||
|
assert!(
|
||||||
|
h.system_prompt_for(crate::Via::ClaudeCli)
|
||||||
|
.contains("mcp__hx__mcp_call")
|
||||||
|
);
|
||||||
assert!(sp.contains("mem://notes") && sp.contains("Use echo for tests."));
|
assert!(sp.contains("mem://notes") && sp.contains("Use echo for tests."));
|
||||||
let st = h.status();
|
let st = h.status();
|
||||||
assert!(
|
assert!(
|
||||||
|
|||||||
@@ -86,7 +86,10 @@ impl Codemode {
|
|||||||
let mut names = BTreeMap::new();
|
let mut names = BTreeMap::new();
|
||||||
let mut list = String::new();
|
let mut list = String::new();
|
||||||
let mut hidden = 0;
|
let mut hidden = 0;
|
||||||
for s in reg.specs() {
|
// MCP tools first so builtins cannot push them out of the listing budget
|
||||||
|
let mut specs = reg.specs();
|
||||||
|
specs.sort_by_key(|s| !(s.name.contains("__") || s.name.starts_with("mcp_")));
|
||||||
|
for s in specs {
|
||||||
let id = ident(&s.name);
|
let id = ident(&s.name);
|
||||||
let first = s.description.split(". ").next().unwrap_or("").trim();
|
let first = s.description.split(". ").next().unwrap_or("").trim();
|
||||||
let line = format!("- tools.{id}({}): {first}\n", sig(&s.input_schema));
|
let line = format!("- tools.{id}({}): {first}\n", sig(&s.input_schema));
|
||||||
|
|||||||
@@ -66,6 +66,7 @@ pub fn registry() -> Registry {
|
|||||||
.add(Edit)
|
.add(Edit)
|
||||||
.add(Bash)
|
.add(Bash)
|
||||||
.add(AskUser)
|
.add(AskUser)
|
||||||
|
.add(ExitPlan)
|
||||||
.add(MemoryWrite)
|
.add(MemoryWrite)
|
||||||
.add(MemoryForget)
|
.add(MemoryForget)
|
||||||
.add(skill::Skill);
|
.add(skill::Skill);
|
||||||
@@ -313,6 +314,7 @@ impl Tool for AskUser {
|
|||||||
options,
|
options,
|
||||||
multi: a["multi"].as_bool().unwrap_or(false),
|
multi: a["multi"].as_bool().unwrap_or(false),
|
||||||
other: true,
|
other: true,
|
||||||
|
plan: None,
|
||||||
};
|
};
|
||||||
match cx.state.choose(q).await {
|
match cx.state.choose(q).await {
|
||||||
Err(e) => ToolResult::err(e),
|
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.
|
/// Bytes of running bash output kept for the live view.
|
||||||
const LIVE_TAIL: usize = 2048;
|
const LIVE_TAIL: usize = 2048;
|
||||||
|
|
||||||
|
|||||||
@@ -19,6 +19,8 @@ pub struct Choose {
|
|||||||
picked: Vec<bool>,
|
picked: Vec<bool>,
|
||||||
/// Some while typing an own answer
|
/// Some while typing an own answer
|
||||||
typing: Option<String>,
|
typing: Option<String>,
|
||||||
|
/// opened straight into the text input: esc dismisses instead of showing the list
|
||||||
|
direct: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Choose {
|
impl Choose {
|
||||||
@@ -28,9 +30,18 @@ impl Choose {
|
|||||||
q,
|
q,
|
||||||
sel: 0,
|
sel: 0,
|
||||||
typing: None,
|
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 {
|
fn rows(&self) -> usize {
|
||||||
self.q.options.len() + usize::from(self.q.other)
|
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![] };
|
let picked = if self.q.multi { self.labels() } else { vec![] };
|
||||||
if let Some(t) = &mut self.typing {
|
if let Some(t) = &mut self.typing {
|
||||||
match k.code {
|
match k.code {
|
||||||
|
KeyCode::Esc if self.direct => return Act::Done(None),
|
||||||
KeyCode::Esc => self.typing = None,
|
KeyCode::Esc => self.typing = None,
|
||||||
KeyCode::Backspace => {
|
KeyCode::Backspace => {
|
||||||
t.pop();
|
t.pop();
|
||||||
@@ -286,6 +298,7 @@ mod tests {
|
|||||||
],
|
],
|
||||||
multi,
|
multi,
|
||||||
other: true,
|
other: true,
|
||||||
|
plan: None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
fn k(c: KeyCode) -> KeyEvent {
|
fn k(c: KeyCode) -> KeyEvent {
|
||||||
@@ -314,6 +327,23 @@ mod tests {
|
|||||||
assert!(c.is_other());
|
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]
|
#[test]
|
||||||
fn multi_toggle_and_other_text() {
|
fn multi_toggle_and_other_text() {
|
||||||
let mut c = q(true);
|
let mut c = q(true);
|
||||||
@@ -405,6 +435,7 @@ mod tests {
|
|||||||
],
|
],
|
||||||
multi: false,
|
multi: false,
|
||||||
other: true,
|
other: true,
|
||||||
|
plan: None,
|
||||||
});
|
});
|
||||||
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(200, 50)).unwrap();
|
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(200, 50)).unwrap();
|
||||||
term.draw(|f| c.draw(f, 45)).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"));
|
||||||
|
}
|
||||||
|
}
|
||||||
+113
-8
@@ -3,6 +3,7 @@
|
|||||||
pub mod agents;
|
pub mod agents;
|
||||||
pub mod btw_view;
|
pub mod btw_view;
|
||||||
pub mod choose;
|
pub mod choose;
|
||||||
|
pub mod doc_view;
|
||||||
pub mod editor;
|
pub mod editor;
|
||||||
pub mod permit_view;
|
pub mod permit_view;
|
||||||
pub mod picker;
|
pub mod picker;
|
||||||
@@ -172,6 +173,12 @@ struct App {
|
|||||||
tokio::sync::oneshot::Sender<hx_core::permit::Decision>,
|
tokio::sync::oneshot::Sender<hx_core::permit::Decision>,
|
||||||
)>,
|
)>,
|
||||||
review: Option<review::Review>,
|
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
|
/// `/keys`: show every key as hx receives it until esc
|
||||||
probe: bool,
|
probe: bool,
|
||||||
/// keyboard protocol was switched on (shift-enter is distinguishable)
|
/// keyboard protocol was switched on (shift-enter is distinguishable)
|
||||||
@@ -382,6 +389,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
|||||||
choose: None,
|
choose: None,
|
||||||
perm: None,
|
perm: None,
|
||||||
review: None,
|
review: None,
|
||||||
|
doc: None,
|
||||||
probe: false,
|
probe: false,
|
||||||
kbd,
|
kbd,
|
||||||
stats: None,
|
stats: None,
|
||||||
@@ -496,6 +504,22 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
|||||||
let _ = reply.send(d);
|
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() => {
|
TEvent::Key(k) if k.kind != KeyEventKind::Release && app.choose.is_some() => {
|
||||||
if let Some((c, _)) = &mut app.choose
|
if let Some((c, _)) = &mut app.choose
|
||||||
&& let choose::Act::Done(ans) = c.key(k)
|
&& let choose::Act::Done(ans) = c.key(k)
|
||||||
@@ -539,7 +563,24 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
|||||||
match u {
|
match u {
|
||||||
Ui::Ask(q, reply) => app.ask = Some((q, reply)),
|
Ui::Ask(q, reply) => app.ask = Some((q, reply)),
|
||||||
Ui::Permit(r, reply) => app.perm = Some((permit_view::Prompt::new(r), 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) => {
|
Ui::Ev(e) => {
|
||||||
if let Event::SubUsage(u) = &e {
|
if let Event::SubUsage(u) = &e {
|
||||||
app.st.usage.add(u);
|
app.st.usage.add(u);
|
||||||
@@ -902,13 +943,24 @@ fn on_mouse(app: &mut App, m: crossterm::event::MouseEvent) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The chat text as drawn, full height (for extracting a selection).
|
/// The chat text as drawn, full height (for extracting a selection).
|
||||||
fn chat_buf(app: &App) -> Buffer {
|
/// Off-screen chat render plus, per row, whether it continues a soft-wrapped line.
|
||||||
|
fn chat_buf(app: &App) -> (Buffer, Vec<bool>) {
|
||||||
let w = app.areas.chat.width;
|
let w = app.areas.chat.width;
|
||||||
let para = Paragraph::new(app.t.lines(app.expanded, w)).wrap(Wrap { trim: false });
|
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);
|
||||||
|
cont.push(false);
|
||||||
|
cont.extend(std::iter::repeat(true).take(n - 1));
|
||||||
|
}
|
||||||
|
let para = Paragraph::new(lines).wrap(Wrap { trim: false });
|
||||||
let r = Rect::new(0, 0, w, para.line_count(w) as u16);
|
let r = Rect::new(0, 0, w, para.line_count(w) as u16);
|
||||||
let mut b = Buffer::empty(r);
|
let mut b = Buffer::empty(r);
|
||||||
Widget::render(para, r, &mut b);
|
Widget::render(para, r, &mut b);
|
||||||
b
|
(b, cont)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Put `t` on the clipboard (OSC 52) and say so in the footer.
|
/// Put `t` on the clipboard (OSC 52) and say so in the footer.
|
||||||
@@ -934,6 +986,7 @@ fn select_mouse(app: &mut App, m: crossterm::event::MouseEvent) {
|
|||||||
|| app.sessions.is_some()
|
|| app.sessions.is_some()
|
||||||
|| app.choose.is_some()
|
|| app.choose.is_some()
|
||||||
|| app.review.is_some()
|
|| app.review.is_some()
|
||||||
|
|| app.doc.is_some()
|
||||||
|| app.perm.is_some()
|
|| app.perm.is_some()
|
||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
@@ -973,13 +1026,13 @@ fn select_mouse(app: &mut App, m: crossterm::event::MouseEvent) {
|
|||||||
app.sel = Some(select::Sel { anchor: p, head: p });
|
app.sel = Some(select::Sel { anchor: p, head: p });
|
||||||
app.drag = true;
|
app.drag = true;
|
||||||
} else {
|
} else {
|
||||||
let b = chat_buf(app);
|
let (b, cont) = chat_buf(app);
|
||||||
let s = if n == 2 {
|
let s = if n == 2 {
|
||||||
select::word(&b, p.0, p.1)
|
select::word(&b, p.0, p.1)
|
||||||
} else {
|
} else {
|
||||||
select::line(&b, p.0)
|
select::line(&b, p.0)
|
||||||
};
|
};
|
||||||
let t = select::text(&b, &s);
|
let t = select::text(&b, &s, &cont);
|
||||||
app.sel = Some(s);
|
app.sel = Some(s);
|
||||||
copy(app, &t);
|
copy(app, &t);
|
||||||
}
|
}
|
||||||
@@ -993,7 +1046,8 @@ fn select_mouse(app: &mut App, m: crossterm::event::MouseEvent) {
|
|||||||
app.drag = false;
|
app.drag = false;
|
||||||
match app.sel {
|
match app.sel {
|
||||||
Some(s) if s.anchor != p => {
|
Some(s) if s.anchor != p => {
|
||||||
let t = select::text(&chat_buf(app), &s);
|
let (b, cont) = chat_buf(app);
|
||||||
|
let t = select::text(&b, &s, &cont);
|
||||||
copy(app, &t);
|
copy(app, &t);
|
||||||
}
|
}
|
||||||
_ => app.sel = None,
|
_ => app.sel = None,
|
||||||
@@ -1006,6 +1060,9 @@ fn select_mouse(app: &mut App, m: crossterm::event::MouseEvent) {
|
|||||||
fn wheel(app: &mut App, m: crossterm::event::MouseEvent, up: bool) {
|
fn wheel(app: &mut App, m: crossterm::event::MouseEvent, up: bool) {
|
||||||
let s = if let Some(agents::View::Detail { scroll, .. }) = &mut app.agents {
|
let s = if let Some(agents::View::Detail { scroll, .. }) = &mut app.agents {
|
||||||
scroll
|
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() {
|
} else if app.picker.is_some() || app.sessions.is_some() || app.choose.is_some() {
|
||||||
return;
|
return;
|
||||||
} else if app.panel.is_some() && inside(app.areas.panel, m.column, m.row) {
|
} else if app.panel.is_some() && inside(app.areas.panel, m.column, m.row) {
|
||||||
@@ -1325,7 +1382,7 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
|||||||
let (c, arg) = cmd
|
let (c, arg) = cmd
|
||||||
.split_once(' ')
|
.split_once(' ')
|
||||||
.map_or((cmd, ""), |(a, b)| (a, b.trim()));
|
.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()));
|
app.t.push(Item::Error("busy; esc to abort first".into()));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -1477,6 +1534,24 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
|||||||
drop(al);
|
drop(al);
|
||||||
app.t.push(Item::Info(m));
|
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" => {
|
"yolo" => {
|
||||||
let on = app
|
let on = app
|
||||||
.state
|
.state
|
||||||
@@ -1674,6 +1749,32 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
|||||||
)));
|
)));
|
||||||
line = r.prompt;
|
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.busy = true;
|
||||||
app.since = Instant::now();
|
app.since = Instant::now();
|
||||||
app.run_tokens = (0, 0);
|
app.run_tokens = (0, 0);
|
||||||
@@ -1920,6 +2021,9 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
|
|||||||
if let Some(r) = &app.review {
|
if let Some(r) = &app.review {
|
||||||
r.draw(f);
|
r.draw(f);
|
||||||
}
|
}
|
||||||
|
if let Some((v, _, _)) = &mut app.doc {
|
||||||
|
v.draw(f);
|
||||||
|
}
|
||||||
if let Some((p, _)) = &app.perm {
|
if let Some((p, _)) = &app.perm {
|
||||||
p.draw(f, input.y);
|
p.draw(f, input.y);
|
||||||
}
|
}
|
||||||
@@ -2634,6 +2738,7 @@ mod tests {
|
|||||||
choose: None,
|
choose: None,
|
||||||
perm: None,
|
perm: None,
|
||||||
review: None,
|
review: None,
|
||||||
|
doc: None,
|
||||||
probe: false,
|
probe: false,
|
||||||
kbd: false,
|
kbd: false,
|
||||||
stats: None,
|
stats: None,
|
||||||
|
|||||||
+35
-10
@@ -55,13 +55,15 @@ pub fn paint(buf: &mut Buffer, area: Rect, top: u16, s: &Sel) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Selected text from a buffer rendered at origin (0, 0); trailing blanks per row are dropped.
|
/// Selected text from a buffer rendered at origin (0, 0); trailing blanks per row are dropped.
|
||||||
pub fn text(buf: &Buffer, s: &Sel) -> String {
|
/// `cont[row]` = row is a soft-wrap continuation: joined to the previous row, not newline-split.
|
||||||
|
pub fn text(buf: &Buffer, s: &Sel, cont: &[bool]) -> String {
|
||||||
let (w, h) = (buf.area.width, buf.area.height);
|
let (w, h) = (buf.area.width, buf.area.height);
|
||||||
if w == 0 || h == 0 {
|
if w == 0 || h == 0 {
|
||||||
return String::new();
|
return String::new();
|
||||||
}
|
}
|
||||||
let (a, b) = s.span();
|
let (a, b) = s.span();
|
||||||
let mut rows = vec![];
|
let mut out = String::new();
|
||||||
|
let mut prev_full = false;
|
||||||
for row in a.0..=b.0.min(h - 1) {
|
for row in a.0..=b.0.min(h - 1) {
|
||||||
let Some((lo, hi)) = s.cols(row, w) else {
|
let Some((lo, hi)) = s.cols(row, w) else {
|
||||||
continue;
|
continue;
|
||||||
@@ -72,9 +74,22 @@ pub fn text(buf: &Buffer, s: &Sel) -> String {
|
|||||||
line.push_str(sym);
|
line.push_str(sym);
|
||||||
x += Span::raw(sym).width().max(1) as u16; // skip the trailing cell of wide chars
|
x += Span::raw(sym).width().max(1) as u16; // skip the trailing cell of wide chars
|
||||||
}
|
}
|
||||||
rows.push(line.trim_end().to_string());
|
let line = line.trim_end();
|
||||||
|
let full = Span::raw(line).width() as u16 >= w; // word broken mid-token
|
||||||
|
if row > a.0 {
|
||||||
|
if cont.get(row as usize) == Some(&true) {
|
||||||
|
// ponytail: wrap at a space leaves no trace; assume one unless the row was full
|
||||||
|
if !prev_full {
|
||||||
|
out.push(' ');
|
||||||
}
|
}
|
||||||
rows.join("\n")
|
} else {
|
||||||
|
out.push('\n');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.push_str(line);
|
||||||
|
prev_full = full;
|
||||||
|
}
|
||||||
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
fn is_word(sym: &str) -> bool {
|
fn is_word(sym: &str) -> bool {
|
||||||
@@ -151,28 +166,38 @@ mod tests {
|
|||||||
anchor: (0, 6),
|
anchor: (0, 6),
|
||||||
head: (1, 5),
|
head: (1, 5),
|
||||||
};
|
};
|
||||||
assert_eq!(text(&b, &fwd), "world\nsecond");
|
assert_eq!(text(&b, &fwd, &[]), "world\nsecond");
|
||||||
let rev = Sel {
|
let rev = Sel {
|
||||||
anchor: (1, 5),
|
anchor: (1, 5),
|
||||||
head: (0, 6),
|
head: (0, 6),
|
||||||
};
|
};
|
||||||
assert_eq!(text(&b, &rev), "world\nsecond");
|
assert_eq!(text(&b, &rev, &[]), "world\nsecond");
|
||||||
let wide = Sel {
|
let wide = Sel {
|
||||||
anchor: (1, 7),
|
anchor: (1, 7),
|
||||||
head: (1, 10),
|
head: (1, 10),
|
||||||
};
|
};
|
||||||
assert_eq!(text(&b, &wide), "日本");
|
assert_eq!(text(&b, &wide, &[]), "日本");
|
||||||
let past = Sel {
|
let past = Sel {
|
||||||
anchor: (2, 0),
|
anchor: (2, 0),
|
||||||
head: (9, 3),
|
head: (9, 3),
|
||||||
};
|
};
|
||||||
assert_eq!(text(&b, &past), "third");
|
assert_eq!(text(&b, &past, &[]), "third");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn soft_wrap_rows_join_without_newline() {
|
||||||
|
let b = buf("hello\nworld\nnext", 10);
|
||||||
|
let s = Sel {
|
||||||
|
anchor: (0, 0),
|
||||||
|
head: (2, 9),
|
||||||
|
};
|
||||||
|
assert_eq!(text(&b, &s, &[false, true, false]), "hello world\nnext");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn word_and_line_pick() {
|
fn word_and_line_pick() {
|
||||||
let b = buf("see src/main.rs now", 30);
|
let b = buf("see src/main.rs now", 30);
|
||||||
assert_eq!(text(&b, &word(&b, 0, 6)), "src/main.rs");
|
assert_eq!(text(&b, &word(&b, 0, 6), &[]), "src/main.rs");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
word(&b, 0, 3),
|
word(&b, 0, 3),
|
||||||
Sel {
|
Sel {
|
||||||
@@ -180,7 +205,7 @@ mod tests {
|
|||||||
head: (0, 3)
|
head: (0, 3)
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
assert_eq!(text(&b, &line(&b, 0)), "see src/main.rs now");
|
assert_eq!(text(&b, &line(&b, 0), &[]), "see src/main.rs now");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -555,7 +555,7 @@ fn advance(cur: Option<usize>, l: &str) -> Option<usize> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Minimal markdown: fenced code, headings, bullets, inline `code` and **bold**.
|
/// 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;
|
let mut code = false;
|
||||||
for l in s.lines() {
|
for l in s.lines() {
|
||||||
if l.trim_start().starts_with("```") {
|
if l.trim_start().starts_with("```") {
|
||||||
|
|||||||
@@ -13,4 +13,29 @@ export HOME="$tmp/home" HX_CLAUDE_BIN="$root/tests/fake_claude.py" FAKE_CLAUDE_L
|
|||||||
grep -q "claude Bash: echo hi-from-tool" "$tmp/out" && grep -q "approve: allow" "$tmp/out" || { echo "FAIL text"; cat "$tmp/out" "$tmp/err"; exit 1; }
|
grep -q "claude Bash: echo hi-from-tool" "$tmp/out" && grep -q "approve: allow" "$tmp/out" || { echo "FAIL text"; cat "$tmp/out" "$tmp/err"; exit 1; }
|
||||||
grep -q '"--permission-prompt-tool"' "$tmp/argv" && grep -q '"--mcp-config"' "$tmp/argv" && grep -q '"stream-json"' "$tmp/argv" || { echo "FAIL argv"; cat "$tmp/argv"; exit 1; }
|
grep -q '"--permission-prompt-tool"' "$tmp/argv" && grep -q '"--mcp-config"' "$tmp/argv" && grep -q '"stream-json"' "$tmp/argv" || { echo "FAIL argv"; cat "$tmp/argv"; exit 1; }
|
||||||
grep -q "cm-ok" "$tmp/out" || { echo "FAIL codemode"; cat "$tmp/out" "$tmp/err"; exit 1; }
|
grep -q "cm-ok" "$tmp/out" || { echo "FAIL codemode"; cat "$tmp/out" "$tmp/err"; exit 1; }
|
||||||
|
# bridge goes through the bus: an extension blocks a secret Read and `curl`; tool events reach NDJSON
|
||||||
|
cd "$tmp/repo"
|
||||||
|
export FAKE_ASK=1
|
||||||
|
timeout 20 "$root/target/debug/hx" -p "go" --mode json -s "$tmp/s2.jsonl" > "$tmp/o2" 2> "$tmp/e2" || { echo "FAIL ask run"; cat "$tmp/e2"; exit 1; }
|
||||||
|
python3 - "$tmp/o2" allow <<'PY' || { echo "FAIL events (no extension)"; exit 1; }
|
||||||
|
import json, sys
|
||||||
|
ev = [json.loads(l) for l in open(sys.argv[1]) if l.startswith("{")]
|
||||||
|
calls = [(e["name"], e["id"]) for e in ev if e["type"] == "tool_call"]
|
||||||
|
res = [e for e in ev if e["type"] == "tool_result"]
|
||||||
|
assert calls == [("read", "t1"), ("bash", "t2")], calls
|
||||||
|
assert [r["is_error"] for r in res] == [False, False] and "allow" in res[1]["content"], res
|
||||||
|
PY
|
||||||
|
"$root/target/debug/hx" stats "$tmp/s2.jsonl" | grep -q "bash: 1 calls, 0 errors" || { echo "FAIL stats"; "$root/target/debug/hx" stats "$tmp/s2.jsonl"; exit 1; }
|
||||||
|
printf 'claude_cli = []\n[lsp]\nmode = "off"\ntests = "off"\n[[extensions]]\ncommand = ["python3", "%s/tests/ext_block_all.py"]\n' "$root" > "$tmp/home/.hx/config.toml"
|
||||||
|
timeout 20 "$root/target/debug/hx" -p "go" --mode json -s "$tmp/s3.jsonl" > "$tmp/o3" 2> "$tmp/e3" || { echo "FAIL ext run"; cat "$tmp/e3"; exit 1; }
|
||||||
|
python3 - "$tmp/o3" <<'PY' || { echo "FAIL events (extension)"; cat "$tmp/e3"; exit 1; }
|
||||||
|
import json, sys
|
||||||
|
ev = [json.loads(l) for l in open(sys.argv[1]) if l.startswith("{")]
|
||||||
|
res = [e for e in ev if e["type"] == "tool_result"]
|
||||||
|
assert len(res) == 2 and all(r["is_error"] and "blocked: guard: " in r["content"] for r in res), res
|
||||||
|
PY
|
||||||
|
# a dead guard must not leave the run open under permissions = "extensions-only"
|
||||||
|
printf 'claude_cli = []\npermissions = "extensions-only"\n[lsp]\nmode = "off"\ntests = "off"\n' > "$tmp/home/.hx/config.toml"
|
||||||
|
timeout 20 "$root/target/debug/hx" -p "go" --mode json -s "$tmp/s4.jsonl" > "$tmp/o4" 2> "$tmp/e4" || { echo "FAIL deny run"; cat "$tmp/e4"; exit 1; }
|
||||||
|
grep -q 'extensions-only' "$tmp/o4" && ! grep -q '"content":"allow' "$tmp/o4" || { echo "FAIL extensions-only"; cat "$tmp/o4"; exit 1; }
|
||||||
echo "claude cli e2e ok"
|
echo "claude cli e2e ok"
|
||||||
Executable
+12
@@ -0,0 +1,12 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Test extension: subscribes to tool_call, blocks `read` of secrets and `bash` curl."""
|
||||||
|
import json, sys
|
||||||
|
for line in sys.stdin:
|
||||||
|
m = json.loads(line)
|
||||||
|
if m["method"] == "initialize":
|
||||||
|
r = {"subscribe": ["tool_call"], "tools": []}
|
||||||
|
else:
|
||||||
|
e = m["params"]["event"]
|
||||||
|
bad = (e["name"] == "read" and ".ssh" in e["args"]["path"]) or (e["name"] == "bash" and "curl" in e["args"]["command"])
|
||||||
|
r = {"action": "block", "reason": "guard: " + e["name"]} if bad else {"action": "continue"}
|
||||||
|
print(json.dumps({"jsonrpc": "2.0", "id": m["id"], "result": r}), flush=True)
|
||||||
@@ -6,6 +6,29 @@ if "--version" in sys.argv:
|
|||||||
print("fake"); sys.exit(0)
|
print("fake"); sys.exit(0)
|
||||||
def out(o): print(json.dumps(o), flush=True)
|
def out(o): print(json.dumps(o), flush=True)
|
||||||
reply = "hello from claude"
|
reply = "hello from claude"
|
||||||
|
if os.environ.get("FAKE_ASK"): # ask hx about a secret Read and `curl x` (ids t1/t2); report the answers
|
||||||
|
import subprocess
|
||||||
|
cfg = json.loads(sys.argv[sys.argv.index("--mcp-config") + 1])["mcpServers"]["hx"]
|
||||||
|
p = subprocess.Popen([cfg["command"], *cfg["args"]], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||||
|
text=True, env={**os.environ, **cfg["env"]})
|
||||||
|
asks = [("t1", "Read", {"file_path": "/home/u/.ssh/id_rsa"}), ("t2", "Bash", {"command": "curl x"})]
|
||||||
|
p.stdin.write(json.dumps({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}) + "\n")
|
||||||
|
p.stdin.flush()
|
||||||
|
p.stdout.readline()
|
||||||
|
ans = []
|
||||||
|
for i, (tid, n, inp) in enumerate(asks): # one at a time: deterministic order
|
||||||
|
p.stdin.write(json.dumps({"jsonrpc": "2.0", "id": 10 + i, "method": "tools/call", "params": {"name": "approve",
|
||||||
|
"arguments": {"tool_name": n, "input": inp, "tool_use_id": tid}}}) + "\n")
|
||||||
|
p.stdin.flush()
|
||||||
|
ans.append(json.loads(json.loads(p.stdout.readline())["result"]["content"][0]["text"]))
|
||||||
|
p.stdin.close()
|
||||||
|
out({"type": "system", "subtype": "init", "session_id": "S1"})
|
||||||
|
for (tid, n, inp), a in zip(asks, ans):
|
||||||
|
out({"type": "assistant", "session_id": "S1", "message": {"content": [{"type": "tool_use", "id": tid, "name": n, "input": inp}]}})
|
||||||
|
out({"type": "user", "session_id": "S1", "message": {"content": [{"type": "tool_result", "tool_use_id": tid,
|
||||||
|
"content": a["behavior"] + ": " + a.get("message", ""), "is_error": a["behavior"] == "deny"}]}})
|
||||||
|
out({"type": "result", "session_id": "S1", "is_error": False, "result": "done", "usage": {"input_tokens": 1, "output_tokens": 1}})
|
||||||
|
sys.exit(0)
|
||||||
if "--permission-prompt-tool" in sys.argv: # act like claude: ask hx whether `rm -rf x` may run
|
if "--permission-prompt-tool" in sys.argv: # act like claude: ask hx whether `rm -rf x` may run
|
||||||
import subprocess
|
import subprocess
|
||||||
cfg = json.loads(sys.argv[sys.argv.index("--mcp-config") + 1])["mcpServers"]["hx"]
|
cfg = json.loads(sys.argv[sys.argv.index("--mcp-config") + 1])["mcpServers"]["hx"]
|
||||||
|
|||||||
Reference in new issue
Block a user