Merge pull request 'claude_cli: codemode for claude' (#167) from feat/claude-cli-codemode into main
This commit was merged in pull request #167.
This commit is contained in:
commit
d69c56b3c8
4 files changed
+111
-27
No files matched your search
@@ -454,6 +454,8 @@ fn pricing(model: &str) -> Option<hx_ai::Pricing> {
|
|||||||
|
|
||||||
/// `[openai_compat]` from config, set once at startup.
|
/// `[openai_compat]` from config, set once at startup.
|
||||||
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.
|
||||||
|
static CODEMODE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||||
/// `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();
|
||||||
|
|
||||||
@@ -464,11 +466,14 @@ fn provider(k: Kind) -> hx_ai::Result<Arc<dyn Provider>> {
|
|||||||
hx_ai::claude_cli::ClaudeCli::new(CLAUDE_CLI.get().cloned().unwrap_or_default());
|
hx_ai::claude_cli::ClaudeCli::new(CLAUDE_CLI.get().cloned().unwrap_or_default());
|
||||||
let c = c.with_spawner(Arc::new(|bin| Box::pin(claude_command(bin))));
|
let c = c.with_spawner(Arc::new(|bin| Box::pin(claude_command(bin))));
|
||||||
Arc::new(match std::env::current_exe() {
|
Arc::new(match std::env::current_exe() {
|
||||||
Ok(e) => c.with_mcp(
|
Ok(e) => c.with_mcp(e.to_string_lossy().into(), vec!["mcp-serve".into()], {
|
||||||
e.to_string_lossy().into(),
|
let mut env =
|
||||||
vec!["mcp-serve".into()],
|
serde_json::json!({ hx_core::approve::ENV: hx_core::approve::sock_path() });
|
||||||
serde_json::json!({ hx_core::approve::ENV: hx_core::approve::sock_path() }),
|
if CODEMODE.get().copied().unwrap_or(false) {
|
||||||
),
|
env["HX_CODEMODE"] = "1".into();
|
||||||
|
}
|
||||||
|
env
|
||||||
|
}),
|
||||||
Err(_) => c,
|
Err(_) => c,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -708,13 +713,35 @@ async fn main() -> Result<()> {
|
|||||||
));
|
));
|
||||||
let mut reg = hx_core::tool::Registry::default();
|
let mut reg = hx_core::tool::Registry::default();
|
||||||
reg.add(hx_lens::LspTool::new(mgr.clone()));
|
reg.add(hx_lens::LspTool::new(mgr.clone()));
|
||||||
if let Some(p) = std::env::var_os(hx_core::approve::ENV) {
|
|
||||||
reg.add(hx_core::approve::Approve(p.into()));
|
|
||||||
}
|
|
||||||
let cx = ToolCtx {
|
let cx = ToolCtx {
|
||||||
cwd,
|
cwd: cwd.clone(),
|
||||||
state: Default::default(),
|
state: Default::default(),
|
||||||
};
|
};
|
||||||
|
let sock = std::env::var_os(hx_core::approve::ENV);
|
||||||
|
if let Some(p) = &sock {
|
||||||
|
reg.add(hx_core::approve::Approve(p.into()));
|
||||||
|
// tools run by codemode ask hx for permission like any other
|
||||||
|
let _ = cx
|
||||||
|
.state
|
||||||
|
.permit
|
||||||
|
.set(hx_core::approve::remote_permit(p.into()));
|
||||||
|
}
|
||||||
|
if std::env::var_os("HX_CODEMODE").is_some() {
|
||||||
|
// claude keeps its own tools; only `codemode` is added, and scripts may call the hx tools
|
||||||
|
let cfg = Config::load(&cwd)?;
|
||||||
|
let hub = Arc::new(
|
||||||
|
hx_mcp::Hub::start(
|
||||||
|
hx_mcp::config::load(&context::hx_home(), &cwd)
|
||||||
|
.map_err(anyhow::Error::msg)?,
|
||||||
|
)
|
||||||
|
.await,
|
||||||
|
);
|
||||||
|
let mut all = hx_tools::registry();
|
||||||
|
hx_tools::web::register(&mut all, web_search(&cfg));
|
||||||
|
hub.register(&mut all);
|
||||||
|
all.add(hx_lens::LspTool::new(mgr.clone()));
|
||||||
|
reg.add(hx_tools::codemode::Codemode::new(&all));
|
||||||
|
}
|
||||||
hx_mcp::serve::serve(
|
hx_mcp::serve::serve(
|
||||||
reg,
|
reg,
|
||||||
cx,
|
cx,
|
||||||
@@ -749,6 +776,7 @@ async fn main() -> Result<()> {
|
|||||||
&& hx_ai::claude_cli::ClaudeCli::available())
|
&& hx_ai::claude_cli::ClaudeCli::available())
|
||||||
.then(Vec::new),
|
.then(Vec::new),
|
||||||
};
|
};
|
||||||
|
let _ = CODEMODE.set(cfg.codemode.unwrap_or(false));
|
||||||
if let Some(a) = cli_args {
|
if let Some(a) = cli_args {
|
||||||
let _ = CLAUDE_CLI.set(a);
|
let _ = CLAUDE_CLI.set(a);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -77,9 +77,23 @@ pub async fn serve(path: &Path, cx: ToolCtx) -> std::io::Result<()> {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let v: Value = serde_json::from_str(&line).unwrap_or_default();
|
let v: Value = serde_json::from_str(&line).unwrap_or_default();
|
||||||
let ok = match question(v["tool_name"].as_str().unwrap_or_default(), &v["input"]) {
|
// hx tools run by `codemode` inside mcp-serve ask for their own permission
|
||||||
None => true,
|
let ok = if let Some(q) = v.get("permit") {
|
||||||
Some(q) => gate(&cx, q).await,
|
let s = |k: &str| q[k].as_str().unwrap_or_default().to_string();
|
||||||
|
gate(
|
||||||
|
&cx,
|
||||||
|
Request {
|
||||||
|
tool: s("tool"),
|
||||||
|
detail: s("detail"),
|
||||||
|
rule: s("rule"),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
} else {
|
||||||
|
match question(v["tool_name"].as_str().unwrap_or_default(), &v["input"]) {
|
||||||
|
None => true,
|
||||||
|
Some(q) => gate(&cx, q).await,
|
||||||
|
}
|
||||||
};
|
};
|
||||||
let _ = w
|
let _ = w
|
||||||
.write_all(format!("{}\n", json!({"allow": ok})).as_bytes())
|
.write_all(format!("{}\n", json!({"allow": ok})).as_bytes())
|
||||||
@@ -88,6 +102,38 @@ pub async fn serve(path: &Path, cx: ToolCtx) -> std::io::Result<()> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn roundtrip(path: &Path, msg: Value) -> bool {
|
||||||
|
let ask = async {
|
||||||
|
let mut c = UnixStream::connect(path).await?;
|
||||||
|
c.write_all(format!("{msg}\n").as_bytes()).await?;
|
||||||
|
let mut l = String::new();
|
||||||
|
BufReader::new(c).read_line(&mut l).await?;
|
||||||
|
std::io::Result::Ok(l)
|
||||||
|
};
|
||||||
|
ask.await
|
||||||
|
.ok()
|
||||||
|
.and_then(|l| serde_json::from_str::<Value>(&l).ok())
|
||||||
|
.is_some_and(|v| v["allow"] == true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Permission hook for tools that run in another process (`hx mcp-serve`): ask the owner of the socket.
|
||||||
|
/// Unreachable socket = deny.
|
||||||
|
pub fn remote_permit(path: PathBuf) -> crate::permit::Permit {
|
||||||
|
use crate::permit::Decision;
|
||||||
|
std::sync::Arc::new(move |r| {
|
||||||
|
let path = path.clone();
|
||||||
|
Box::pin(async move {
|
||||||
|
let m = json!({"permit": {"tool": r.tool, "detail": r.detail, "rule": r.rule}});
|
||||||
|
// the owner stores "always" itself; here a yes is a plain yes
|
||||||
|
if roundtrip(&path, m).await {
|
||||||
|
Decision::Once
|
||||||
|
} else {
|
||||||
|
Decision::Deny
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/// MCP tool `approve` for `--permission-prompt-tool`.
|
/// MCP tool `approve` for `--permission-prompt-tool`.
|
||||||
pub struct Approve(pub PathBuf);
|
pub struct Approve(pub PathBuf);
|
||||||
|
|
||||||
@@ -103,18 +149,7 @@ impl Tool for Approve {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
async fn call(&self, args: Value, _cx: &ToolCtx) -> ToolResult {
|
async fn call(&self, args: Value, _cx: &ToolCtx) -> ToolResult {
|
||||||
let ask = async {
|
let ok = roundtrip(&self.0, args.clone()).await;
|
||||||
let mut c = UnixStream::connect(&self.0).await?;
|
|
||||||
c.write_all(format!("{args}\n").as_bytes()).await?;
|
|
||||||
let mut l = String::new();
|
|
||||||
BufReader::new(c).read_line(&mut l).await?;
|
|
||||||
std::io::Result::Ok(l)
|
|
||||||
};
|
|
||||||
let ok = ask
|
|
||||||
.await
|
|
||||||
.ok()
|
|
||||||
.and_then(|l| serde_json::from_str::<Value>(&l).ok())
|
|
||||||
.is_some_and(|v| v["allow"] == true);
|
|
||||||
ToolResult::ok(if ok {
|
ToolResult::ok(if ok {
|
||||||
json!({"behavior": "allow", "updatedInput": args["input"]})
|
json!({"behavior": "allow", "updatedInput": args["input"]})
|
||||||
} else {
|
} else {
|
||||||
@@ -175,6 +210,20 @@ mod tests {
|
|||||||
};
|
};
|
||||||
assert!(ask("cargo test").await.contains("\"allow\""));
|
assert!(ask("cargo test").await.contains("\"allow\""));
|
||||||
assert!(ask("rm -rf x").await.contains("\"deny\""));
|
assert!(ask("rm -rf x").await.contains("\"deny\""));
|
||||||
let _ = std::fs::remove_file(path);
|
// tools run in another process ask through the same socket
|
||||||
|
let remote = remote_permit(path.clone());
|
||||||
|
let req = |d: &str| crate::permit::Request {
|
||||||
|
tool: "bash".into(),
|
||||||
|
detail: d.into(),
|
||||||
|
rule: String::new(),
|
||||||
|
};
|
||||||
|
assert_eq!(remote(req("cargo test")).await, Decision::Once);
|
||||||
|
assert_eq!(remote(req("rm -rf x")).await, Decision::Deny);
|
||||||
|
let _ = std::fs::remove_file(&path);
|
||||||
|
assert_eq!(
|
||||||
|
remote(req("cargo test")).await,
|
||||||
|
Decision::Deny,
|
||||||
|
"no socket = deny"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,11 +5,12 @@ root=$(cd "$(dirname "$0")/.." && pwd)
|
|||||||
tmp=$(mktemp -d)
|
tmp=$(mktemp -d)
|
||||||
trap 'rm -rf "$tmp"' EXIT
|
trap 'rm -rf "$tmp"' EXIT
|
||||||
mkdir -p "$tmp/home/.hx" "$tmp/repo"
|
mkdir -p "$tmp/home/.hx" "$tmp/repo"
|
||||||
printf 'claude_cli = []\n[lsp]\nmode = "off"\ntests = "off"\n' > "$tmp/home/.hx/config.toml"
|
printf 'claude_cli = []\ncodemode = true\n[lsp]\nmode = "off"\ntests = "off"\n' > "$tmp/home/.hx/config.toml"
|
||||||
chmod +x "$root/tests/fake_claude.py"
|
chmod +x "$root/tests/fake_claude.py"
|
||||||
cd "$tmp/repo"
|
cd "$tmp/repo"
|
||||||
export HOME="$tmp/home" HX_CLAUDE_BIN="$root/tests/fake_claude.py" FAKE_CLAUDE_LOG="$tmp/argv"
|
export HOME="$tmp/home" HX_CLAUDE_BIN="$root/tests/fake_claude.py" FAKE_CLAUDE_LOG="$tmp/argv"
|
||||||
"$root/target/debug/hx" -p "hi" -s "$tmp/s.jsonl" > "$tmp/out" 2> "$tmp/err" || { echo "FAIL run"; cat "$tmp/err"; exit 1; }
|
"$root/target/debug/hx" -p "hi" -s "$tmp/s.jsonl" > "$tmp/out" 2> "$tmp/err" || { echo "FAIL run"; cat "$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 "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; }
|
||||||
echo "claude cli e2e ok"
|
echo "claude cli e2e ok"
|
||||||
@@ -15,9 +15,15 @@ if "--permission-prompt-tool" in sys.argv: # act like claude: ask hx whether `r
|
|||||||
{"tool_name": "Bash", "input": {"command": "rm -rf x"}}}}
|
{"tool_name": "Bash", "input": {"command": "rm -rf x"}}}}
|
||||||
p.stdin.write(json.dumps({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}) + "\n" + json.dumps(call) + "\n")
|
p.stdin.write(json.dumps({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}) + "\n" + json.dumps(call) + "\n")
|
||||||
p.stdin.flush()
|
p.stdin.flush()
|
||||||
lines = [json.loads(p.stdout.readline()) for _ in range(2)]
|
cm = {"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "codemode", "arguments":
|
||||||
|
{"script": "return await tools.bash({command: 'echo cm-' + 'ok > cm.txt; cat cm.txt'})"}}}
|
||||||
|
if "HX_CODEMODE" in cfg["env"]:
|
||||||
|
p.stdin.write(json.dumps(cm) + "\n"); p.stdin.flush()
|
||||||
|
lines = [json.loads(p.stdout.readline()) for _ in range(2 + ("HX_CODEMODE" in cfg["env"]))]
|
||||||
p.stdin.close()
|
p.stdin.close()
|
||||||
reply = "approve: " + json.loads(lines[1]["result"]["content"][0]["text"])["behavior"]
|
reply = "approve: " + json.loads(lines[1]["result"]["content"][0]["text"])["behavior"]
|
||||||
|
if len(lines) == 3:
|
||||||
|
reply += " " + lines[2]["result"]["content"][0]["text"]
|
||||||
out({"type": "system", "subtype": "init", "session_id": "S1"})
|
out({"type": "system", "subtype": "init", "session_id": "S1"})
|
||||||
ev = lambda e: out({"type": "stream_event", "session_id": "S1", "event": e})
|
ev = lambda e: out({"type": "stream_event", "session_id": "S1", "event": e})
|
||||||
out({"type": "assistant", "session_id": "S1", "message": {"content": [
|
out({"type": "assistant", "session_id": "S1", "message": {"content": [
|
||||||
|
|||||||
Reference in new issue
Block a user