14 Commits
Author SHA1 Message Date
johannes 437f8ec501 Merge pull request 'fix: orchestrated runs honour yolo/auto and work inside the sandbox' (#194) from fix/acp-sandbox-permissions into main
build / version (push) Successful in 11s
build / build (aarch64-apple-darwin) (push) Successful in 6m9s
build / build (x86_64-unknown-linux-musl) (push) Successful in 5m56s
build / release (push) Successful in 36s
Reviewed-on: #194
2026-11-17 15:48:37 +00:00
Johannes KresnerandClaude Opus 5.5 b1ca582d6b fix: orchestrated runs honour yolo/auto and work inside the sandbox
- serve --acp applies --yolo / --auto (or `permissions` in config.toml)
  like the TUI; before, every edit and command went to the orchestrator.
- claude no longer asks to run outside the sandbox. With the sandbox on it
  stays confined; only a stored `claude:unsandboxed` rule or
  --no-claude-sandbox lets it out, and yolo never does.
- The sandbox reads the files the global git config includes and may stat
  $HOME and the directories above allowed paths and includeIf gitdir
  paths (metadata only). git died on both before.
- hx mcp-serve logs a failed start to $TMPDIR/hx-mcp-serve.log; claude
  hides its stderr and only reports "mcp__hx__approve not found".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 16:43:41 +01:00
gitea-actions 37ebf96108 ci: bin.json v0.2.2 2026-11-17 15:16:06 +00:00
johannes 47e184738a Merge pull request 'fix: sandboxed claude can read its macOS login from the keychain' (#193) from fix/claude-sandbox-keychain into main
build / version (push) Successful in 14s
build / build (aarch64-apple-darwin) (push) Successful in 6m18s
build / build (x86_64-unknown-linux-musl) (push) Successful in 5m40s
build / release (push) Successful in 33s
Reviewed-on: #193
2026-11-17 14:53:04 +00:00
Johannes KresnerandClaude Opus 5.5 800bae97d7 fix: sandboxed claude can read its macOS login from the keychain
The seatbelt profile hides $HOME, and claude_extra did not bring back
~/Library/Keychains. On macOS claude keeps its OAuth login there, so a
sandboxed claude failed with "Not logged in" and the only way out was
to let it run unconfined.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:47:25 +01:00
gitea-actions 1f4f8aa081 ci: bin.json v0.2.1 2026-11-15 15:35:31 +00:00
johannes 061649cb07 chore: add depencencies to readme and flake
build / version (push) Successful in 11s
build / build (aarch64-apple-darwin) (push) Successful in 6m14s
build / build (x86_64-unknown-linux-musl) (push) Successful in 5m37s
build / release (push) Successful in 26s
2026-11-15 16:13:16 +01:00
gitea-actions 9d8b7dfbd8 ci: bin.json v0.1.16 2026-11-15 11:24:30 +00:00
hermes 179e5cddc7 Merge pull request 'Configurable session storage path' (#192) from sessions-dir into main
build / version (push) Successful in 11s
build / build (aarch64-apple-darwin) (push) Successful in 6m25s
build / build (x86_64-unknown-linux-musl) (push) Successful in 5m27s
build / release (push) Successful in 26s
2026-11-15 11:12:02 +00:00
hermes 05165d7b8f Configurable session storage path (sessions_dir, HX_SESSIONS_DIR, optional sessions_host) 2026-11-15 11:09:09 +00:00
gitea-actions c06381117b ci: bin.json v0.1.15 2026-11-14 13:32:19 +00:00
hermes 9fbcf4a62c Merge pull request 'Gate task subagents behind permission prompt' (#191) from gate-subagents into main
build / version (push) Successful in 12s
build / build (aarch64-apple-darwin) (push) Successful in 6m57s
build / build (x86_64-unknown-linux-musl) (push) Successful in 5m52s
build / release (push) Successful in 27s
2026-11-14 13:18:52 +00:00
hermes b84b6ab23a Gate task subagents behind permission prompt; subagents=false / --no-subagents; description: only when asked 2026-11-14 13:18:27 +00:00
gitea-actions 161c33fe6c ci: bin.json v0.1.14 2026-11-14 13:00:12 +00:00
11 changed files with 341 additions and 101 deletions

No files matched your search

+9 -1
View File
@@ -15,6 +15,12 @@ hx -r # pick a session to resume
hx -r parser # resume the session whose title best matches "parser" hx -r parser # resume the session whose title best matches "parser"
``` ```
## Dependencies
- Rust toolchain (to build from source; `cmake` and `perl` may be needed for the TLS stack).
- `git`.
- Linux: [`bubblewrap`](https://github.com/containers/bubblewrap) (`bwrap`) on `PATH` (`apt install bubblewrap`, `pacman -S bubblewrap`, `dnf install bubblewrap`). The Nix package wraps `hx` so it is provided automatically.
TUI: `enter` send, `shift-enter`/`alt-enter`/`ctrl-j` newline (or end a line with `\` and press enter), `esc` abort, `ctrl-o` expand tool output. TUI: `enter` send, `shift-enter`/`alt-enter`/`ctrl-j` newline (or end a line with `\` and press enter), `esc` abort, `ctrl-o` expand tool output.
Shift-enter needs a terminal that reports it; hx turns on the kitty keyboard protocol when the terminal answers the probe. Works in ghostty, kitty, WezTerm (`enable_kitty_keyboard = true`), iTerm2, foot, Alacritty 0.13+, Windows Terminal (map shift-enter to `\u001b[13;2u`) and zellij 0.41+. tmux 3.2+ needs `set -g extended-keys on` and `set -g extended-keys-format csi-u`. Elsewhere use `alt-enter`, `ctrl-j` or a trailing `\`. `/keys` prints every key as hx receives it, to see what a terminal or multiplexer (e.g. herdr) passes through. Long input lines wrap; the box grows up to 10 rows. Shift-enter needs a terminal that reports it; hx turns on the kitty keyboard protocol when the terminal answers the probe. Works in ghostty, kitty, WezTerm (`enable_kitty_keyboard = true`), iTerm2, foot, Alacritty 0.13+, Windows Terminal (map shift-enter to `\u001b[13;2u`) and zellij 0.41+. tmux 3.2+ needs `set -g extended-keys on` and `set -g extended-keys-format csi-u`. Elsewhere use `alt-enter`, `ctrl-j` or a trailing `\`. `/keys` prints every key as hx receives it, to see what a terminal or multiplexer (e.g. herdr) passes through. Long input lines wrap; the box grows up to 10 rows.
@@ -44,6 +50,8 @@ Lens findings and affected-test results appear after each turn as a `┄ lens
Config: `~/.hx/config.toml`, overridden per project by `.hx/config.toml`. `hx config init [--project] [--force]` writes a fully commented sample with every key. Example: Config: `~/.hx/config.toml`, overridden per project by `.hx/config.toml`. `hx config init [--project] [--force]` writes a fully commented sample with every key. Example:
**Session storage:** `sessions_dir` in config (or `HX_SESSIONS_DIR`, wins) moves sessions off `~/.hx/sessions`, e.g. to a synced or mounted cloud folder (rclone, Nextcloud, Syncthing). `~` expands; an unwritable path is an error, no silent fallback. `sessions_host = true` prefixes project folders with the host name so machines sharing one folder stay apart. Sessions are append-only JSONL: one hx per session file.
```toml ```toml
provider = "claude" # or "codex" provider = "claude" # or "codex"
# claude_model = "claude-sonnet-5-5" # default: the account's latest Sonnet # claude_model = "claude-sonnet-5-5" # default: the account's latest Sonnet
@@ -108,7 +116,7 @@ Permissions: only writes ask. `write`/`edit` and unknown `bash` commands prompt;
Auto permissions (`--auto`, `permissions = "auto"`, `/auto [on|off|log]`): nothing prompts for the usual work, and dangerous calls are refused without asking. A refused call returns `blocked by auto mode: <reason>` to the model (also over a stored "always" rule); `/auto log` lists the last 20. Per call, in order: (1) rules block `rm -rf` of home/root/project root/outside the project, `sudo`, raw disk writes and filesystem creation, download piped to a shell, force push, push to main/master, sending `.env`/keys over the network, `npm|cargo publish`, `docker push`, `kubectl delete`, `terraform destroy`, SQL `DROP`, writes to `/etc`, `~/.ssh`, shell rc files, `.git/hooks`; (2) rules allow routine work inside the project (build/test/format, local git, `mkdir`/`mv`/`cp`/`rm` in the project, `write`/`edit` of project files); (3) everything else (unknown binaries, `curl`, `python -c`, `$(..)`, redirects, paths outside the project) goes to one cheap-model request (Haiku/Luna, ~300 input tokens, 20 s timeout) that answers ALLOW or BLOCK; if that fails or is unavailable the normal prompt appears. `--yolo` / `/yolo` still skip everything. With the `claude_cli` provider claude's tools appear on the event bus (`tool_call` / `tool_result`; hx names `bash{command}`, `write|edit|read{path}`, other tools under claude's name), so extensions can block them (a `block` denies the call with its reason) and NDJSON / `hx stats` see them. Reads are asked too (`--settings` `permissions.ask`; Bash too, claude auto-runs read-only commands like `ls` without asking otherwise). In `-p` there is no prompt and everything is allowed, unless `permissions = "deny"` (every unanswered call is denied) or `permissions = "extensions-only"` (allowed only while a live `tool_call` extension exists). The same rules apply to claude's tool calls, but no model judge runs (unclear ones ask). Pattern rules are not a sandbox: combine with `[sandbox]` for confinement. Auto permissions (`--auto`, `permissions = "auto"`, `/auto [on|off|log]`): nothing prompts for the usual work, and dangerous calls are refused without asking. A refused call returns `blocked by auto mode: <reason>` to the model (also over a stored "always" rule); `/auto log` lists the last 20. Per call, in order: (1) rules block `rm -rf` of home/root/project root/outside the project, `sudo`, raw disk writes and filesystem creation, download piped to a shell, force push, push to main/master, sending `.env`/keys over the network, `npm|cargo publish`, `docker push`, `kubectl delete`, `terraform destroy`, SQL `DROP`, writes to `/etc`, `~/.ssh`, shell rc files, `.git/hooks`; (2) rules allow routine work inside the project (build/test/format, local git, `mkdir`/`mv`/`cp`/`rm` in the project, `write`/`edit` of project files); (3) everything else (unknown binaries, `curl`, `python -c`, `$(..)`, redirects, paths outside the project) goes to one cheap-model request (Haiku/Luna, ~300 input tokens, 20 s timeout) that answers ALLOW or BLOCK; if that fails or is unavailable the normal prompt appears. `--yolo` / `/yolo` still skip everything. With the `claude_cli` provider claude's tools appear on the event bus (`tool_call` / `tool_result`; hx names `bash{command}`, `write|edit|read{path}`, other tools under claude's name), so extensions can block them (a `block` denies the call with its reason) and NDJSON / `hx stats` see them. Reads are asked too (`--settings` `permissions.ask`; Bash too, claude auto-runs read-only commands like `ls` without asking otherwise). In `-p` there is no prompt and everything is allowed, unless `permissions = "deny"` (every unanswered call is denied) or `permissions = "extensions-only"` (allowed only while a live `tool_call` extension exists). The same rules apply to claude's tool calls, but no model judge runs (unclear ones ask). Pattern rules are not a sandbox: combine with `[sandbox]` for confinement.
The model can call `task(prompt, kind)` (or `task(prompts=[…], kind)` to fan out: one subagent per prompt, parallel, answers returned numbered; a lone task blocks the parent, so the tool description steers the model to batches) to run a subagent with a fresh context and get back only its final answer (cut at 8 KB), so big searches don't fill the main context. `explore` (default) is read-only (`read`, `lsp`, `bash`) on the provider's cheapest model (`explore_model` in config); `general` has the parent's tools and model, and the lens runs on its edits. Up to 3 run in parallel, none can start another, a parent abort stops them. Their sessions are written to `<session>.sub/`; `hx stats` shows `task` usage (calls, lone vs. batched turns) and lists them and the footer token counts include them. **Overview:** while any subagent exists, a list sits above the footer (bottom right: spinner/✓, id, kind, task, time, calls, tokens). `ctrl-g` focuses it (`↑↓`, `enter` opens, `esc` closes); the detail view shows that agent's live transcript. Typing there messages the agent: while it runs the text is delivered at its next turn end (like steering the main agent), after it finished it continues that agent's conversation. `ctrl-c` aborts that agent only; `ctrl-s` sends its last answer to the main chat as `[subagent N] …`. NDJSON/RPC carry no per-agent events yet. Each `task` call asks for permission (`[a]` allows that kind for the project); `subagents = false` or `--no-subagents` removes the tool. The model can call `task(prompt, kind)` (or `task(prompts=[…], kind)` to fan out: one subagent per prompt, parallel, answers returned numbered; a lone task blocks the parent, so the tool description steers the model to batches) to run a subagent with a fresh context and get back only its final answer (cut at 8 KB), so big searches don't fill the main context. `explore` (default) is read-only (`read`, `lsp`, `bash`) on the provider's cheapest model (`explore_model` in config); `general` has the parent's tools and model, and the lens runs on its edits. Up to 3 run in parallel, none can start another, a parent abort stops them. Their sessions are written to `<session>.sub/`; `hx stats` shows `task` usage (calls, lone vs. batched turns) and lists them and the footer token counts include them. **Overview:** while any subagent exists, a list sits above the footer (bottom right: spinner/✓, id, kind, task, time, calls, tokens). `ctrl-g` focuses it (`↑↓`, `enter` opens, `esc` closes); the detail view shows that agent's live transcript. Typing there messages the agent: while it runs the text is delivered at its next turn end (like steering the main agent), after it finished it continues that agent's conversation. `ctrl-c` aborts that agent only; `ctrl-s` sends its last answer to the main chat as `[subagent N] …`. NDJSON/RPC carry no per-agent events yet.
A child starts with a cold prompt cache and costs tokens of its own: it saves *main-context* size, not total tokens. A child starts with a cold prompt cache and costs tokens of its own: it saves *main-context* size, not total tokens.
+3 -3
View File
@@ -1,7 +1,7 @@
{ {
"version": "0.1.13", "version": "0.2.2",
"sha256": { "sha256": {
"aarch64-apple-darwin": "bbc47b4ef0225201654b0c0330dd161bc88100ad499e1e23652414c6a1d84910", "aarch64-apple-darwin": "84b1789847d5e3b94f903ef5f9cf67336b7b5a2d8801fe9fde68656e5a9167cc",
"x86_64-unknown-linux-musl": "38c000648bb34f99e49437b79dfe9f518f6ca476f6cd9e04892982f0a11a0601" "x86_64-unknown-linux-musl": "ccff5a974df795a044853a66594424e3176eb9c4a8ef2315176ef2ab3ed95dfc"
} }
} }
+3
View File
@@ -5,11 +5,14 @@
# model = "claude-sonnet-5-5" # model for the chosen provider; "auto" = pick per prompt (see [auto]) # model = "claude-sonnet-5-5" # model for the chosen provider; "auto" = pick per prompt (see [auto])
# claude_model = "claude-sonnet-5-5" # default: the account's latest Sonnet # claude_model = "claude-sonnet-5-5" # default: the account's latest Sonnet
# codex_model = "gpt-5.6-sol" # default: Codex's top-listed model # codex_model = "gpt-5.6-sol" # default: Codex's top-listed model
# subagents = false # do not offer the `task` tool (default true; every call asks first)
# explore_model = "claude-haiku-4-5" # read-only `task` subagents; default: cheapest tier of the provider # explore_model = "claude-haiku-4-5" # read-only `task` subagents; default: cheapest tier of the provider
# remember_model = true # reuse the last model picked with /model or /provider # remember_model = true # reuse the last model picked with /model or /provider
# compact_at = 900000 # auto-compact at this many tokens; default: 90% of the context window # compact_at = 900000 # auto-compact at this many tokens; default: 90% of the context window
# max_tokens = 16384 # max_tokens = 16384
# permissions = "ask" # ask | auto (refuse dangerous calls, run safe ones) | yolo (nothing asks) # permissions = "ask" # ask | auto (refuse dangerous calls, run safe ones) | yolo (nothing asks)
# sessions_dir = "~/Nextcloud/hx-sessions" # default ~/.hx/sessions; point at a synced/mounted cloud folder (env HX_SESSIONS_DIR wins)
# sessions_host = false # true: prefix project folders with the host name (machines sharing one sessions_dir)
# mouse = true # wheel scrolling; false keeps terminal text selection # mouse = true # wheel scrolling; false keeps terminal text selection
# codemode = false # `codemode` tool: JS scripts that call other tools in a sandbox # codemode = false # `codemode` tool: JS scripts that call other tools in a sandbox
# system_prompt = "..." # replaces the built-in prompt; AGENTS.md is still appended # system_prompt = "..." # replaces the built-in prompt; AGENTS.md is still appended
+146 -83
View File
@@ -49,6 +49,9 @@ struct Cli {
/// prompt (also `permissions = "auto"`). /// prompt (also `permissions = "auto"`).
#[arg(long, conflicts_with = "yolo")] #[arg(long, conflicts_with = "yolo")]
auto: bool, auto: bool,
/// Do not offer the `task` subagent tool to the model.
#[arg(long)]
no_subagents: bool,
/// Run bash, LSP servers and lens runners in a sandbox (bwrap / seatbelt). /// Run bash, LSP servers and lens runners in a sandbox (bwrap / seatbelt).
#[arg(long, conflicts_with = "no_sandbox")] #[arg(long, conflicts_with = "no_sandbox")]
sandbox: bool, sandbox: bool,
@@ -160,10 +163,16 @@ struct Config {
max_tokens: Option<u32>, max_tokens: Option<u32>,
/// Model for read-only `task` subagents; default: the provider's cheapest tier (Haiku / Luna). /// Model for read-only `task` subagents; default: the provider's cheapest tier (Haiku / Luna).
explore_model: Option<String>, explore_model: Option<String>,
/// Register the `task` subagent tool (default true; each call still asks the user). `--no-subagents` = off.
subagents: Option<bool>,
/// Add the `codemode` tool: JS scripts that call the other tools (default false). /// Add the `codemode` tool: JS scripts that call the other tools (default false).
codemode: Option<bool>, codemode: Option<bool>,
/// Capture the mouse for wheel scrolling (default true; false = terminal selection works without shift). /// Capture the mouse for wheel scrolling (default true; false = terminal selection works without shift).
mouse: Option<bool>, mouse: Option<bool>,
/// Where sessions live (default `~/.hx/sessions`); `~` expands. Point at a synced/mounted cloud folder. `HX_SESSIONS_DIR` wins.
sessions_dir: Option<String>,
/// Prefix session folders with the host name, so machines sharing `sessions_dir` stay apart (default false).
sessions_host: Option<bool>,
/// Reuse the last model chosen with /model or /provider (default true). /// Reuse the last model chosen with /model or /provider (default true).
remember_model: Option<bool>, remember_model: Option<bool>,
/// `/model auto`: tier pins (`fast`, `balanced`, `deep` = model ids) and `down_after`. /// `/model auto`: tier pins (`fast`, `balanced`, `deep` = model ids) and `down_after`.
@@ -236,8 +245,11 @@ impl Config {
compact_at: o.compact_at.or(c.compact_at), compact_at: o.compact_at.or(c.compact_at),
max_tokens: o.max_tokens.or(c.max_tokens), max_tokens: o.max_tokens.or(c.max_tokens),
explore_model: o.explore_model.or(c.explore_model), explore_model: o.explore_model.or(c.explore_model),
subagents: o.subagents.or(c.subagents),
codemode: o.codemode.or(c.codemode), codemode: o.codemode.or(c.codemode),
mouse: o.mouse.or(c.mouse), mouse: o.mouse.or(c.mouse),
sessions_dir: o.sessions_dir.or(c.sessions_dir),
sessions_host: o.sessions_host.or(c.sessions_host),
remember_model: o.remember_model.or(c.remember_model), remember_model: o.remember_model.or(c.remember_model),
auto: o.auto.or(c.auto), auto: o.auto.or(c.auto),
permissions: o.permissions.or(c.permissions), permissions: o.permissions.or(c.permissions),
@@ -252,44 +264,91 @@ impl Config {
} }
} }
/// Tool context for the claude sandbox question (set once the agent exists). /// Tool context of the agent, for the stored "run claude outside the sandbox" rule.
static CLAUDE_CX: std::sync::OnceLock<ToolCtx> = std::sync::OnceLock::new(); static CLAUDE_CX: std::sync::OnceLock<ToolCtx> = std::sync::OnceLock::new();
/// Answer to "run claude outside the sandbox?" for this process.
static CLAUDE_OUTSIDE: std::sync::Mutex<Option<bool>> = std::sync::Mutex::new(None);
const OUTSIDE_RULE: &str = "claude:unsandboxed"; const OUTSIDE_RULE: &str = "claude:unsandboxed";
/// Allowed to leave the sandbox? A stored rule says yes; else the TUI asks (once per run, "always" /// Leave the sandbox only on an explicit, stored rule (`claude:unsandboxed` in `.hx/allow.json`). Never
/// is stored in `.hx/allow.json`); without a prompt hook (`-p`) the answer is no. /// asked and never implied by yolo: yolo is only safe because claude's tools stay confined.
async fn claude_outside() -> bool { fn claude_outside() -> bool {
if let Some(v) = *CLAUDE_OUTSIDE.lock().unwrap_or_else(|e| e.into_inner()) { CLAUDE_CX.get().is_some_and(|cx| {
return v; cx.state
}
let ok = match CLAUDE_CX.get() {
Some(cx) if cx.state.permit.get().is_some() => {
hx_core::tool::gate(
cx,
hx_core::permit::Request {
tool: "claude".into(),
detail: "run claude outside the sandbox (its tools then run unconfined)".into(),
rule: OUTSIDE_RULE.into(),
},
)
.await
}
Some(cx) => cx
.state
.allow .allow
.lock() .lock()
.unwrap_or_else(|e| e.into_inner()) .unwrap_or_else(|e| e.into_inner())
.allows(&hx_core::permit::Request { .has_rule(OUTSIDE_RULE)
tool: "claude".into(), })
detail: String::new(), }
rule: OUTSIDE_RULE.into(),
}), /// `hx mcp-serve`: lens/LSP, hx's MCP servers and (with a permission socket) `approve` for claude.
None => false, async fn mcp_serve() -> Result<()> {
let cwd = std::env::current_dir()?;
let mgr = Arc::new(hx_lens::manager::Manager::new(
cwd.clone(),
hx_lens::manager::default_servers(),
));
let mut reg = hx_core::tool::Registry::default();
reg.add(hx_lens::LspTool::new(mgr.clone()));
let cx = ToolCtx {
cwd: cwd.clone(),
state: Default::default(),
}; };
*CLAUDE_OUTSIDE.lock().unwrap_or_else(|e| e.into_inner()) = Some(ok); let sock = std::env::var_os(hx_core::approve::ENV);
ok 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()));
}
// claude keeps its own tools; hx's MCP servers are added directly, or only through `codemode`
let cfg = Config::load(&cwd)?;
let mut servers =
hx_mcp::config::load(&context::hx_home(), &cwd).map_err(anyhow::Error::msg)?;
// a server entry that is hx itself would spawn mcp-serve recursively
servers.retain(|_, s| !s.args.iter().any(|a| a == "mcp-serve"));
let hub = Arc::new(hx_mcp::Hub::start(servers).await);
if std::env::var_os("HX_CODEMODE").is_some() {
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));
} else {
hub.register(&mut reg);
}
hx_mcp::serve::serve(
reg,
cx,
tokio::io::BufReader::new(tokio::io::stdin()),
tokio::io::stdout(),
)
.await?;
mgr.shutdown().await;
Ok(())
}
/// Appends a line to `$TMPDIR/hx-mcp-serve.log` (writable inside the sandbox too); best effort.
fn mcp_serve_log(line: &str) {
use std::io::Write;
let p = std::env::temp_dir().join("hx-mcp-serve.log");
if let Ok(mut f) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(p)
{
let cwd = std::env::current_dir().unwrap_or_default();
let t = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs());
let _ = writeln!(
f,
"{t} pid {} cwd {}: {line}",
std::process::id(),
cwd.display()
);
}
} }
/// What `claude` (and its `hx mcp-serve` child) need inside the sandbox: its binary and config, /// What `claude` (and its `hx mcp-serve` child) need inside the sandbox: its binary and config,
@@ -321,6 +380,8 @@ fn claude_extra(bin: &str) -> hx_core::sandbox::Extra {
home.join(".claude"), home.join(".claude"),
home.join(".claude.json"), home.join(".claude.json"),
home.join(".config/claude"), home.join(".config/claude"),
// macOS keeps claude's login in the login keychain; without it claude says "Not logged in"
home.join("Library/Keychains"),
hx_core::approve::sock_path(), hx_core::approve::sock_path(),
], ],
network: true, network: true,
@@ -340,11 +401,11 @@ fn claude_extra(bin: &str) -> hx_core::sandbox::Extra {
} }
} }
/// The `claude` command: sandboxed when the sandbox is on, unless the user let it out. /// The `claude` command: sandboxed when the sandbox is on, unless claude's sandbox is off or a rule lets it out.
async fn claude_command(bin: String) -> tokio::process::Command { async fn claude_command(bin: String) -> tokio::process::Command {
if hx_core::sandbox::active().is_none() if hx_core::sandbox::active().is_none()
|| !hx_core::sandbox::claude_sandboxed() || !hx_core::sandbox::claude_sandboxed()
|| claude_outside().await || claude_outside()
{ {
return tokio::process::Command::new(bin); return tokio::process::Command::new(bin);
} }
@@ -585,8 +646,33 @@ impl<H: Hook> Hook for ArcHook<H> {
} }
} }
fn session_dir(cwd: &std::path::Path) -> std::path::PathBuf { fn session_dir(cwd: &std::path::Path, cfg: &Config) -> Result<std::path::PathBuf> {
hx_core::session::dir(&context::hx_home(), cwd) let home = context::hx_home();
let root = match std::env::var("HX_SESSIONS_DIR")
.ok()
.or(cfg.sessions_dir.clone())
{
Some(s) if !s.is_empty() => match s.strip_prefix('~') {
Some(r) => std::env::var_os("HOME")
.map(std::path::PathBuf::from)
.unwrap_or_default()
.join(r.trim_start_matches('/')),
None => s.into(),
},
_ => home.join("sessions"),
};
let host = cfg.sessions_host.unwrap_or(false).then(|| {
["HOSTNAME", "HOST", "COMPUTERNAME"]
.iter()
.find_map(|k| std::env::var(k).ok())
.or_else(|| std::fs::read_to_string("/etc/hostname").ok())
.map_or("host".into(), |h| h.trim().to_string())
});
let dir = hx_core::session::dir(&root, cwd, host.as_deref());
// fail loud: a silent fallback would leave sessions off the cloud folder
std::fs::create_dir_all(&dir)
.map_err(|e| anyhow::anyhow!("sessions dir {}: {e}", dir.display()))?;
Ok(dir)
} }
#[tokio::main] #[tokio::main]
@@ -704,7 +790,9 @@ async fn main() -> Result<()> {
]; ];
rows.extend(skill_rows); rows.extend(skill_rows);
let mut specs = reg.specs(); let mut specs = reg.specs();
specs.push(hx_core::subagent::spec()); if !cli.no_subagents && cfg.subagents != Some(false) {
specs.push(hx_core::subagent::spec());
}
specs.sort_by_key(|t| { specs.sort_by_key(|t| {
std::cmp::Reverse(serde_json::to_string(t).map_or(0, |s| s.len())) std::cmp::Reverse(serde_json::to_string(t).map_or(0, |s| s.len()))
}); });
@@ -776,51 +864,13 @@ async fn main() -> Result<()> {
return Ok(()); return Ok(());
} }
Some(Cmd::McpServe) => { Some(Cmd::McpServe) => {
let cwd = std::env::current_dir()?; // claude starts this and hides its stderr: a failed start shows up only as
let mgr = Arc::new(hx_lens::manager::Manager::new( // "mcp__hx__approve not found", so the reason goes to a log file as well
cwd.clone(), let r = mcp_serve().await;
hx_lens::manager::default_servers(), if let Err(e) = &r {
)); mcp_serve_log(&format!("mcp-serve failed: {e:#}"));
let mut reg = hx_core::tool::Registry::default();
reg.add(hx_lens::LspTool::new(mgr.clone()));
let cx = ToolCtx {
cwd: cwd.clone(),
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()));
} }
// claude keeps its own tools; hx's MCP servers are added directly, or only through `codemode` return r;
let cfg = Config::load(&cwd)?;
let mut servers =
hx_mcp::config::load(&context::hx_home(), &cwd).map_err(anyhow::Error::msg)?;
// a server entry that is hx itself would spawn mcp-serve recursively
servers.retain(|_, s| !s.args.iter().any(|a| a == "mcp-serve"));
let hub = Arc::new(hx_mcp::Hub::start(servers).await);
if std::env::var_os("HX_CODEMODE").is_some() {
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));
} else {
hub.register(&mut reg);
}
hx_mcp::serve::serve(
reg,
cx,
tokio::io::BufReader::new(tokio::io::stdin()),
tokio::io::stdout(),
)
.await?;
mgr.shutdown().await;
return Ok(());
} }
None => {} None => {}
} }
@@ -904,7 +954,7 @@ async fn main() -> Result<()> {
} }
.unwrap_or_else(|| hx_ai::models::default_for(kind, &models)) .unwrap_or_else(|| hx_ai::models::default_for(kind, &models))
}); });
let dir = session_dir(&cwd); let dir = session_dir(&cwd, &cfg)?;
let query = cli.resume.as_deref().filter(|q| !q.is_empty()); let query = cli.resume.as_deref().filter(|q| !q.is_empty());
let path = match (cli.session, cli.r#continue, query) { let path = match (cli.session, cli.r#continue, query) {
_ if acp_id.is_some() => dir.join(format!( _ if acp_id.is_some() => dir.join(format!(
@@ -1052,7 +1102,7 @@ async fn main() -> Result<()> {
mgr.warm(probe).await; mgr.warm(probe).await;
} }
trace("lens"); trace("lens");
{ if !cli.no_subagents && cfg.subagents != Some(false) {
// 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" && n != "exit_plan"); general.retain(|n| n != "ask_user" && n != "exit_plan");
@@ -1144,7 +1194,20 @@ async fn main() -> Result<()> {
}); });
} }
if let Some(id) = acp_id { if let Some(id) = acp_id {
// no TUI, no prompts: every permission question goes to the orchestrator // no TUI, no prompts: every permission question goes to the orchestrator, except what
// --yolo / --auto (or `permissions` in config.toml) settle here, the same as in the TUI
{
let yolo = cli.yolo || cfg.permissions.as_deref() == Some("yolo");
let auto = cli.auto || cfg.permissions.as_deref() == Some("auto");
let mut a = agent
.cx
.state
.allow
.lock()
.unwrap_or_else(|e| e.into_inner());
a.set_yolo(yolo);
a.set_auto(auto && !yolo);
}
let opts = acp::Opts { let opts = acp::Opts {
session: id, session: id,
cwd: cwd.clone(), cwd: cwd.clone(),
+6 -1
View File
@@ -42,7 +42,12 @@ pub fn question(tool: &str, input: &Value) -> Option<Request> {
detail: s("file_path"), detail: s("file_path"),
rule: String::new(), rule: String::new(),
}), }),
"Grep" | "Glob" | "LS" | "TodoWrite" | "NotebookRead" | "Task" | "Agent" => None, "Grep" | "Glob" | "LS" | "TodoWrite" | "NotebookRead" => None,
"Task" | "Agent" => Some(Request {
tool: "task".into(),
detail: format!("subagent: {}", s("description")),
rule: "task:claude".into(),
}),
t if t.starts_with("mcp__hx__") => None, t if t.starts_with("mcp__hx__") => None,
"WebFetch" => Some(crate::permit::request( "WebFetch" => Some(crate::permit::request(
"web_fetch", "web_fetch",
+37 -1
View File
@@ -198,7 +198,7 @@ pub fn needs_permit(tool: &str, args: &serde_json::Value) -> bool {
match tool { match tool {
"bash" => !readonly_cmd(a("command").trim()), "bash" => !readonly_cmd(a("command").trim()),
"read" => secret(a("path")), "read" => secret(a("path")),
"web_fetch" => true, "web_fetch" | "task" => true,
_ => gated(tool), _ => gated(tool),
} }
} }
@@ -261,6 +261,25 @@ pub fn request(tool: &str, args: &serde_json::Value) -> Request {
rule: format!("web:{host}"), rule: format!("web:{host}"),
}; };
} }
if tool == "task" {
let kind = args["kind"].as_str().unwrap_or("explore");
let ps: Vec<&str> = match args["prompts"].as_array() {
Some(a) => a.iter().filter_map(|v| v.as_str()).collect(),
None => vec![args["prompt"].as_str().unwrap_or_default()],
};
let first: String = ps
.first()
.copied()
.unwrap_or_default()
.chars()
.take(120)
.collect();
return Request {
tool: tool.into(),
detail: format!("{} {kind} subagent(s): {first}", ps.len()),
rule: format!("task:{kind}"),
};
}
if tool != "bash" { if tool != "bash" {
return Request { return Request {
tool: tool.into(), tool: tool.into(),
@@ -378,6 +397,16 @@ impl Allow {
self.yolo self.yolo
} }
/// Allow everything (not persisted).
pub fn set_yolo(&mut self, on: bool) {
self.yolo = on;
}
/// A stored rule (`.hx/allow.json` or "always" this session), ignoring yolo and edit grants.
pub fn has_rule(&self, rule: &str) -> bool {
self.rules.contains(rule)
}
/// Toggle: allow everything (not persisted); returns the new state. /// Toggle: allow everything (not persisted); returns the new state.
pub fn toggle_yolo(&mut self) -> bool { pub fn toggle_yolo(&mut self) -> bool {
self.yolo = !self.yolo; self.yolo = !self.yolo;
@@ -467,6 +496,13 @@ mod tests {
assert_eq!(bash("go test $(id)").rule, ""); assert_eq!(bash("go test $(id)").rule, "");
assert_eq!(request("edit", &json!({"path": "a.rs"})).rule, ""); assert_eq!(request("edit", &json!({"path": "a.rs"})).rule, "");
assert!(gated("bash") && !gated("read")); assert!(gated("bash") && !gated("read"));
let t = serde_json::json!({"prompts": ["a", "b"], "kind": "general"});
assert!(needs_permit("task", &t));
let r = request("task", &t);
assert_eq!(
(r.rule.as_str(), r.detail.starts_with("2 general")),
("task:general", true)
);
} }
#[test] #[test]
+113
View File
@@ -91,6 +91,60 @@ impl Default for Cfg {
} }
} }
/// Paths named by `path =` in `[include]` / `[includeIf ...]` sections of the global git config, followed
/// into the included files (a few levels), and the `gitdir:` directories of `includeIf` (git resolves
/// them on every start). `~/` expands; relative paths are relative to the including file.
fn git_includes(home: &Path) -> (Vec<PathBuf>, Vec<PathBuf>) {
let mut todo = vec![home.join(".gitconfig"), home.join(".config/git/config")];
let mut found: Vec<PathBuf> = vec![];
let mut dirs: Vec<PathBuf> = vec![];
let mut depth = 0;
while !todo.is_empty() && depth < 5 {
depth += 1;
let mut next = vec![];
for f in todo {
let Ok(text) = std::fs::read_to_string(&f) else {
continue;
};
let mut include = false;
for line in text.lines().map(str::trim) {
if let Some(sec) = line.strip_prefix('[') {
let sec = sec.trim_start();
include = sec.to_ascii_lowercase().starts_with("include");
// [includeIf "gitdir:~/w/"] or "gitdir/i:..."
if let Some(d) = sec
.split_once('"')
.and_then(|(_, r)| r.split_once(':'))
.filter(|(k, _)| k.starts_with("gitdir"))
.and_then(|(_, v)| v.split('"').next())
.and_then(|v| v.strip_prefix("~/"))
{
dirs.push(home.join(d.trim_end_matches("**").trim_end_matches('/')));
}
continue;
}
let Some((k, v)) = line.split_once('=') else {
continue;
};
if !include || !k.trim().eq_ignore_ascii_case("path") {
continue;
}
let v = v.trim().trim_matches('"');
let p = match v.strip_prefix("~/") {
Some(r) => home.join(r),
None => f.parent().unwrap_or(Path::new("/")).join(v),
};
if !found.contains(&p) {
found.push(p.clone());
next.push(p);
}
}
}
todo = next;
}
(found, dirs)
}
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Sandbox { pub struct Sandbox {
backend: Backend, backend: Backend,
@@ -99,6 +153,8 @@ pub struct Sandbox {
cwd: PathBuf, cwd: PathBuf,
rw: Vec<PathBuf>, rw: Vec<PathBuf>,
ro: Vec<PathBuf>, ro: Vec<PathBuf>,
/// paths under `$HOME` whose metadata (not content) may be read, e.g. `includeIf "gitdir:~/w"`
meta: Vec<PathBuf>,
env_allow: Vec<String>, env_allow: Vec<String>,
} }
@@ -273,6 +329,9 @@ impl Sandbox {
.collect() .collect()
}; };
let mut ro = paths(&cfg.ro); let mut ro = paths(&cfg.ro);
// files the global git config includes (`[include] path = ...`): without them git fails to start
let (inc, meta) = git_includes(&home);
ro.extend(inc.into_iter().filter(|p| p.exists()).map(|p| canon(&p)));
let skills = crate::context::hx_home().join("skills"); let skills = crate::context::hx_home().join("skills");
if skills.exists() { if skills.exists() {
ro.push(canon(&skills)); ro.push(canon(&skills));
@@ -284,6 +343,7 @@ impl Sandbox {
cwd: canon(cwd), cwd: canon(cwd),
rw: paths(&cfg.rw), rw: paths(&cfg.rw),
ro, ro,
meta,
env_allow: cfg.env_allow.clone(), env_allow: cfg.env_allow.clone(),
}) })
} }
@@ -442,6 +502,28 @@ impl Sandbox {
let w = self.writable(); let w = self.writable();
let readable: Vec<PathBuf> = w.iter().chain(self.ro.iter()).cloned().collect(); let readable: Vec<PathBuf> = w.iter().chain(self.ro.iter()).cloned().collect();
p += &format!("(allow file-read* {})\n", list(&readable)); p += &format!("(allow file-read* {})\n", list(&readable));
// stat of $HOME and the directories above each allowed path (git resolves paths component by
// component and dies on EPERM); `literal` = these directories only, not what is inside
let mut dirs: Vec<&Path> = readable
.iter()
.chain(&self.meta)
.flat_map(|p| p.ancestors())
.filter(|a| a.starts_with(&self.home))
.collect();
dirs.sort();
dirs.dedup();
let lit = |p: &Path| {
format!(
"(literal \"{}\")",
p.to_string_lossy()
.replace('\\', "\\\\")
.replace('"', "\\\"")
)
};
p += &format!(
"(allow file-read-metadata {})\n",
dirs.iter().map(|d| lit(d)).collect::<Vec<_>>().join(" ")
);
p += &format!("(allow file-write* {})\n", list(&w)); p += &format!("(allow file-write* {})\n", list(&w));
p += "(allow file-write* (literal \"/dev/null\") (literal \"/dev/tty\"))\n"; p += "(allow file-write* (literal \"/dev/null\") (literal \"/dev/tty\"))\n";
if self.network { if self.network {
@@ -455,6 +537,33 @@ impl Sandbox {
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn git_includes_follow_include_sections() {
let home = std::env::temp_dir().join(format!("hx-gitinc-{}", std::process::id()));
std::fs::create_dir_all(home.join(".config/delta")).unwrap();
std::fs::write(
home.join(".gitconfig"),
"[user]\n path = /not/an/include\n[include]\n path = ~/.config/delta/theme.gitconfig\n[includeIf \"gitdir:~/w/\"]\n path = \"work.gitconfig\"\n",
)
.unwrap();
std::fs::write(
home.join(".config/delta/theme.gitconfig"),
"[include]\npath = nested\n",
)
.unwrap();
let (got, dirs) = git_includes(&home);
let _ = std::fs::remove_dir_all(&home);
assert_eq!(dirs, [home.join("w")]);
assert_eq!(
got,
[
home.join(".config/delta/theme.gitconfig"),
home.join("work.gitconfig"),
home.join(".config/delta/nested"),
]
);
}
fn sb(backend: Backend, network: bool) -> Sandbox { fn sb(backend: Backend, network: bool) -> Sandbox {
Sandbox { Sandbox {
backend, backend,
@@ -463,6 +572,7 @@ mod tests {
cwd: "/home/u/proj".into(), cwd: "/home/u/proj".into(),
rw: vec!["/home/u/.cargo/registry".into()], rw: vec!["/home/u/.cargo/registry".into()],
ro: vec!["/home/u/.cargo".into()], ro: vec!["/home/u/.cargo".into()],
meta: vec!["/home/u/w/x".into()],
env_allow: vec!["PATH".into(), "LC_*".into()], env_allow: vec!["PATH".into(), "LC_*".into()],
} }
} }
@@ -495,6 +605,9 @@ mod tests {
.unwrap() .unwrap()
); );
assert!(p.contains("(allow file-write* (subpath \"/home/u/proj\")")); assert!(p.contains("(allow file-write* (subpath \"/home/u/proj\")"));
assert!(p.contains(
"(allow file-read-metadata (literal \"/home/u\") (literal \"/home/u/.cargo\") (literal \"/home/u/.cargo/registry\") (literal \"/home/u/proj\") (literal \"/home/u/w\") (literal \"/home/u/w/x\"))"
));
assert!( assert!(
sb(Backend::Seatbelt, true) sb(Backend::Seatbelt, true)
.seatbelt_profile() .seatbelt_profile()
+16 -8
View File
@@ -173,14 +173,18 @@ impl Session {
} }
} }
/// `<hx home>/sessions/<slug of cwd>`. /// `<root>/<slug of cwd>`, with `<host>-` in front when `host` is set (shared roots).
pub fn dir(home: &Path, cwd: &Path) -> PathBuf { pub fn dir(root: &Path, cwd: &Path, host: Option<&str>) -> PathBuf {
let slug: String = cwd let cwd = cwd.to_string_lossy();
.to_string_lossy() let slug: String = host
.into_iter()
.chain([cwd.trim_matches('/')])
.collect::<Vec<_>>()
.join("/")
.chars() .chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }) .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
.collect(); .collect();
home.join("sessions").join(slug.trim_matches('-')) root.join(slug.trim_matches('-'))
} }
/// A fresh, not yet created session file in `dir` (created on first append). /// A fresh, not yet created session file in `dir` (created on first append).
@@ -279,7 +283,7 @@ pub fn list(dir: &Path) -> Vec<Meta> {
v v
} }
/// Sessions of every project under `<hx home>/sessions`, newest first. /// Sessions of every project under the sessions root, newest first.
pub fn list_all(root: &Path) -> Vec<Meta> { pub fn list_all(root: &Path) -> Vec<Meta> {
let mut v: Vec<Meta> = std::fs::read_dir(root) let mut v: Vec<Meta> = std::fs::read_dir(root)
.into_iter() .into_iter()
@@ -370,8 +374,12 @@ mod tests {
.collect(); .collect();
assert_eq!(t, [("newer", "other"), ("fix parser", "proj")]); assert_eq!(t, [("newer", "other"), ("fix parser", "proj")]);
assert_eq!( assert_eq!(
dir(Path::new("/h"), Path::new("/a/b c")), dir(Path::new("/h"), Path::new("/a/b c"), None),
Path::new("/h/sessions/a-b-c") Path::new("/h/a-b-c")
);
assert_eq!(
dir(Path::new("/h"), Path::new("/a/b"), Some("box")),
Path::new("/h/box-a-b")
); );
let n = new_path(&proj); let n = new_path(&proj);
assert!(n.starts_with(&proj) && !n.exists()); assert!(n.starts_with(&proj) && !n.exists());
+1 -1
View File
@@ -283,7 +283,7 @@ impl Task {
pub fn spec() -> ToolSpec { pub fn spec() -> ToolSpec {
ToolSpec { ToolSpec {
name: "task".into(), name: "task".into(),
description: "Run a subagent in a fresh context; you get back only its final answer. kind=explore (default): read-only research on a cheaper model; use it for searching/reading that would fill your context (many files or >10k tokens). kind=general: same tools as you, may edit. The subagent sees nothing of this conversation: make every prompt self-contained. You are blocked until it answers, so a single task you then wait on only pays off when the search would put >10k tokens in your context; otherwise do it yourself. Prefer splitting work into 2+ independent subtasks: pass `prompts` (array) or several task calls in one turn, they run in parallel. Not for small lookups.".into(), description: "Run a subagent in a fresh context; you get back only its final answer. The user is asked to approve every call: use it only when the user asked for subagents or parallel work, or when a search would clearly put >10k tokens in your context. Do ordinary discovery (read, grep, lsp, bash) yourself in this session. kind=explore (default): read-only research on a cheaper model. kind=general: same tools as you, may edit. The subagent sees nothing of this conversation: make every prompt self-contained. You are blocked until it answers. For 2+ independent subtasks pass `prompts` (array); they run in parallel.".into(),
input_schema: json!({"type":"object","properties":{ input_schema: json!({"type":"object","properties":{
"prompt":{"type":"string"}, "prompt":{"type":"string"},
"prompts":{"type":"array","items":{"type":"string"},"description":"several independent subtasks: one subagent each, run in parallel, answers returned numbered"}, "prompts":{"type":"array","items":{"type":"string"},"description":"several independent subtasks: one subagent each, run in parallel, answers returned numbered"},
+1 -1
View File
@@ -11,7 +11,7 @@
packages = [ packages = [
pkgs.git pkgs.git
pkgs.stdenv.cc pkgs.stdenv.cc
]; ] ++ lib.optional pkgs.stdenv.hostPlatform.isLinux pkgs.bubblewrap;
languages.rust.enable = true; languages.rust.enable = true;
} }
+6 -2
View File
@@ -31,8 +31,12 @@
# ponytail: tests skipped (need git/network); enable when hermetic. # ponytail: tests skipped (need git/network); enable when hermetic.
doCheck = false; doCheck = false;
# rustls may build aws-lc-sys (cmake) depending on feature set. # rustls may build aws-lc-sys (cmake) depending on feature set.
nativeBuildInputs = [ pkgs.cmake pkgs.perl ]; nativeBuildInputs = [ pkgs.cmake pkgs.perl ] ++ pkgs.lib.optionals pkgs.stdenv.hostPlatform.isLinux [ pkgs.makeWrapper ];
dontUseCmakeConfigure = true; dontUseCmakeConfigure = true;
# bubblewrap sandbox runtime dependency (Linux only).
postInstall = pkgs.lib.optionalString pkgs.stdenv.hostPlatform.isLinux ''
wrapProgram $out/bin/hx --suffix PATH : ${pkgs.lib.makeBinPath [ pkgs.bubblewrap ]}
'';
meta = { meta = {
description = "Minimal Rust coding agent using existing subscriptions"; description = "Minimal Rust coding agent using existing subscriptions";
license = pkgs.lib.licenses.unlicense; license = pkgs.lib.licenses.unlicense;
@@ -67,7 +71,7 @@
devShells = forAll (pkgs: { devShells = forAll (pkgs: {
default = pkgs.mkShell { default = pkgs.mkShell {
packages = with pkgs; [ cargo rustc clippy rustfmt rust-analyzer git ]; packages = with pkgs; [ cargo rustc clippy rustfmt rust-analyzer git ] ++ pkgs.lib.optional pkgs.stdenv.hostPlatform.isLinux pkgs.bubblewrap;
}; };
}); });
}; };