Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
da31c30fd0 | ||
|
|
0626692591 | ||
|
|
9614ac32ab | ||
|
|
c2800b9554 | ||
|
|
f68a7a2c41 | ||
|
|
437f8ec501 | ||
|
|
b1ca582d6b | ||
|
|
37ebf96108 | ||
|
|
47e184738a | ||
|
|
800bae97d7 | ||
|
|
1f4f8aa081 | ||
|
|
061649cb07 | ||
|
|
9d8b7dfbd8 | ||
|
|
179e5cddc7 | ||
|
|
05165d7b8f | ||
|
|
c06381117b | ||
|
|
9fbcf4a62c | ||
|
|
b84b6ab23a | ||
|
|
161c33fe6c | ||
|
|
3f1acd045b | ||
|
|
c849463805 | ||
|
|
742f2a124a | ||
|
|
aec92ff5a5 | ||
|
|
5408db83a9 | ||
|
|
77e32bbc78 | ||
|
|
79cf5fcda1 | ||
|
|
05dbb8e63f | ||
|
|
e119dc2f0d | ||
|
|
0184627f27 | ||
|
|
5d4cdbf10d | ||
|
|
4949a4b558 | ||
|
|
fa8641f803 | ||
|
|
8a9d8fe607 | ||
|
|
36e99fc8af | ||
|
|
1da3d52190 | ||
|
|
f1b3ee0607 | ||
|
|
ddf8bcd92c | ||
|
|
7e0031da2f | ||
|
|
4e4d996a6f | ||
|
|
25936457c9 | ||
|
|
71f05d9a0d | ||
|
|
6978aad27a | ||
|
|
6ebf1c3180 |
No files matched your search
+11
-19
@@ -4,8 +4,6 @@ on:
|
|||||||
branches: [main]
|
branches: [main]
|
||||||
paths-ignore: [bin.json]
|
paths-ignore: [bin.json]
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
env:
|
|
||||||
MACOS_SDK: "14.5"
|
|
||||||
jobs:
|
jobs:
|
||||||
# next version = highest vX.Y.Z tag with the patch bumped; push a tag by hand for minor/major
|
# next version = highest vX.Y.Z tag with the patch bumped; push a tag by hand for minor/major
|
||||||
version:
|
version:
|
||||||
@@ -33,28 +31,22 @@ jobs:
|
|||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
target: [x86_64-unknown-linux-musl, aarch64-apple-darwin]
|
target: [x86_64-unknown-linux-musl, aarch64-apple-darwin]
|
||||||
|
# rust, zig, cargo-zigbuild, both targets and a macOS SDK (SDKROOT) prebuilt;
|
||||||
|
# the runner keeps the pulled image, so no per-run toolchain/SDK setup
|
||||||
|
container:
|
||||||
|
image: ghcr.io/rust-cross/cargo-zigbuild:0.24.1
|
||||||
steps:
|
steps:
|
||||||
|
# the image has no node, which act_runner needs for the JS actions below
|
||||||
|
- run: |
|
||||||
|
case "$(uname -m)" in x86_64) a=x64 ;; aarch64) a=arm64 ;; esac
|
||||||
|
curl -fsSL "https://nodejs.org/dist/v22.11.0/node-v22.11.0-linux-$a.tar.xz" \
|
||||||
|
| tar -xJ -C /usr/local --strip-components=1
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- uses: dtolnay/rust-toolchain@stable
|
# caches ~/.cargo registry/git and target/, keyed on Cargo.lock + toolchain;
|
||||||
with:
|
# a no-op until the runner's cache server is enabled
|
||||||
targets: ${{ matrix.target }}
|
|
||||||
# caches ~/.cargo registry/git and target/, keyed on Cargo.lock + toolchain
|
|
||||||
- uses: Swatinem/rust-cache@v2
|
- uses: Swatinem/rust-cache@v2
|
||||||
with:
|
with:
|
||||||
key: ${{ matrix.target }}
|
key: ${{ matrix.target }}
|
||||||
# zig as cross C compiler/linker for both musl and macOS
|
|
||||||
- run: pip install ziglang cargo-zigbuild
|
|
||||||
# macOS: Apple SDK for Security.framework etc.
|
|
||||||
- if: matrix.target == 'aarch64-apple-darwin'
|
|
||||||
id: sdk-cache
|
|
||||||
uses: actions/cache@v4
|
|
||||||
with:
|
|
||||||
path: ~/MacOSX${{ env.MACOS_SDK }}.sdk
|
|
||||||
key: macos-sdk-${{ env.MACOS_SDK }}
|
|
||||||
- if: matrix.target == 'aarch64-apple-darwin' && steps.sdk-cache.outputs.cache-hit != 'true'
|
|
||||||
run: curl -fsSL "https://github.com/joseluisq/macosx-sdks/releases/download/${MACOS_SDK}/MacOSX${MACOS_SDK}.sdk.tar.xz" | tar -xJ -C "$HOME"
|
|
||||||
- if: matrix.target == 'aarch64-apple-darwin'
|
|
||||||
run: echo "SDKROOT=$HOME/MacOSX${MACOS_SDK}.sdk" >> "$GITHUB_ENV"
|
|
||||||
- run: cargo zigbuild --release --locked --target ${{ matrix.target }} -p hx-cli
|
- run: cargo zigbuild --release --locked --target ${{ matrix.target }} -p hx-cli
|
||||||
env:
|
env:
|
||||||
HX_VERSION: ${{ needs.version.outputs.version }}
|
HX_VERSION: ${{ needs.version.outputs.version }}
|
||||||
|
|||||||
Generated
+19
@@ -1054,6 +1054,7 @@ dependencies = [
|
|||||||
"hx-tui",
|
"hx-tui",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
|
"similar",
|
||||||
"tokio",
|
"tokio",
|
||||||
"toml",
|
"toml",
|
||||||
]
|
]
|
||||||
@@ -1131,6 +1132,7 @@ dependencies = [
|
|||||||
"hx-ai",
|
"hx-ai",
|
||||||
"hx-core",
|
"hx-core",
|
||||||
"ignore",
|
"ignore",
|
||||||
|
"pulldown-cmark",
|
||||||
"ratatui",
|
"ratatui",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"similar",
|
"similar",
|
||||||
@@ -1957,6 +1959,17 @@ dependencies = [
|
|||||||
"unicode-ident",
|
"unicode-ident",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "pulldown-cmark"
|
||||||
|
version = "0.13.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3db2be46835f013dd3f4fa7f5f7402c537787b54ebb6fe2b94bbdd7e2669bb7b"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags 2.13.2",
|
||||||
|
"memchr",
|
||||||
|
"unicase",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "quinn"
|
name = "quinn"
|
||||||
version = "0.11.12"
|
version = "0.11.12"
|
||||||
@@ -3164,6 +3177,12 @@ version = "0.1.7"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971"
|
checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "unicase"
|
||||||
|
version = "2.10.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "unicode-ident"
|
name = "unicode-ident"
|
||||||
version = "1.0.26"
|
version = "1.0.26"
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -106,9 +114,9 @@ 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.
|
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.
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"version": "0.1.7",
|
"version": "0.2.3",
|
||||||
"sha256": {
|
"sha256": {
|
||||||
"aarch64-apple-darwin": "344a37aeee8ff92b7908a65f0a9d999b83c6ecf609e8e18c4e6709d76d228b0f",
|
"aarch64-apple-darwin": "0f1e039b4694e0835a0cceac8902b34093bd67502bfc5abc820ae862450d3e68",
|
||||||
"x86_64-unknown-linux-musl": "b7ab51611366c777ea58aac0b7dc76efa2ea9c372368e784b5e668bc8861b17d"
|
"x86_64-unknown-linux-musl": "6f9d6c01b4e56eeb59deaf283581f9609fd3e799eca878cbce295a61d7826649"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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 {
|
||||||
|
|||||||
@@ -20,7 +20,8 @@ hx-tools = { version = "0.1.0", path = "../hx-tools" }
|
|||||||
hx-mcp = { version = "0.1.0", path = "../hx-mcp" }
|
hx-mcp = { version = "0.1.0", path = "../hx-mcp" }
|
||||||
hx-tui = { version = "0.1.0", path = "../hx-tui" }
|
hx-tui = { version = "0.1.0", path = "../hx-tui" }
|
||||||
serde = { version = "1.0.229", features = ["derive"] }
|
serde = { version = "1.0.229", features = ["derive"] }
|
||||||
tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "signal", "io-std", "io-util"] }
|
similar = "3.2.0"
|
||||||
|
tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "signal", "io-std", "io-util", "sync", "time"] }
|
||||||
serde_json = "1.0.151"
|
serde_json = "1.0.151"
|
||||||
toml = "1.1.6"
|
toml = "1.1.6"
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,795 @@
|
|||||||
|
//! Headless Agent Client Protocol server: `hx serve --acp --cwd <dir> --session <id>`.
|
||||||
|
//!
|
||||||
|
//! JSON-RPC 2.0, one message per line on stdio; the orchestrator is the client.
|
||||||
|
//! Standard ACP: `initialize`, `session/new|load`, `session/prompt`, `session/cancel`,
|
||||||
|
//! `session/update` (notifications out), `session/request_permission` (request out).
|
||||||
|
//! Orchestrator extensions: in `hx/step`, `hx/message`, `hx/interrupt`, `hx/compact`;
|
||||||
|
//! out `hx/step_result`, `hx/intent`, `hx/edit`, `hx/usage`, `hx/decision`, `hx/plan`.
|
||||||
|
//!
|
||||||
|
//! The model reports step outcome, decisions and plan in a closing ```hx-step JSON block
|
||||||
|
//! (see [`PROMPT`]); that works the same for every provider, including the `claude` CLI whose
|
||||||
|
//! tools hx does not own.
|
||||||
|
|
||||||
|
use crate::rpc::emit;
|
||||||
|
use anyhow::Result;
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use hx_ai::{Pricing, StreamEvent, Usage};
|
||||||
|
use hx_core::agent::{AbortHandle, Agent, Error};
|
||||||
|
use hx_core::hook::{Event, Hook, HookAction};
|
||||||
|
use hx_core::permit::Decision;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::SeqCst};
|
||||||
|
use std::sync::{Arc, Mutex as StdMutex};
|
||||||
|
use std::time::Duration;
|
||||||
|
use tokio::io::AsyncBufReadExt;
|
||||||
|
use tokio::sync::{Mutex, oneshot};
|
||||||
|
|
||||||
|
const PROMPT: &str = r#"
|
||||||
|
|
||||||
|
# Headless step
|
||||||
|
You run as one step of an automated pipeline. Nobody answers questions while you work: decide
|
||||||
|
yourself and state assumptions. If you cannot go on without a human answer, stop and ask it.
|
||||||
|
Lines starting with "Messages since your last step" are hints from the orchestrator; follow them.
|
||||||
|
End every step with exactly one fenced block, last in your reply:
|
||||||
|
|
||||||
|
```hx-step
|
||||||
|
{"status": "done" | "blocked" | "needs_input",
|
||||||
|
"summary": "what you did, 1-3 sentences",
|
||||||
|
"catch": "blocked only: one name from the catch list of the step, else omit",
|
||||||
|
"question": "the one question you need answered (needs_input only)",
|
||||||
|
"decisions": ["choices worth recording, e.g. token bucket over sliding window"],
|
||||||
|
"plan": {"steps": ["..."], "files": ["paths you will touch"]}}
|
||||||
|
```
|
||||||
|
`decisions` and `plan` are optional; give `plan` in planning steps. Put free text in `summary`,
|
||||||
|
never in `catch`."#;
|
||||||
|
|
||||||
|
/// Server options from the command line and the finished agent setup.
|
||||||
|
pub struct Opts {
|
||||||
|
pub session: String,
|
||||||
|
pub cwd: PathBuf,
|
||||||
|
pub pricing: Option<Pricing>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Outgoing messages and requests waiting for the client's answer.
|
||||||
|
struct Link {
|
||||||
|
sid: String,
|
||||||
|
next: AtomicU64,
|
||||||
|
pending: StdMutex<HashMap<u64, oneshot::Sender<Value>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Link {
|
||||||
|
fn notify(&self, method: &str, params: Value) {
|
||||||
|
emit(&json!({"jsonrpc": "2.0", "method": method, "params": params}));
|
||||||
|
}
|
||||||
|
fn update(&self, u: Value) {
|
||||||
|
self.notify(
|
||||||
|
"session/update",
|
||||||
|
json!({"sessionId": self.sid, "update": u}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
/// The client's whole reply message; None when the connection closed first.
|
||||||
|
async fn request(&self, method: &str, params: Value) -> Option<Value> {
|
||||||
|
let id = self.next.fetch_add(1, SeqCst);
|
||||||
|
let (tx, rx) = oneshot::channel();
|
||||||
|
self.pending
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|e| e.into_inner())
|
||||||
|
.insert(id, tx);
|
||||||
|
emit(&json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}));
|
||||||
|
rx.await.ok()
|
||||||
|
}
|
||||||
|
fn resolve(&self, id: &Value, msg: Value) {
|
||||||
|
let tx = id.as_u64().and_then(|n| {
|
||||||
|
self.pending
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|e| e.into_inner())
|
||||||
|
.remove(&n)
|
||||||
|
});
|
||||||
|
if let Some(tx) = tx {
|
||||||
|
let _ = tx.send(msg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Unanswered requests fail (permissions are denied).
|
||||||
|
fn close(&self) {
|
||||||
|
self.pending
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|e| e.into_inner())
|
||||||
|
.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn respond(id: &Value, r: Result<Value, String>) {
|
||||||
|
if id.is_null() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
emit(&match r {
|
||||||
|
Ok(v) => json!({"jsonrpc": "2.0", "id": id, "result": v}),
|
||||||
|
Err(e) => json!({"jsonrpc": "2.0", "id": id, "error": {"code": -32000, "message": e}}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct M {
|
||||||
|
step: Usage,
|
||||||
|
total: Usage,
|
||||||
|
/// context tokens of the last request
|
||||||
|
ctx: u64,
|
||||||
|
ctx_limit: Option<u64>,
|
||||||
|
cost_limit: Option<f64>,
|
||||||
|
/// why the run must end at the next turn boundary
|
||||||
|
stop: Option<String>,
|
||||||
|
/// hints from `hx/message`, injected at the next turn boundary
|
||||||
|
pending: Vec<String>,
|
||||||
|
/// a question the model tried to ask a human
|
||||||
|
question: Option<String>,
|
||||||
|
intent: String,
|
||||||
|
/// file contents before a write/edit call, by tool call id
|
||||||
|
before: HashMap<String, Option<String>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Turns bus events into ACP notifications and enforces the step limits.
|
||||||
|
struct Meter {
|
||||||
|
link: Arc<Link>,
|
||||||
|
abort: AbortHandle,
|
||||||
|
cwd: PathBuf,
|
||||||
|
pricing: Option<Pricing>,
|
||||||
|
/// context limit reported when the step sets none
|
||||||
|
window: u64,
|
||||||
|
st: StdMutex<M>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn kind(tool: &str) -> &'static str {
|
||||||
|
match tool {
|
||||||
|
"bash" => "execute",
|
||||||
|
"write" | "edit" => "edit",
|
||||||
|
"read" => "read",
|
||||||
|
"grep" | "find" | "ls" | "lsp" => "search",
|
||||||
|
"web_fetch" | "web_search" => "fetch",
|
||||||
|
_ => "other",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn intent_of(name: &str, args: &Value) -> String {
|
||||||
|
let s = |k: &str| args[k].as_str().unwrap_or_default();
|
||||||
|
let short = |t: &str| {
|
||||||
|
t.lines()
|
||||||
|
.next()
|
||||||
|
.unwrap_or_default()
|
||||||
|
.chars()
|
||||||
|
.take(80)
|
||||||
|
.collect::<String>()
|
||||||
|
};
|
||||||
|
match name {
|
||||||
|
"bash" => format!("Running `{}`", short(s("command"))),
|
||||||
|
"edit" => format!("Editing {}", s("path")),
|
||||||
|
"write" => format!("Writing {}", s("path")),
|
||||||
|
"read" => format!("Reading {}", s("path")),
|
||||||
|
_ => format!("Using {name}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// (added, removed) lines between two file contents.
|
||||||
|
fn line_diff(old: &str, new: &str) -> (usize, usize) {
|
||||||
|
use similar::{ChangeTag, TextDiff};
|
||||||
|
TextDiff::from_lines(old, new)
|
||||||
|
.iter_all_changes()
|
||||||
|
.fold((0, 0), |(a, r), c| match c.tag() {
|
||||||
|
ChangeTag::Insert => (a + 1, r),
|
||||||
|
ChangeTag::Delete => (a, r + 1),
|
||||||
|
ChangeTag::Equal => (a, r),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Meter {
|
||||||
|
fn m(&self) -> std::sync::MutexGuard<'_, M> {
|
||||||
|
self.st.lock().unwrap_or_else(|e| e.into_inner())
|
||||||
|
}
|
||||||
|
fn cost(&self, u: &Usage) -> f64 {
|
||||||
|
self.pricing.map_or(0.0, |p| u.cost(&p))
|
||||||
|
}
|
||||||
|
fn usage_note(&self, m: &M) {
|
||||||
|
self.link.notify(
|
||||||
|
"hx/usage",
|
||||||
|
json!({"used": m.ctx, "limit": m.ctx_limit.unwrap_or(self.window),
|
||||||
|
"cost": self.cost(&m.total)}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
fn path(&self, args: &Value) -> PathBuf {
|
||||||
|
self.cwd.join(args["path"].as_str().unwrap_or_default())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn begin(&self, ctx: Option<u64>, cost: Option<f64>) {
|
||||||
|
let mut m = self.m();
|
||||||
|
m.step = Usage::default();
|
||||||
|
m.ctx_limit = ctx;
|
||||||
|
m.cost_limit = cost;
|
||||||
|
m.stop = None;
|
||||||
|
m.question = None;
|
||||||
|
}
|
||||||
|
/// Ask the run to end after the current tool round; the first reason wins.
|
||||||
|
fn stop(&self, why: impl Into<String>) {
|
||||||
|
let mut m = self.m();
|
||||||
|
m.stop.get_or_insert(why.into());
|
||||||
|
}
|
||||||
|
fn take(&self) -> (Option<String>, Option<String>) {
|
||||||
|
let mut m = self.m();
|
||||||
|
(m.stop.take(), m.question.take())
|
||||||
|
}
|
||||||
|
fn sync(&self, total: &Usage, ctx: Option<u64>) {
|
||||||
|
let mut m = self.m();
|
||||||
|
m.total = total.clone();
|
||||||
|
if let Some(c) = ctx {
|
||||||
|
m.ctx = c;
|
||||||
|
}
|
||||||
|
self.usage_note(&m);
|
||||||
|
}
|
||||||
|
fn say(&self, m: &mut M, text: String) {
|
||||||
|
if m.intent != text {
|
||||||
|
self.link.notify("hx/intent", json!(text));
|
||||||
|
m.intent = text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl Hook for Meter {
|
||||||
|
async fn on(&self, ev: &Event) -> HookAction {
|
||||||
|
match ev {
|
||||||
|
Event::Stream(StreamEvent::TextDelta { text }) => {
|
||||||
|
self.link.update(json!({
|
||||||
|
"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": text}}))
|
||||||
|
}
|
||||||
|
Event::Stream(StreamEvent::ThinkingDelta { text }) => {
|
||||||
|
self.link.update(json!({
|
||||||
|
"sessionUpdate": "agent_thought_chunk", "content": {"type": "text", "text": text}}))
|
||||||
|
}
|
||||||
|
Event::Stream(StreamEvent::Done { usage, .. }) => {
|
||||||
|
let mut m = self.m();
|
||||||
|
m.step.add(usage);
|
||||||
|
m.total.add(usage);
|
||||||
|
m.ctx = usage.input_tokens + usage.cache_read_tokens + usage.cache_write_tokens;
|
||||||
|
if let Some(l) = m.ctx_limit.filter(|l| m.ctx >= *l) {
|
||||||
|
let why = format!(
|
||||||
|
"context limit reached ({}/{l} tokens); send hx/compact",
|
||||||
|
m.ctx
|
||||||
|
);
|
||||||
|
m.stop.get_or_insert(why);
|
||||||
|
}
|
||||||
|
if let Some(l) = m.cost_limit.filter(|l| self.cost(&m.step) >= *l) {
|
||||||
|
m.stop.get_or_insert(format!("cost limit ${l:.2} reached"));
|
||||||
|
}
|
||||||
|
self.usage_note(&m);
|
||||||
|
}
|
||||||
|
Event::SubUsage(u) => {
|
||||||
|
let mut m = self.m();
|
||||||
|
m.step.add(u);
|
||||||
|
m.total.add(u);
|
||||||
|
self.usage_note(&m);
|
||||||
|
}
|
||||||
|
Event::ToolCall { id, name, args } => {
|
||||||
|
let text = intent_of(name, args);
|
||||||
|
let mut m = self.m();
|
||||||
|
self.say(&mut m, text.clone());
|
||||||
|
if matches!(name.as_str(), "write" | "edit") {
|
||||||
|
m.before
|
||||||
|
.insert(id.clone(), std::fs::read_to_string(self.path(args)).ok());
|
||||||
|
}
|
||||||
|
drop(m);
|
||||||
|
self.link
|
||||||
|
.update(json!({"sessionUpdate": "tool_call", "toolCallId": id,
|
||||||
|
"title": text, "kind": kind(name), "status": "in_progress", "rawInput": args}));
|
||||||
|
}
|
||||||
|
Event::ToolResult {
|
||||||
|
id,
|
||||||
|
args,
|
||||||
|
content,
|
||||||
|
is_error,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
let shown: String = content.chars().take(4000).collect();
|
||||||
|
self.link.update(
|
||||||
|
json!({"sessionUpdate": "tool_call_update", "toolCallId": id,
|
||||||
|
"status": if *is_error { "failed" } else { "completed" },
|
||||||
|
"content": [{"type": "content", "content": {"type": "text", "text": shown}}]}),
|
||||||
|
);
|
||||||
|
let old = self.m().before.remove(id);
|
||||||
|
if let (false, Some(old)) = (*is_error, old) {
|
||||||
|
let p = self.path(args);
|
||||||
|
if let Ok(new) = std::fs::read_to_string(&p) {
|
||||||
|
let (added, removed) = line_diff(old.as_deref().unwrap_or_default(), &new);
|
||||||
|
let rel = p.strip_prefix(&self.cwd).unwrap_or(&p);
|
||||||
|
self.link.notify(
|
||||||
|
"hx/edit",
|
||||||
|
json!({"path": rel, "added": added, "removed": removed}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Event::TurnEnd | Event::AgentEnd => {
|
||||||
|
let mut m = self.m();
|
||||||
|
if m.stop.is_some() {
|
||||||
|
if matches!(ev, Event::TurnEnd) {
|
||||||
|
self.abort.abort();
|
||||||
|
}
|
||||||
|
} else if !m.pending.is_empty() {
|
||||||
|
return HookAction::Inject(format!(
|
||||||
|
"Messages since your last step:\n{}",
|
||||||
|
std::mem::take(&mut m.pending)
|
||||||
|
.iter()
|
||||||
|
.map(|h| format!("- {h}"))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\n")
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
HookAction::Continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Options shown to the client for a permission request.
|
||||||
|
fn options(always: bool) -> Value {
|
||||||
|
let mut o = vec![json!({"optionId": "allow_once", "name": "Allow", "kind": "allow_once"})];
|
||||||
|
if always {
|
||||||
|
o.push(json!({"optionId": "allow_always", "name": "Allow always", "kind": "allow_always"}));
|
||||||
|
}
|
||||||
|
o.push(json!({"optionId": "reject_once", "name": "Deny", "kind": "reject_once"}));
|
||||||
|
json!(o)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `Some(option id)` when the client picked one; None = cancelled, error or connection gone.
|
||||||
|
async fn permission(
|
||||||
|
link: &Link,
|
||||||
|
mut abort: tokio::sync::watch::Receiver<bool>,
|
||||||
|
call: Value,
|
||||||
|
always: bool,
|
||||||
|
) -> Option<String> {
|
||||||
|
let params = json!({"sessionId": link.sid, "toolCall": call, "options": options(always)});
|
||||||
|
let reply = tokio::select! {
|
||||||
|
r = link.request("session/request_permission", params) => r?,
|
||||||
|
_ = async { abort.wait_for(|a| *a).await.is_ok() } => return None,
|
||||||
|
};
|
||||||
|
let o = &reply["result"]["outcome"];
|
||||||
|
(o["outcome"] == "selected")
|
||||||
|
.then(|| o["optionId"].as_str().map(String::from))
|
||||||
|
.flatten()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wire permission, yes/no and multiple-choice questions to the client.
|
||||||
|
fn install(agent: &Agent, link: &Arc<Link>, meter: &Arc<Meter>) {
|
||||||
|
let state = &agent.cx.state;
|
||||||
|
let abort = state.abort.get().cloned();
|
||||||
|
let calls = Arc::new(AtomicU64::new(0));
|
||||||
|
let rx = move || {
|
||||||
|
abort
|
||||||
|
.clone()
|
||||||
|
.unwrap_or_else(|| tokio::sync::watch::channel(false).1)
|
||||||
|
};
|
||||||
|
{
|
||||||
|
let (link, rx, calls) = (link.clone(), rx.clone(), calls.clone());
|
||||||
|
let _ = state.permit.set(Arc::new(move |r| {
|
||||||
|
let (link, rx) = (link.clone(), rx.clone());
|
||||||
|
let n = calls.fetch_add(1, SeqCst);
|
||||||
|
Box::pin(async move {
|
||||||
|
let call = json!({"toolCallId": format!("perm-{n}"),
|
||||||
|
"title": format!("{}: {}", r.tool, r.detail), "kind": kind(&r.tool),
|
||||||
|
"status": "pending", "rawInput": {"tool": r.tool, "detail": r.detail}});
|
||||||
|
// file tools have no rule; their "always" means all edits this session
|
||||||
|
let always = !r.rule.is_empty() || matches!(r.tool.as_str(), "write" | "edit");
|
||||||
|
match permission(&link, rx(), call, always).await.as_deref() {
|
||||||
|
Some("allow_once") => Decision::Once,
|
||||||
|
Some("allow_always") if matches!(r.tool.as_str(), "write" | "edit") => {
|
||||||
|
Decision::Edits
|
||||||
|
}
|
||||||
|
Some("allow_always") => Decision::Always,
|
||||||
|
_ => Decision::Deny,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
{
|
||||||
|
let (link, rx) = (link.clone(), rx.clone());
|
||||||
|
let _ = state.ask.set(Arc::new(move |q| {
|
||||||
|
let (link, rx) = (link.clone(), rx.clone());
|
||||||
|
let n = calls.fetch_add(1, SeqCst);
|
||||||
|
Box::pin(async move {
|
||||||
|
let call = json!({"toolCallId": format!("perm-{n}"), "title": q,
|
||||||
|
"kind": "other", "status": "pending"});
|
||||||
|
permission(&link, rx(), call, false).await.as_deref() == Some("allow_once")
|
||||||
|
})
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
{
|
||||||
|
// no human to answer: remember the question, the step ends as needs_input
|
||||||
|
let meter = meter.clone();
|
||||||
|
let _ = state.choose.set(Arc::new(move |q| {
|
||||||
|
meter.m().question.get_or_insert(q.text);
|
||||||
|
Box::pin(async { None })
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn text_of(v: &Value) -> Option<String> {
|
||||||
|
match v {
|
||||||
|
Value::Null => None,
|
||||||
|
Value::String(s) => (!s.trim().is_empty()).then(|| s.clone()),
|
||||||
|
// ACP content blocks
|
||||||
|
Value::Array(a) if a.iter().all(|b| b["text"].is_string()) => {
|
||||||
|
let t: Vec<_> = a.iter().filter_map(|b| b["text"].as_str()).collect();
|
||||||
|
Some(t.join("\n"))
|
||||||
|
}
|
||||||
|
o => serde_json::to_string_pretty(o).ok(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// instruction, context and prompt of an `hx/step` as one user message.
|
||||||
|
fn compose(p: &Value) -> String {
|
||||||
|
let mut parts = vec![];
|
||||||
|
parts.extend(text_of(&p["instruction"]));
|
||||||
|
parts.extend(text_of(&p["context"]).map(|c| format!("Context:\n{c}")));
|
||||||
|
parts.extend(text_of(&p["prompt"]));
|
||||||
|
parts.join("\n\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn num(v: &Value, keys: &[&str]) -> Option<f64> {
|
||||||
|
keys.iter().find_map(|k| v[k].as_f64()).filter(|n| *n > 0.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The closing ```hx-step block of a reply.
|
||||||
|
fn report(text: &str) -> Option<(Value, &str)> {
|
||||||
|
let i = text.rfind("```hx-step")?;
|
||||||
|
let rest = &text[i + "```hx-step".len()..];
|
||||||
|
let end = rest.find("```")?;
|
||||||
|
Some((
|
||||||
|
serde_json::from_str(rest[..end].trim()).ok()?,
|
||||||
|
text[..i].trim(),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn now() -> u64 {
|
||||||
|
std::time::SystemTime::now()
|
||||||
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
.map_or(0, |d| d.as_secs())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `hx/step_result` payload from the model's reply; sends `hx/decision` and `hx/plan` on the way.
|
||||||
|
fn outcome(link: &Link, reply: &str, question: Option<String>, catches: &[String]) -> Value {
|
||||||
|
let (rep, body) = report(reply).unwrap_or((Value::Null, reply.trim()));
|
||||||
|
for d in rep["decisions"].as_array().into_iter().flatten() {
|
||||||
|
let (text, state) = match d {
|
||||||
|
Value::String(s) => (s.as_str(), "made"),
|
||||||
|
o => (
|
||||||
|
o["text"].as_str().unwrap_or_default(),
|
||||||
|
o["state"].as_str().unwrap_or("made"),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
if !text.is_empty() {
|
||||||
|
link.notify(
|
||||||
|
"hx/decision",
|
||||||
|
json!({"text": text, "state": state, "at": now()}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if rep["plan"].is_object() {
|
||||||
|
link.notify(
|
||||||
|
"hx/plan",
|
||||||
|
json!({"steps": rep["plan"]["steps"], "files": rep["plan"]["files"]}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let mut status = rep["status"]
|
||||||
|
.as_str()
|
||||||
|
.filter(|s| matches!(*s, "done" | "blocked" | "needs_input"))
|
||||||
|
.unwrap_or(if question.is_some() {
|
||||||
|
"needs_input"
|
||||||
|
} else {
|
||||||
|
"done"
|
||||||
|
});
|
||||||
|
let q = rep["question"].as_str().map(String::from).or(question);
|
||||||
|
if status == "needs_input" && q.is_none() {
|
||||||
|
status = "blocked";
|
||||||
|
}
|
||||||
|
let mut summary: String = rep["summary"]
|
||||||
|
.as_str()
|
||||||
|
.map_or_else(|| body.chars().take(1500).collect(), String::from);
|
||||||
|
// `catch` is a name from the step's catch list, only on blocked; anything else is free text
|
||||||
|
let mut catch = Value::Null;
|
||||||
|
if let (true, Some(c)) = (status == "blocked", rep["catch"].as_str()) {
|
||||||
|
if catches.iter().any(|n| n == c) {
|
||||||
|
catch = json!(c);
|
||||||
|
} else if !c.is_empty() {
|
||||||
|
summary = format!("{summary} ({c})");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
json!({"status": status, "summary": summary, "catch": catch, "question": q})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Catch names the orchestrator offers in `hx/step` (`catches`, also inside `context`).
|
||||||
|
fn catch_names(p: &Value) -> Vec<String> {
|
||||||
|
[&p["catches"], &p["context"]["catches"]]
|
||||||
|
.iter()
|
||||||
|
.find_map(|v| v.as_array())
|
||||||
|
.into_iter()
|
||||||
|
.flatten()
|
||||||
|
.filter_map(|c| c.as_str().map(String::from))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Srv {
|
||||||
|
link: Arc<Link>,
|
||||||
|
meter: Arc<Meter>,
|
||||||
|
agent: Arc<Mutex<Agent>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One step; returns the `hx/step_result` payload.
|
||||||
|
async fn step(s: &Srv, p: &Value) -> Value {
|
||||||
|
// no catch: a stop that is not one of the state's catches names its reason instead
|
||||||
|
let blocked = |reason: &str, why: String| {
|
||||||
|
json!({"status": "blocked", "summary": why, "catch": null, "reason": reason,
|
||||||
|
"question": null})
|
||||||
|
};
|
||||||
|
let mut prompt = compose(p);
|
||||||
|
if prompt.is_empty() {
|
||||||
|
return blocked("error", "empty step: no prompt".into());
|
||||||
|
}
|
||||||
|
let catches = catch_names(p);
|
||||||
|
if !catches.is_empty() {
|
||||||
|
prompt.push_str(&format!(
|
||||||
|
"\n\nValid `catch` names when status is blocked: {}. Use one only if it fits.",
|
||||||
|
catches.join(", ")
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let lim = &p["limits"];
|
||||||
|
let wall = num(lim, &["wall_time_secs", "wall_time", "wall_secs"]);
|
||||||
|
s.meter.begin(
|
||||||
|
num(lim, &["context_tokens", "context"]).map(|n| n as u64),
|
||||||
|
num(lim, &["cost_usd", "cost"]),
|
||||||
|
);
|
||||||
|
let mut a = s.agent.lock().await;
|
||||||
|
let r = {
|
||||||
|
let run = a.run(prompt);
|
||||||
|
tokio::pin!(run);
|
||||||
|
let deadline = async {
|
||||||
|
match wall {
|
||||||
|
Some(w) => tokio::time::sleep(Duration::from_secs_f64(w)).await,
|
||||||
|
None => std::future::pending().await,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
tokio::select! {
|
||||||
|
r = &mut run => r,
|
||||||
|
_ = deadline => {
|
||||||
|
s.meter.stop(format!("wall time limit {}s reached", wall.unwrap_or_default()));
|
||||||
|
// soft stop at the next turn boundary; a stuck tool gets a grace period
|
||||||
|
tokio::select! {
|
||||||
|
r = &mut run => r,
|
||||||
|
_ = tokio::time::sleep(Duration::from_secs(30)) => {
|
||||||
|
s.meter.abort.abort();
|
||||||
|
run.await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let (stop, question) = s.meter.take();
|
||||||
|
s.meter.sync(a.usage(), None);
|
||||||
|
match r {
|
||||||
|
Ok(m) => outcome(&s.link, &m.text(), question, &catches),
|
||||||
|
Err(Error::Aborted) => match stop {
|
||||||
|
Some(s) if s == "interrupted" => blocked("interrupted", s),
|
||||||
|
Some(s) => blocked("limit", s),
|
||||||
|
None => blocked("cancelled", "cancelled".into()),
|
||||||
|
},
|
||||||
|
Err(e) => blocked("error", e.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn serve(mut agent: Agent, abort: AbortHandle, o: Opts) -> Result<()> {
|
||||||
|
let link = Arc::new(Link {
|
||||||
|
sid: o.session,
|
||||||
|
next: AtomicU64::new(1),
|
||||||
|
pending: Default::default(),
|
||||||
|
});
|
||||||
|
let meter = Arc::new(Meter {
|
||||||
|
link: link.clone(),
|
||||||
|
abort: abort.clone(),
|
||||||
|
cwd: o.cwd,
|
||||||
|
pricing: o.pricing,
|
||||||
|
window: agent.compact_at() as u64,
|
||||||
|
st: Default::default(),
|
||||||
|
});
|
||||||
|
// nobody to answer exit_plan; the step reports its plan instead
|
||||||
|
agent.tools.retain(|n| n != "exit_plan");
|
||||||
|
agent.append_system(PROMPT);
|
||||||
|
install(&agent, &link, &meter);
|
||||||
|
agent.bus.add_arc(meter.clone());
|
||||||
|
let srv = Arc::new(Srv {
|
||||||
|
link: link.clone(),
|
||||||
|
meter: meter.clone(),
|
||||||
|
agent: Arc::new(Mutex::new(agent)),
|
||||||
|
});
|
||||||
|
let busy = Arc::new(AtomicBool::new(false));
|
||||||
|
let mut tasks = vec![];
|
||||||
|
let mut lines = tokio::io::BufReader::new(tokio::io::stdin()).lines();
|
||||||
|
while let Some(l) = lines.next_line().await? {
|
||||||
|
let Ok(m) = serde_json::from_str::<Value>(&l) else {
|
||||||
|
emit(&json!({"jsonrpc": "2.0", "id": null,
|
||||||
|
"error": {"code": -32700, "message": "parse error"}}));
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let (id, p) = (m["id"].clone(), m["params"].clone());
|
||||||
|
let Some(method) = m["method"].as_str() else {
|
||||||
|
// answer to one of our requests
|
||||||
|
link.resolve(&id, m);
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
match method {
|
||||||
|
"initialize" => respond(
|
||||||
|
&id,
|
||||||
|
Ok(json!({"protocolVersion": 1, "authMethods": [],
|
||||||
|
"agentCapabilities": {"loadSession": true, "promptCapabilities": {}},
|
||||||
|
"agentInfo": {"name": "hx", "version": env!("CARGO_PKG_VERSION")}})),
|
||||||
|
),
|
||||||
|
// the session id is fixed by --session
|
||||||
|
"session/new" | "session/load" => respond(&id, Ok(json!({"sessionId": link.sid}))),
|
||||||
|
"session/cancel" => abort.abort(),
|
||||||
|
"hx/interrupt" => {
|
||||||
|
if busy.load(SeqCst) {
|
||||||
|
meter.stop("interrupted");
|
||||||
|
}
|
||||||
|
respond(&id, Ok(json!({})));
|
||||||
|
}
|
||||||
|
"hx/message" => {
|
||||||
|
match text_of(&p)
|
||||||
|
.or_else(|| text_of(&p["text"]))
|
||||||
|
.or_else(|| text_of(&p["message"]))
|
||||||
|
{
|
||||||
|
Some(t) => {
|
||||||
|
meter.m().pending.push(t);
|
||||||
|
respond(&id, Ok(json!({})));
|
||||||
|
}
|
||||||
|
None => respond(&id, Err("message text required".into())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"hx/compact" => {
|
||||||
|
if busy.swap(true, SeqCst) {
|
||||||
|
respond(&id, Err("busy: a step is running".into()));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let (srv, busy) = (srv.clone(), busy.clone());
|
||||||
|
tasks.push(tokio::spawn(async move {
|
||||||
|
let mut a = srv.agent.lock().await;
|
||||||
|
let r = a.compact_now().await;
|
||||||
|
srv.meter.sync(a.usage(), Some(a.context_tokens() as u64));
|
||||||
|
busy.store(false, SeqCst);
|
||||||
|
respond(
|
||||||
|
&id,
|
||||||
|
r.map(|c| json!({"compacted": c}))
|
||||||
|
.map_err(|e| e.to_string()),
|
||||||
|
);
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
"hx/step" | "session/prompt" => {
|
||||||
|
if busy.swap(true, SeqCst) {
|
||||||
|
respond(&id, Err("busy: a step is running".into()));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let (srv, busy) = (srv.clone(), busy.clone());
|
||||||
|
let acp = method == "session/prompt";
|
||||||
|
tasks.push(tokio::spawn(async move {
|
||||||
|
let hints = std::mem::take(&mut srv.meter.m().pending);
|
||||||
|
let mut p = p;
|
||||||
|
if !hints.is_empty() {
|
||||||
|
let h = hints.iter().map(|h| format!("- {h}")).collect::<Vec<_>>();
|
||||||
|
p["instruction"] = json!(format!(
|
||||||
|
"Messages since your last step:\n{}\n\n{}",
|
||||||
|
h.join("\n"),
|
||||||
|
text_of(&p["instruction"]).unwrap_or_default()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let out = step(&srv, &p).await;
|
||||||
|
busy.store(false, SeqCst);
|
||||||
|
srv.link.notify("hx/step_result", out.clone());
|
||||||
|
respond(
|
||||||
|
&id,
|
||||||
|
Ok(if acp {
|
||||||
|
let cancelled = out["reason"] == "cancelled";
|
||||||
|
json!({"stopReason": if cancelled { "cancelled" } else { "end_turn" }})
|
||||||
|
} else {
|
||||||
|
out
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
other => respond(&id, Err(format!("method not found: {other}"))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// client gone: stop the running step, deny open permission requests
|
||||||
|
abort.abort();
|
||||||
|
link.close();
|
||||||
|
for t in tasks {
|
||||||
|
let _ = t.await;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn report_block_is_parsed() {
|
||||||
|
let t = "did it\n```hx-step\n{\"status\":\"blocked\",\"catch\":\"x\"}\n```";
|
||||||
|
let (v, body) = report(t).unwrap();
|
||||||
|
assert_eq!((v["status"].as_str(), body), (Some("blocked"), "did it"));
|
||||||
|
assert!(report("no block").is_none());
|
||||||
|
assert!(report("```hx-step\nnot json\n```").is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn step_prompt_and_limits() {
|
||||||
|
let p = json!({"instruction": "implement", "context": {"goal": "x"}, "prompt": "go"});
|
||||||
|
let c = compose(&p);
|
||||||
|
assert!(c.starts_with("implement\n\nContext:\n{"), "{c}");
|
||||||
|
assert!(c.ends_with("\n\ngo"));
|
||||||
|
assert_eq!(
|
||||||
|
num(&json!({"cost_usd": 2.5}), &["cost_usd", "cost"]),
|
||||||
|
Some(2.5)
|
||||||
|
);
|
||||||
|
assert_eq!(num(&json!({"cost_usd": 0}), &["cost_usd"]), None);
|
||||||
|
assert_eq!(
|
||||||
|
text_of(&json!([{"type": "text", "text": "a"}])),
|
||||||
|
Some("a".into())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn diff_counts_lines() {
|
||||||
|
assert_eq!(line_diff("a\nb\n", "a\nc\nd\n"), (2, 1));
|
||||||
|
assert_eq!(line_diff("", "x\n"), (1, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn outcome_defaults() {
|
||||||
|
let l = Link {
|
||||||
|
sid: "s".into(),
|
||||||
|
next: AtomicU64::new(1),
|
||||||
|
pending: Default::default(),
|
||||||
|
};
|
||||||
|
assert_eq!(outcome(&l, "all good", None, &[])["status"], "done");
|
||||||
|
let o = outcome(&l, "hmm", Some("which db?".into()), &[]);
|
||||||
|
assert_eq!(
|
||||||
|
(o["status"].as_str(), o["question"].as_str()),
|
||||||
|
(Some("needs_input"), Some("which db?"))
|
||||||
|
);
|
||||||
|
// needs_input without a question cannot be answered
|
||||||
|
let r = "```hx-step\n{\"status\":\"needs_input\"}\n```";
|
||||||
|
assert_eq!(outcome(&l, r, None, &[])["status"], "blocked");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn catch_must_be_a_listed_name() {
|
||||||
|
let l = Link {
|
||||||
|
sid: "s".into(),
|
||||||
|
next: AtomicU64::new(1),
|
||||||
|
pending: Default::default(),
|
||||||
|
};
|
||||||
|
let names = catch_names(&json!({"context": {"catches": ["PlanInvalid", "ToolDenied"]}}));
|
||||||
|
let blocked = |c: &str| {
|
||||||
|
let r = format!(
|
||||||
|
"```hx-step\n{{\"status\":\"blocked\",\"summary\":\"s\",\"catch\":\"{c}\"}}\n```"
|
||||||
|
);
|
||||||
|
outcome(&l, &r, None, &names)
|
||||||
|
};
|
||||||
|
assert_eq!(blocked("ToolDenied")["catch"], "ToolDenied");
|
||||||
|
let o = blocked("made up");
|
||||||
|
assert_eq!(
|
||||||
|
(o["catch"].is_null(), o["summary"].as_str()),
|
||||||
|
(true, Some("s (made up)"))
|
||||||
|
);
|
||||||
|
// caveats on a done step are not a catch
|
||||||
|
let r = "```hx-step\n{\"status\":\"done\",\"catch\":\"ToolDenied\"}\n```";
|
||||||
|
assert!(outcome(&l, r, None, &names)["catch"].is_null());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,11 +5,14 @@
|
|||||||
# model = "claude-sonnet-5-5" # model for the chosen provider; "auto" = pick per prompt (see [auto])
|
# 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
|
||||||
|
|||||||
+202
-84
@@ -11,6 +11,7 @@ use hx_core::switch::Switcher;
|
|||||||
use hx_core::tool::ToolCtx;
|
use hx_core::tool::ToolCtx;
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
|
|
||||||
|
mod acp;
|
||||||
mod rpc;
|
mod rpc;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
@@ -48,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,
|
||||||
@@ -97,6 +101,18 @@ enum Cmd {
|
|||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
action: ConfigAction,
|
action: ConfigAction,
|
||||||
},
|
},
|
||||||
|
/// Run headless for an orchestrator: Agent Client Protocol (JSON-RPC) on stdio, no TUI.
|
||||||
|
Serve {
|
||||||
|
/// Speak ACP on stdio (the only protocol so far).
|
||||||
|
#[arg(long)]
|
||||||
|
acp: bool,
|
||||||
|
/// Working directory (the worktree to edit).
|
||||||
|
#[arg(long)]
|
||||||
|
cwd: std::path::PathBuf,
|
||||||
|
/// Session id; a later `hx serve` with the same id continues that conversation.
|
||||||
|
#[arg(long)]
|
||||||
|
session: String,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Subcommand)]
|
#[derive(Subcommand)]
|
||||||
@@ -147,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`.
|
||||||
@@ -223,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),
|
||||||
@@ -239,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,
|
||||||
@@ -308,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,
|
||||||
@@ -327,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);
|
||||||
}
|
}
|
||||||
@@ -572,15 +646,62 @@ 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]
|
||||||
async fn main() -> Result<()> {
|
async fn main() -> Result<()> {
|
||||||
trace("main");
|
trace("main");
|
||||||
let cli = Cli::parse();
|
let cli = Cli::parse();
|
||||||
|
let mut acp_id = None;
|
||||||
match cli.cmd {
|
match cli.cmd {
|
||||||
|
Some(Cmd::Serve { acp, cwd, session }) => {
|
||||||
|
anyhow::ensure!(acp, "hx serve: --acp is required");
|
||||||
|
// file-name safe, so the id maps to one session file
|
||||||
|
let id: String = session
|
||||||
|
.chars()
|
||||||
|
.map(|c| {
|
||||||
|
if c.is_ascii_alphanumeric() || "-_.".contains(c) {
|
||||||
|
c
|
||||||
|
} else {
|
||||||
|
'_'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
anyhow::ensure!(
|
||||||
|
!id.trim_matches('.').is_empty(),
|
||||||
|
"hx serve: --session is empty"
|
||||||
|
);
|
||||||
|
std::env::set_current_dir(&cwd)
|
||||||
|
.map_err(|e| anyhow::anyhow!("--cwd {}: {e}", cwd.display()))?;
|
||||||
|
acp_id = Some(id);
|
||||||
|
}
|
||||||
Some(Cmd::Login { provider }) => {
|
Some(Cmd::Login { provider }) => {
|
||||||
auth::login(provider).await?;
|
auth::login(provider).await?;
|
||||||
eprintln!("logged in; credentials in {}", auth::store_path().display());
|
eprintln!("logged in; credentials in {}", auth::store_path().display());
|
||||||
@@ -595,6 +716,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(());
|
||||||
}
|
}
|
||||||
@@ -668,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()))
|
||||||
});
|
});
|
||||||
@@ -740,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 => {}
|
||||||
}
|
}
|
||||||
@@ -868,9 +954,13 @@ 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!(
|
||||||
|
"acp-{}.jsonl",
|
||||||
|
acp_id.as_deref().unwrap_or_default()
|
||||||
|
)),
|
||||||
(Some(p), _, _) => p,
|
(Some(p), _, _) => p,
|
||||||
(None, _, Some(q)) => {
|
(None, _, Some(q)) => {
|
||||||
let all = hx_core::session::list(&dir);
|
let all = hx_core::session::list(&dir);
|
||||||
@@ -1012,10 +1102,10 @@ 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");
|
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 {
|
||||||
@@ -1096,10 +1186,38 @@ 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;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
if let Some(id) = acp_id {
|
||||||
|
// 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 {
|
||||||
|
session: id,
|
||||||
|
cwd: cwd.clone(),
|
||||||
|
pricing: pricing(agent.model()),
|
||||||
|
};
|
||||||
|
let r = acp::serve(agent, abort, opts).await;
|
||||||
|
hx_core::herdr::release().await;
|
||||||
|
mgr.shutdown().await;
|
||||||
|
return r;
|
||||||
|
}
|
||||||
let Some(prompt) = cli.print else {
|
let Some(prompt) = cli.print else {
|
||||||
hx_tui::run(hx_tui::Setup {
|
hx_tui::run(hx_tui::Setup {
|
||||||
agent,
|
agent,
|
||||||
|
|||||||
+189
-7
@@ -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
|
||||||
}
|
}
|
||||||
@@ -390,7 +433,12 @@ impl Agent {
|
|||||||
) -> Result<futures::stream::BoxStream<'static, hx_ai::Result<StreamEvent>>, Error> {
|
) -> Result<futures::stream::BoxStream<'static, hx_ai::Result<StreamEvent>>, Error> {
|
||||||
let mut wait = self.retry_ms;
|
let mut wait = self.retry_ms;
|
||||||
for attempt in 1..=4 {
|
for attempt in 1..=4 {
|
||||||
match self.provider.stream(req.clone()).await {
|
let mut ab = self.abort.clone();
|
||||||
|
let r = tokio::select! {
|
||||||
|
r = self.provider.stream(req.clone()) => r,
|
||||||
|
_ = async { ab.wait_for(|a| *a).await.is_ok() } => return Err(Error::Aborted),
|
||||||
|
};
|
||||||
|
match r {
|
||||||
Err(hx_ai::Error::Api { status, .. }) if attempt < 4 && transient(status) => {
|
Err(hx_ai::Error::Api { status, .. }) if attempt < 4 && transient(status) => {
|
||||||
self.emit(Event::Info(format!(
|
self.emit(Event::Info(format!(
|
||||||
"api error {status}; retry {attempt}/3 in {wait}ms"
|
"api error {status}; retry {attempt}/3 in {wait}ms"
|
||||||
@@ -434,8 +482,12 @@ impl Agent {
|
|||||||
if self.aborted() {
|
if self.aborted() {
|
||||||
return Err(Error::Aborted);
|
return Err(Error::Aborted);
|
||||||
}
|
}
|
||||||
|
let mut ab = self.abort.clone();
|
||||||
if self.window.should_compact(&self.session.messages())
|
if self.window.should_compact(&self.session.messages())
|
||||||
&& self.compact(KEEP_MESSAGES).await?
|
&& tokio::select! {
|
||||||
|
r = self.compact(KEEP_MESSAGES) => r?,
|
||||||
|
_ = async { ab.wait_for(|a| *a).await.is_ok() } => return Err(Error::Aborted),
|
||||||
|
}
|
||||||
{
|
{
|
||||||
self.emit(Event::Info("context compacted".into())).await;
|
self.emit(Event::Info("context compacted".into())).await;
|
||||||
}
|
}
|
||||||
@@ -460,6 +512,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,
|
||||||
@@ -550,17 +606,32 @@ impl Agent {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let outs = self
|
// Inner calls of `codemode` arrive on `rx` while the round runs; show them as notices.
|
||||||
.tools
|
let (ntx, mut nrx) = tokio::sync::mpsc::unbounded_channel::<String>();
|
||||||
.call_all(
|
*self.cx.state.nested.lock().unwrap_or_else(|e| e.into_inner()) = Some(ntx);
|
||||||
|
let outs = {
|
||||||
|
let round = self.tools.call_all(
|
||||||
runnable
|
runnable
|
||||||
.iter()
|
.iter()
|
||||||
.map(|(_, n, a)| (n.clone(), a.clone()))
|
.map(|(_, n, a)| (n.clone(), a.clone()))
|
||||||
.collect(),
|
.collect(),
|
||||||
&self.cx,
|
&self.cx,
|
||||||
)
|
);
|
||||||
.await;
|
tokio::pin!(round);
|
||||||
|
loop {
|
||||||
|
tokio::select! {
|
||||||
|
outs = &mut round => break outs,
|
||||||
|
Some(line) = nrx.recv() => { self.emit(Event::Info(line)).await; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
self.cx.state.nested.lock().unwrap_or_else(|e| e.into_inner()).take();
|
||||||
|
while let Ok(line) = nrx.try_recv() {
|
||||||
|
self.emit(Event::Info(line)).await;
|
||||||
|
}
|
||||||
|
let mut images = vec![];
|
||||||
for ((i, name, args), mut r) in runnable.into_iter().zip(outs) {
|
for ((i, name, args), mut r) in runnable.into_iter().zip(outs) {
|
||||||
|
images.append(&mut r.images);
|
||||||
let id = calls[i].0.clone();
|
let id = calls[i].0.clone();
|
||||||
if repeat.seen(&name, &args, &r.content) {
|
if repeat.seen(&name, &args, &r.content) {
|
||||||
r.content.push_str(REPEAT_HINT);
|
r.content.push_str(REPEAT_HINT);
|
||||||
@@ -592,6 +663,12 @@ impl Agent {
|
|||||||
self.emit(Event::SubUsage(sub)).await;
|
self.emit(Event::SubUsage(sub)).await;
|
||||||
}
|
}
|
||||||
let mut content: Vec<ContentBlock> = results.into_iter().flatten().collect();
|
let mut content: Vec<ContentBlock> = results.into_iter().flatten().collect();
|
||||||
|
// Images follow all tool results (providers want results first).
|
||||||
|
content.extend(
|
||||||
|
images
|
||||||
|
.into_iter()
|
||||||
|
.map(|(media_type, data)| ContentBlock::Image { media_type, data }),
|
||||||
|
);
|
||||||
let o = self.emit(Event::TurnEnd).await;
|
let o = self.emit(Event::TurnEnd).await;
|
||||||
if !o.inject.is_empty() {
|
if !o.inject.is_empty() {
|
||||||
self.emit(Event::Injected(o.inject.clone())).await;
|
self.emit(Event::Injected(o.inject.clone())).await;
|
||||||
@@ -762,6 +839,78 @@ mod tests {
|
|||||||
assert!(r.messages[2].text().contains("why?"));
|
assert!(r.messages[2].text().contains("why?"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn tool_images_follow_results_and_nested_notes_become_info() {
|
||||||
|
struct Pic;
|
||||||
|
#[async_trait]
|
||||||
|
impl Tool for Pic {
|
||||||
|
fn spec(&self) -> ToolSpec {
|
||||||
|
ToolSpec {
|
||||||
|
name: "pic".into(),
|
||||||
|
description: "".into(),
|
||||||
|
input_schema: json!({"type":"object"}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async fn call(&self, _: Value, cx: &ToolCtx) -> ToolResult {
|
||||||
|
if let Some(tx) = cx.state.nested.lock().unwrap().as_ref() {
|
||||||
|
let _ = tx.send(" ↳ inner".into());
|
||||||
|
}
|
||||||
|
ToolResult::ok("a picture").with_images(vec![("image/png".into(), "QQ==".into())])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
struct Notes(Arc<Mutex<Vec<String>>>);
|
||||||
|
#[async_trait]
|
||||||
|
impl Hook for Notes {
|
||||||
|
async fn on(&self, ev: &Event) -> HookAction {
|
||||||
|
if let Event::Info(s) = ev {
|
||||||
|
self.0.lock().unwrap().push(s.clone());
|
||||||
|
}
|
||||||
|
HookAction::Continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let call = |name: &str| {
|
||||||
|
asst(vec![ContentBlock::ToolUse {
|
||||||
|
id: "1".into(),
|
||||||
|
name: name.into(),
|
||||||
|
input: json!({}),
|
||||||
|
}])
|
||||||
|
};
|
||||||
|
let script = Arc::new(Script(
|
||||||
|
Mutex::new(vec![
|
||||||
|
call("pic"),
|
||||||
|
asst(vec![ContentBlock::Text { text: "ok".into() }]),
|
||||||
|
]),
|
||||||
|
Mutex::new(vec![]),
|
||||||
|
));
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let mut tools = Registry::default();
|
||||||
|
tools.add(Pic);
|
||||||
|
let cx = ToolCtx {
|
||||||
|
cwd: dir.path().into(),
|
||||||
|
state: Default::default(),
|
||||||
|
};
|
||||||
|
let (mut a, _h) = Agent::new(
|
||||||
|
script.clone(),
|
||||||
|
tools,
|
||||||
|
Session::open(dir.path().join("s.jsonl")).unwrap(),
|
||||||
|
cx,
|
||||||
|
);
|
||||||
|
let notes = Arc::new(Mutex::new(vec![]));
|
||||||
|
a.bus.add(Notes(notes.clone()));
|
||||||
|
a.run("go").await.unwrap();
|
||||||
|
let reqs = script.1.lock().unwrap();
|
||||||
|
let turn = &reqs[1].messages[2];
|
||||||
|
assert!(matches!(&turn.content[0], ContentBlock::ToolResult { content, .. } if content == "a picture"));
|
||||||
|
assert_eq!(
|
||||||
|
turn.content[1],
|
||||||
|
ContentBlock::Image {
|
||||||
|
media_type: "image/png".into(),
|
||||||
|
data: "QQ==".into()
|
||||||
|
}
|
||||||
|
);
|
||||||
|
assert!(notes.lock().unwrap().iter().any(|n| n.contains("inner")));
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn multi_turn_with_hooks() {
|
async fn multi_turn_with_hooks() {
|
||||||
let script = Arc::new(Script(
|
let script = Arc::new(Script(
|
||||||
@@ -872,6 +1021,39 @@ mod tests {
|
|||||||
(r, n)
|
(r, n)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct Hang;
|
||||||
|
#[async_trait]
|
||||||
|
impl Provider for Hang {
|
||||||
|
async fn stream(
|
||||||
|
&self,
|
||||||
|
_: Request,
|
||||||
|
) -> hx_ai::Result<BoxStream<'static, hx_ai::Result<StreamEvent>>> {
|
||||||
|
std::future::pending().await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn abort_ends_a_request_that_never_answers() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let cx = ToolCtx {
|
||||||
|
cwd: dir.path().into(),
|
||||||
|
state: Default::default(),
|
||||||
|
};
|
||||||
|
let (mut a, h) = Agent::new(
|
||||||
|
Arc::new(Hang),
|
||||||
|
Registry::default(),
|
||||||
|
Session::open(dir.path().join("s.jsonl")).unwrap(),
|
||||||
|
cx,
|
||||||
|
);
|
||||||
|
let t = tokio::spawn(async move {
|
||||||
|
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
|
||||||
|
h.abort();
|
||||||
|
});
|
||||||
|
let r = tokio::time::timeout(std::time::Duration::from_secs(5), a.run("go")).await;
|
||||||
|
t.await.unwrap();
|
||||||
|
assert!(matches!(r, Ok(Err(Error::Aborted))));
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn transient_api_errors_are_retried() {
|
async fn transient_api_errors_are_retried() {
|
||||||
let (r, n) = flaky_run(1, 529).await;
|
let (r, n) = flaky_run(1, 529).await;
|
||||||
|
|||||||
@@ -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;
|
||||||
@@ -41,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",
|
||||||
@@ -58,8 +64,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 +131,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 +141,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 +217,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 +266,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 +364,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 +402,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 +439,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;
|
||||||
@@ -213,6 +219,7 @@ impl Tool for ExtTool {
|
|||||||
Ok(r) => ToolResult {
|
Ok(r) => ToolResult {
|
||||||
content: r["content"].as_str().unwrap_or_default().into(),
|
content: r["content"].as_str().unwrap_or_default().into(),
|
||||||
is_error: r["is_error"].as_bool().unwrap_or(false),
|
is_error: r["is_error"].as_bool().unwrap_or(false),
|
||||||
|
images: vec![],
|
||||||
},
|
},
|
||||||
Err(e) => ToolResult::err(e),
|
Err(e) => ToolResult::err(e),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -100,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.
|
||||||
@@ -117,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,8 +86,16 @@ 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>,
|
||||||
|
/// Set by the agent while a tool round runs: `codemode` reports its inner calls here as
|
||||||
|
/// one-line notices, which the agent shows as `Event::Info`.
|
||||||
|
pub nested: Mutex<Option<tokio::sync::mpsc::UnboundedSender<String>>>,
|
||||||
|
/// `codemode`'s `store()`/`load()` values, kept across calls.
|
||||||
|
/// ponytail: lives in memory only; a resumed session starts empty.
|
||||||
|
pub codemode_store: Mutex<std::collections::BTreeMap<String, serde_json::Value>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Lens results of the last turn, structured (the injected text is for the model).
|
/// Lens results of the last turn, structured (the injected text is for the model).
|
||||||
|
|||||||
@@ -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(),
|
||||||
@@ -328,6 +347,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 +366,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),
|
||||||
}
|
}
|
||||||
@@ -375,12 +397,31 @@ 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;
|
||||||
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
|
||||||
}
|
}
|
||||||
@@ -455,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]
|
||||||
|
|||||||
@@ -371,7 +371,20 @@ impl Router {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
let prefer = self.cur.map_or(start, |(k, _)| k);
|
let prefer = self.cur.map_or(start, |(k, _)| k);
|
||||||
let (kind, model) = pick_for(tier, prefer, avoid, models, &self.cfg)?;
|
let (mut kind, mut model) = pick_for(tier, prefer, avoid, models, &self.cfg)?;
|
||||||
|
// the history must fit the window (a 1M session cannot go down to a 200k Haiku)
|
||||||
|
let mut tier = tier;
|
||||||
|
while (hx_ai::models::window(models, &model) as usize) * 9 / 10 < sig.ctx {
|
||||||
|
let up = match tier {
|
||||||
|
Tier::Fast => Tier::Balanced,
|
||||||
|
Tier::Balanced => Tier::Deep,
|
||||||
|
_ => break,
|
||||||
|
};
|
||||||
|
let Some((k, m)) = pick_for(up, kind, avoid, models, &self.cfg) else {
|
||||||
|
break;
|
||||||
|
};
|
||||||
|
(tier, kind, model) = (up, k, m);
|
||||||
|
}
|
||||||
// no Fable in the catalog: it ran as Deep
|
// no Fable in the catalog: it ran as Deep
|
||||||
let tier = if tier == Tier::Max && Tier::of(&model) != Some(Tier::Max) {
|
let tier = if tier == Tier::Max && Tier::of(&model) != Some(Tier::Max) {
|
||||||
Tier::Deep
|
Tier::Deep
|
||||||
@@ -485,7 +498,7 @@ mod tests {
|
|||||||
ModelInfo {
|
ModelInfo {
|
||||||
id: id.into(),
|
id: id.into(),
|
||||||
kind,
|
kind,
|
||||||
context_window: 1,
|
context_window: 1_000_000,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -635,6 +648,19 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn history_too_big_for_the_window_skips_the_small_tier() {
|
||||||
|
let mut r = Router::new(Cfg::default());
|
||||||
|
let mut light = signals("commit", &[]);
|
||||||
|
assert_eq!(light.tier, Tier::Fast);
|
||||||
|
light.ctx = 250_000;
|
||||||
|
let mut c = cat();
|
||||||
|
c[2].context_window = 200_000;
|
||||||
|
c[1].context_window = 1_000_000;
|
||||||
|
let p = r.route(&light, Kind::Claude, None, &c).unwrap();
|
||||||
|
assert_eq!(p.model, "claude-sonnet-5-5");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn effort_follows_score_and_provider() {
|
fn effort_follows_score_and_provider() {
|
||||||
assert_eq!(effort_for(-2, Kind::Claude), Effort::Off);
|
assert_eq!(effort_for(-2, Kind::Claude), Effort::Off);
|
||||||
|
|||||||
@@ -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()
|
||||||
|
|||||||
@@ -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());
|
||||||
|
|||||||
@@ -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};
|
||||||
|
|
||||||
|
|||||||
@@ -96,6 +96,7 @@ pub struct Subs {
|
|||||||
list: Mutex<Vec<Arc<Sub>>>,
|
list: Mutex<Vec<Arc<Sub>>>,
|
||||||
/// (child id, event) for the UI; set by interactive frontends
|
/// (child id, event) for the UI; set by interactive frontends
|
||||||
pub events: OnceLock<mpsc::UnboundedSender<(usize, Event)>>,
|
pub events: OnceLock<mpsc::UnboundedSender<(usize, Event)>>,
|
||||||
|
watching: std::sync::atomic::AtomicBool,
|
||||||
}
|
}
|
||||||
|
|
||||||
const KEEP: usize = 20;
|
const KEEP: usize = 20;
|
||||||
@@ -107,6 +108,36 @@ impl Subs {
|
|||||||
pub fn get(&self, id: usize) -> Option<Arc<Sub>> {
|
pub fn get(&self, id: usize) -> Option<Arc<Sub>> {
|
||||||
self.list().into_iter().find(|s| s.sh.id == id)
|
self.list().into_iter().find(|s| s.sh.id == id)
|
||||||
}
|
}
|
||||||
|
/// Abort every running child (also those continued in the background after their task ended).
|
||||||
|
pub fn abort_all(&self) {
|
||||||
|
for s in self.list() {
|
||||||
|
if s.sh.status() == Status::Running {
|
||||||
|
s.abort();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn any_running(&self) -> bool {
|
||||||
|
self.list().iter().any(|s| s.sh.status() == Status::Running)
|
||||||
|
}
|
||||||
|
/// Once per session: every parent abort reaches all running children. The parent flag resets
|
||||||
|
/// after each run, so the loop re-arms.
|
||||||
|
fn watch(&self, state: &Arc<crate::State>) {
|
||||||
|
let Some(mut rx) = state.abort.get().cloned() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if self.watching.swap(true, Ordering::Relaxed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let st = state.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
while rx.wait_for(|a| *a).await.is_ok() {
|
||||||
|
st.subs.abort_all();
|
||||||
|
if rx.wait_for(|a| !*a).await.is_err() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
fn add(&self, s: Arc<Sub>) {
|
fn add(&self, s: Arc<Sub>) {
|
||||||
let mut l = self.list.lock().unwrap_or_else(|e| e.into_inner());
|
let mut l = self.list.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
l.push(s);
|
l.push(s);
|
||||||
@@ -252,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"},
|
||||||
@@ -292,6 +323,7 @@ impl Tool for Task {
|
|||||||
ToolResult {
|
ToolResult {
|
||||||
content: out,
|
content: out,
|
||||||
is_error: err,
|
is_error: err,
|
||||||
|
images: vec![],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -357,23 +389,12 @@ impl Task {
|
|||||||
sem: self.sem.clone(),
|
sem: self.sem.clone(),
|
||||||
});
|
});
|
||||||
cx.state.subs.add(sub.clone());
|
cx.state.subs.add(sub.clone());
|
||||||
// parent abort stops the child
|
cx.state.subs.watch(&cx.state);
|
||||||
let bridge = cx.state.abort.get().cloned().map(|mut rx| {
|
|
||||||
let s = sub.clone();
|
|
||||||
tokio::spawn(async move {
|
|
||||||
if rx.wait_for(|a| *a).await.is_ok() {
|
|
||||||
s.abort();
|
|
||||||
}
|
|
||||||
})
|
|
||||||
});
|
|
||||||
// waiting for a slot may have outlasted an abort
|
// waiting for a slot may have outlasted an abort
|
||||||
if aborted() {
|
if aborted() {
|
||||||
sub.abort();
|
sub.abort();
|
||||||
}
|
}
|
||||||
let r = sub.drive(prompt.to_string()).await;
|
let r = sub.drive(prompt.to_string()).await;
|
||||||
if let Some(b) = bridge {
|
|
||||||
b.abort();
|
|
||||||
}
|
|
||||||
let u = sh.usage.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
let u = sh.usage.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
||||||
let tok = u.input_tokens + u.cache_read_tokens + u.cache_write_tokens + u.output_tokens;
|
let tok = u.input_tokens + u.cache_read_tokens + u.cache_write_tokens + u.output_tokens;
|
||||||
let stats = format!(
|
let stats = format!(
|
||||||
@@ -682,4 +703,41 @@ mod tests {
|
|||||||
assert_eq!(reqs[1].messages.len(), 3);
|
assert_eq!(reqs[1].messages.len(), 3);
|
||||||
assert_eq!(cx.state.sub_usage.lock().unwrap().input_tokens, 2000);
|
assert_eq!(cx.state.sub_usage.lock().unwrap().input_tokens, 2000);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn parent_abort_reaches_background_child() {
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
let p = Arc::new(Script(
|
||||||
|
Mutex::new(vec![text("a"), call("read", json!({}))]),
|
||||||
|
Default::default(),
|
||||||
|
));
|
||||||
|
let t = Task::new(
|
||||||
|
role(&p, "cheap"),
|
||||||
|
role(&p, "main"),
|
||||||
|
d.path().join("s.sub"),
|
||||||
|
2,
|
||||||
|
);
|
||||||
|
let (parent, h) = Agent::new(
|
||||||
|
p.clone(),
|
||||||
|
Registry::default(),
|
||||||
|
Session::open(d.path().join("p.jsonl")).unwrap(),
|
||||||
|
ToolCtx {
|
||||||
|
cwd: d.path().into(),
|
||||||
|
state: Default::default(),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
let cx = parent.cx.clone();
|
||||||
|
t.call(json!({"prompt":"one"}), &cx).await;
|
||||||
|
let sub = cx.state.subs.get(1).unwrap();
|
||||||
|
sub.prompt("two".into());
|
||||||
|
assert!(cx.state.subs.any_running());
|
||||||
|
h.abort();
|
||||||
|
for _ in 0..100 {
|
||||||
|
if sub.sh.status() == Status::Aborted {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
|
||||||
|
}
|
||||||
|
assert_eq!(sub.sh.status(), Status::Aborted);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -11,6 +11,8 @@ use std::sync::Arc;
|
|||||||
pub struct ToolResult {
|
pub struct ToolResult {
|
||||||
pub content: String,
|
pub content: String,
|
||||||
pub is_error: bool,
|
pub is_error: bool,
|
||||||
|
/// Attachments as (media type, base64). The agent sends them to the model after the results.
|
||||||
|
pub images: Vec<(String, String)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ToolResult {
|
impl ToolResult {
|
||||||
@@ -18,14 +20,20 @@ impl ToolResult {
|
|||||||
Self {
|
Self {
|
||||||
content: s.into(),
|
content: s.into(),
|
||||||
is_error: false,
|
is_error: false,
|
||||||
|
images: vec![],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub fn err(s: impl Into<String>) -> Self {
|
pub fn err(s: impl Into<String>) -> Self {
|
||||||
Self {
|
Self {
|
||||||
content: s.into(),
|
content: s.into(),
|
||||||
is_error: true,
|
is_error: true,
|
||||||
|
images: vec![],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
pub fn with_images(mut self, images: Vec<(String, String)>) -> Self {
|
||||||
|
self.images = images;
|
||||||
|
self
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Per-call context. Shared state (read-tracking, seq log) hangs off `state`.
|
/// Per-call context. Shared state (read-tracking, seq log) hangs off `state`.
|
||||||
@@ -93,6 +101,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 +281,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;
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ reqwest = { version = "0.13.5", default-features = false, features = ["rustls",
|
|||||||
rquickjs = { version = "0.14.0", features = ["futures", "macro"] }
|
rquickjs = { version = "0.14.0", features = ["futures", "macro"] }
|
||||||
serde_json = "1.0.151"
|
serde_json = "1.0.151"
|
||||||
similar = "3.2.0"
|
similar = "3.2.0"
|
||||||
tokio = { version = "1.53.1", features = ["process", "time", "io-util", "rt", "macros", "net"] }
|
tokio = { version = "1.53.1", features = ["process", "time", "io-util", "rt", "macros", "net", "sync"] }
|
||||||
|
|
||||||
[lints]
|
[lints]
|
||||||
workspace = true
|
workspace = true
|
||||||
|
|||||||
+518
-58
@@ -1,49 +1,124 @@
|
|||||||
//! `codemode`: the model writes a JavaScript async-function body that calls the other tools
|
//! `codemode`: the model writes a JavaScript async-function body that calls the other tools
|
||||||
//! inside a QuickJS sandbox; only the script's output reaches the model (pi's codemode, minus
|
//! inside a QuickJS sandbox; only the script's output reaches the model (pi's codemode, minus
|
||||||
//! `models`/`image`). Inner calls go through `Registry::call`, so the permission gate and the
|
//! `models`). Inner calls go through `Registry::call`, so the permission gate and the shared
|
||||||
//! shared `State` (read-before-edit, edit log) apply as for direct calls.
|
//! `State` (read-before-edit, edit log) apply as for direct calls. Inner calls are reported
|
||||||
//! ponytail: inner calls emit no agent events (TUI shows only the codemode call); add a bus
|
//! live through `State::nested` (the agent shows them as notices); images shown with `image()`
|
||||||
//! handle on `ToolCtx` if users want to see them live.
|
//! travel as `ToolResult::images`.
|
||||||
|
|
||||||
use super::{head_tail, spec};
|
use super::{head_tail, spec};
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
|
use base64::Engine;
|
||||||
use hx_ai::ToolSpec;
|
use hx_ai::ToolSpec;
|
||||||
use hx_core::tool::{Registry, Tool, ToolCtx, ToolResult};
|
use hx_core::tool::{Registry, Tool, ToolCtx, ToolResult};
|
||||||
use rquickjs::{AsyncContext, AsyncRuntime, Function, function::Async};
|
use rquickjs::{AsyncContext, AsyncRuntime, Function, function::Async};
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
use std::sync::Arc;
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
use std::sync::{Arc, Mutex, OnceLock};
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
|
use tokio::sync::{Notify, Semaphore};
|
||||||
|
|
||||||
const MEM: usize = 256 << 20;
|
const MEM: usize = 256 << 20;
|
||||||
/// ~10k tokens of output; the rest goes to a temp file.
|
/// ~10k tokens of output; the rest goes to a temp file.
|
||||||
const MAX_OUT: usize = 40_000;
|
const MAX_OUT: usize = 40_000;
|
||||||
const HEAD_OUT: usize = 10_000;
|
|
||||||
/// Tool listing budget in the description (~3k tokens).
|
/// Tool listing budget in the description (~3k tokens).
|
||||||
const LIST_BUDGET: usize = 12_000;
|
const LIST_BUDGET: usize = 12_000;
|
||||||
const DEFAULT_TIMEOUT_S: u64 = 300;
|
const DEFAULT_TIMEOUT_S: u64 = 300;
|
||||||
|
/// Scripts running at once in this process; others wait (see `HX_CODEMODE_MAX_WORKERS`).
|
||||||
|
const DEFAULT_WORKERS: usize = 2;
|
||||||
|
const WORKER_WAIT: Duration = Duration::from_secs(60);
|
||||||
|
|
||||||
const PRELUDE: &str = r#"
|
const PRELUDE: &str = r#"
|
||||||
globalThis.__out = []; globalThis.__con = [];
|
globalThis.__out = []; globalThis.__con = []; globalThis.__img = [];
|
||||||
|
globalThis.__sets = {}; globalThis.__dels = [];
|
||||||
const __s = (v) => typeof v === "string" ? v : JSON.stringify(v, null, 1);
|
const __s = (v) => typeof v === "string" ? v : JSON.stringify(v, null, 1);
|
||||||
globalThis.text = (v) => { __out.push(__s(v)); };
|
globalThis.text = (v) => { __out.push(__s(v)); };
|
||||||
globalThis.console = Object.fromEntries(["log","info","warn","error","debug"].map(k =>
|
globalThis.console = Object.fromEntries(["log","info","warn","error","debug"].map(k =>
|
||||||
[k, (...a) => { __con.push(a.map(__s).join(" ")); }]));
|
[k, (...a) => { __con.push(a.map(__s).join(" ")); }]));
|
||||||
class ToolError extends Error {}
|
class ToolError extends Error {}
|
||||||
globalThis.ToolError = ToolError;
|
globalThis.ToolError = ToolError;
|
||||||
globalThis.tools = new Proxy({}, { get: (_, n) => async (a) => {
|
class __Exit {}
|
||||||
const r = JSON.parse(await __call(String(n), JSON.stringify(a ?? {})));
|
globalThis.exit = () => { throw new __Exit(); };
|
||||||
if (r.error) throw new ToolError(r.content);
|
|
||||||
return r.content;
|
const __MIME = ["image/png", "image/jpeg", "image/gif", "image/webp"];
|
||||||
}});
|
globalThis.image = (v) => {
|
||||||
|
let mime, data;
|
||||||
|
if (typeof v === "string") {
|
||||||
|
const m = /^data:([^;,]+);base64,(.*)$/s.exec(v);
|
||||||
|
if (!m) throw new TypeError("image() expects a base64 data: URL or an image block { type: \"image\", data, mimeType }; remote URLs are not supported");
|
||||||
|
mime = m[1]; data = m[2];
|
||||||
|
} else if (v && typeof v === "object") {
|
||||||
|
if (typeof v.image_url === "string") return image(v.image_url);
|
||||||
|
mime = v.mimeType ?? v.media_type; data = v.data;
|
||||||
|
}
|
||||||
|
if (!__MIME.includes(mime) || typeof data !== "string")
|
||||||
|
throw new TypeError("image() accepts png, jpeg, gif and webp base64 data");
|
||||||
|
if (__img.length >= 8) throw new RangeError("at most 8 images per script");
|
||||||
|
__img.push(mime + "|" + data);
|
||||||
|
__out.push("\u0001img" + (__img.length - 1));
|
||||||
|
};
|
||||||
|
|
||||||
|
const __block = ([mimeType, data]) => ({ type: "image", data, mimeType });
|
||||||
|
const __wrap = (n) => {
|
||||||
|
const raw = async (a) => JSON.parse(await __call(n, JSON.stringify(a ?? {})));
|
||||||
|
const f = async (a) => {
|
||||||
|
const r = await raw(a);
|
||||||
|
if (r.error) throw new ToolError(r.content);
|
||||||
|
if (r.images.length) return { ...__block(r.images[0]), note: r.content, images: r.images.map(__block) };
|
||||||
|
return r.content;
|
||||||
|
};
|
||||||
|
f.json = async (a) => JSON.parse(await f(a));
|
||||||
|
f.raw = async (a) => {
|
||||||
|
const r = await raw(a);
|
||||||
|
return { content: r.content, is_error: r.error, images: r.images.map(__block) };
|
||||||
|
};
|
||||||
|
return f;
|
||||||
|
};
|
||||||
|
globalThis.tools = new Proxy({}, { get: (_, n) => typeof n === "string" ? __wrap(n) : undefined });
|
||||||
|
|
||||||
|
globalThis.ALL_TOOLS = JSON.parse(__all_json);
|
||||||
globalThis.describeTool = async (n) => __describe(String(n)) || undefined;
|
globalThis.describeTool = async (n) => __describe(String(n)) || undefined;
|
||||||
|
globalThis.searchTools = async (q, o) =>
|
||||||
|
JSON.parse(__search(String(q), Number(o?.limit ?? 8), String(o?.namespace ?? "")));
|
||||||
|
globalThis.describeNamespace = async (n) => { const r = __ns(String(n)); return r ? JSON.parse(r) : undefined; };
|
||||||
|
|
||||||
|
globalThis.__store = JSON.parse(__store_json);
|
||||||
|
const __eff = () => { const o = { ...__store, ...__sets }; for (const k of __dels) delete o[k]; return o; };
|
||||||
|
globalThis.load = (k) => { const v = __eff()[String(k)]; return v === undefined ? undefined : JSON.parse(JSON.stringify(v)); };
|
||||||
|
globalThis.store = (k, v) => {
|
||||||
|
k = String(k);
|
||||||
|
if (v === undefined) { delete __sets[k]; if (!__dels.includes(k)) __dels.push(k); return; }
|
||||||
|
const j = JSON.stringify(v);
|
||||||
|
if (j === undefined || j.length > 262144) throw new RangeError("store value must be JSON of at most 262144 characters");
|
||||||
|
const prev = __sets[k], had = k in __sets, dels = [...__dels];
|
||||||
|
__sets[k] = JSON.parse(j);
|
||||||
|
const i = __dels.indexOf(k); if (i >= 0) __dels.splice(i, 1);
|
||||||
|
if (JSON.stringify(__eff()).length > 1048576) {
|
||||||
|
if (had) __sets[k] = prev; else delete __sets[k];
|
||||||
|
__dels.length = 0; __dels.push(...dels);
|
||||||
|
throw new RangeError("store is limited to 1048576 characters of JSON in total");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
globalThis.__store_out = () => JSON.stringify({ set: __sets, del: __dels });
|
||||||
"#;
|
"#;
|
||||||
|
|
||||||
|
/// A callable tool as the discovery globals see it.
|
||||||
|
struct Doc {
|
||||||
|
/// JS identifier
|
||||||
|
id: String,
|
||||||
|
/// MCP server for `mcp__server__tool`, else empty
|
||||||
|
ns: String,
|
||||||
|
/// `tools.id({sig}): first sentence`
|
||||||
|
line: String,
|
||||||
|
/// lowercase name + description, for ranking
|
||||||
|
hay: String,
|
||||||
|
}
|
||||||
|
|
||||||
pub struct Codemode {
|
pub struct Codemode {
|
||||||
reg: Arc<Registry>,
|
reg: Arc<Registry>,
|
||||||
/// JS identifier -> real tool name
|
/// JS identifier -> real tool name
|
||||||
names: Arc<BTreeMap<String, String>>,
|
names: Arc<BTreeMap<String, String>>,
|
||||||
|
docs: Arc<Vec<Doc>>,
|
||||||
desc: String,
|
desc: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,10 +155,50 @@ fn sig(schema: &Value) -> String {
|
|||||||
format!("{{{}}}", args.join(", "))
|
format!("{{{}}}", args.join(", "))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// MCP server of `mcp__server__tool`.
|
||||||
|
fn namespace(name: &str) -> String {
|
||||||
|
name.strip_prefix("mcp__")
|
||||||
|
.and_then(|r| r.split("__").next())
|
||||||
|
.map(ident)
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tools matching `query`, best first: name hits weigh more than description hits.
|
||||||
|
fn search(docs: &[Doc], query: &str, limit: usize, ns: &str) -> Value {
|
||||||
|
let terms: Vec<String> = query
|
||||||
|
.to_lowercase()
|
||||||
|
.split(|c: char| !c.is_alphanumeric())
|
||||||
|
.filter(|t| !t.is_empty())
|
||||||
|
.map(String::from)
|
||||||
|
.collect();
|
||||||
|
let ns = ident(ns);
|
||||||
|
let mut hits: Vec<(usize, &Doc)> = docs
|
||||||
|
.iter()
|
||||||
|
.filter(|d| ns.is_empty() || d.ns == ns)
|
||||||
|
.filter_map(|d| {
|
||||||
|
let id = d.id.to_lowercase();
|
||||||
|
let score: usize = terms
|
||||||
|
.iter()
|
||||||
|
.map(|t| {
|
||||||
|
let in_id = id.split('_').any(|p| p == t) as usize * 2 + id.contains(t) as usize * 2;
|
||||||
|
in_id + d.hay.contains(t.as_str()) as usize
|
||||||
|
})
|
||||||
|
.sum();
|
||||||
|
(score > 0).then_some((score, d))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
hits.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.id.cmp(&b.1.id)));
|
||||||
|
hits.into_iter()
|
||||||
|
.take(limit.max(1))
|
||||||
|
.map(|(_, d)| json!({"name": d.id, "description": d.line}))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
impl Codemode {
|
impl Codemode {
|
||||||
/// Snapshot of `reg` at construction: tools added later (and codemode itself) are not callable.
|
/// Snapshot of `reg` at construction: tools added later (and codemode itself) are not callable.
|
||||||
pub fn new(reg: &Registry) -> Self {
|
pub fn new(reg: &Registry) -> Self {
|
||||||
let mut names = BTreeMap::new();
|
let mut names = BTreeMap::new();
|
||||||
|
let mut docs = vec![];
|
||||||
let mut list = String::new();
|
let mut list = String::new();
|
||||||
let mut hidden = 0;
|
let mut hidden = 0;
|
||||||
// MCP tools first so builtins cannot push them out of the listing budget
|
// MCP tools first so builtins cannot push them out of the listing budget
|
||||||
@@ -92,32 +207,63 @@ impl Codemode {
|
|||||||
for s in specs {
|
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}", sig(&s.input_schema));
|
||||||
if list.len() + line.len() <= LIST_BUDGET {
|
if list.len() + line.len() < LIST_BUDGET {
|
||||||
list.push_str(&line);
|
list.push_str(&format!("- {line}\n"));
|
||||||
} else {
|
} else {
|
||||||
hidden += 1;
|
hidden += 1;
|
||||||
}
|
}
|
||||||
|
docs.push(Doc {
|
||||||
|
ns: namespace(&s.name),
|
||||||
|
hay: format!("{id} {}", s.description).to_lowercase(),
|
||||||
|
line,
|
||||||
|
id: id.clone(),
|
||||||
|
});
|
||||||
names.insert(id, s.name);
|
names.insert(id, s.name);
|
||||||
}
|
}
|
||||||
if hidden > 0 {
|
if hidden > 0 {
|
||||||
list.push_str(&format!(
|
list.push_str(&format!(
|
||||||
"- ... {hidden} more; `await describeTool(name)` gives the schema\n"
|
"- ... {hidden} more; find them with `await searchTools(query)` or `ALL_TOOLS`, `await describeTool(name)` gives the schema\n"
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
let desc = format!(
|
let desc = format!(
|
||||||
"Run a JavaScript script that calls other tools; only its output reaches you. Use it to run many tool calls in parallel (Promise.all) or to filter large results before you see them. Input is raw JS (not JSON, no code fence), run as the body of an async function: top-level await and return work. QuickJS sandbox: no Node APIs, fs, network or timers.\n\
|
"Run a JavaScript script that calls other tools; only its output reaches you. Use it to run many tool calls in parallel (Promise.all) or to filter large results before you see them. Input is raw JS (not JSON, no code fence), run as the body of an async function: top-level await and return work. QuickJS sandbox: no Node APIs, fs, network or timers.\n\
|
||||||
Globals: `await tools.<name>(args)` resolves to the tool's text output and throws ToolError (message = output) when the tool fails (e.g. non-zero bash exit, rg without matches); `text(v)` adds output (non-strings as JSON); `return v` adds v; `console.log(...)` lines follow in <console_output>; `await describeTool(name)` returns the input schema. Permission prompts still apply. Output over ~10k tokens is cut, full text saved to a file.\n\
|
Globals: `await tools.<name>(args)` resolves to the tool's text output and throws ToolError (message = output) when the tool fails (e.g. non-zero bash exit, rg without matches); `await tools.<name>.json(args)` parses that output as JSON; `await tools.<name>.raw(args)` never throws and resolves to {{content, is_error, images}}. A tool that returns an image (read on a png/jpg/gif/webp) resolves to an image block {{type:\"image\", data, mimeType, note}}; show it with `image(block)` (a base64 data: URL also works; max 8 images, each is saved to a temp file). `text(v)` adds output (non-strings as JSON); `return v` adds v; `exit()` ends the script successfully; `console.log(...)` lines follow in <console_output>; `store(key, json)` / `load(key)` keep small JSON values across codemode calls (kept only if the script succeeds); `ALL_TOOLS` is every callable tool as {{name, description}}; `await searchTools(query, {{limit?, namespace?}})` ranks them; `await describeTool(name)` returns the input schema; `await describeNamespace(server)` lists an MCP server's tools. Tool calls are real and not undone when the script fails; calls still running when it ends are cancelled. Permission prompts still apply. Output over ~10k tokens (`max_output_tokens`) is cut, full text saved to a file.\n\
|
||||||
Tools:\n{list}"
|
Tools:\n{list}"
|
||||||
);
|
);
|
||||||
Self {
|
Self {
|
||||||
reg: Arc::new(reg.clone()),
|
reg: Arc::new(reg.clone()),
|
||||||
names: Arc::new(names),
|
names: Arc::new(names),
|
||||||
|
docs: Arc::new(docs),
|
||||||
desc,
|
desc,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn workers() -> &'static Semaphore {
|
||||||
|
static W: OnceLock<Semaphore> = OnceLock::new();
|
||||||
|
W.get_or_init(|| {
|
||||||
|
let n = std::env::var("HX_CODEMODE_MAX_WORKERS")
|
||||||
|
.ok()
|
||||||
|
.and_then(|v| v.parse::<usize>().ok())
|
||||||
|
.filter(|n| *n > 0)
|
||||||
|
.unwrap_or(DEFAULT_WORKERS);
|
||||||
|
Semaphore::new(n)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Everything one script run needs.
|
||||||
|
struct Job {
|
||||||
|
script: String,
|
||||||
|
secs: u64,
|
||||||
|
max_out: usize,
|
||||||
|
reg: Arc<Registry>,
|
||||||
|
names: Arc<BTreeMap<String, String>>,
|
||||||
|
docs: Arc<Vec<Doc>>,
|
||||||
|
cx: ToolCtx,
|
||||||
|
stop: Arc<AtomicBool>,
|
||||||
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl Tool for Codemode {
|
impl Tool for Codemode {
|
||||||
fn spec(&self) -> ToolSpec {
|
fn spec(&self) -> ToolSpec {
|
||||||
@@ -126,17 +272,36 @@ impl Tool for Codemode {
|
|||||||
&self.desc,
|
&self.desc,
|
||||||
json!({"type":"object","properties":{
|
json!({"type":"object","properties":{
|
||||||
"script":{"type":"string","description":"JavaScript async function body"},
|
"script":{"type":"string","description":"JavaScript async function body"},
|
||||||
"timeout":{"type":"integer","description":"seconds, default 300"}},
|
"timeout":{"type":"integer","description":"seconds, default 300"},
|
||||||
|
"max_output_tokens":{"type":"integer","description":"output limit, default 10000"}},
|
||||||
"required":["script"]}),
|
"required":["script"]}),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
|
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
|
||||||
let script = a["script"].as_str().unwrap_or_default().to_string();
|
|
||||||
let secs = a["timeout"]
|
let secs = a["timeout"]
|
||||||
.as_u64()
|
.as_u64()
|
||||||
.unwrap_or(DEFAULT_TIMEOUT_S)
|
.unwrap_or(DEFAULT_TIMEOUT_S)
|
||||||
.clamp(1, 3600);
|
.clamp(1, 3600);
|
||||||
|
let max_out = a["max_output_tokens"]
|
||||||
|
.as_u64()
|
||||||
|
.map_or(MAX_OUT, |t| (t as usize).saturating_mul(4).clamp(400, 400_000));
|
||||||
|
// The wait for a free worker counts toward the timeout.
|
||||||
|
let t0 = Instant::now();
|
||||||
|
let permit = match tokio::time::timeout(
|
||||||
|
WORKER_WAIT.min(Duration::from_secs(secs)),
|
||||||
|
workers().acquire(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(Ok(p)) => p,
|
||||||
|
_ => {
|
||||||
|
return ToolResult::err(
|
||||||
|
"Script failed\n\nScript error: no codemode worker became free in time; other scripts are still running. Retry after they finish.\n\nThe script did not start.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let secs = secs.saturating_sub(t0.elapsed().as_secs()).max(1);
|
||||||
// Dropping this future (agent abort) interrupts the script.
|
// Dropping this future (agent abort) interrupts the script.
|
||||||
struct Stop(Arc<AtomicBool>);
|
struct Stop(Arc<AtomicBool>);
|
||||||
impl Drop for Stop {
|
impl Drop for Stop {
|
||||||
@@ -146,21 +311,26 @@ impl Tool for Codemode {
|
|||||||
}
|
}
|
||||||
let stop = Stop(Arc::default());
|
let stop = Stop(Arc::default());
|
||||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||||
let (reg, names, cx, flag) = (
|
let job = Job {
|
||||||
self.reg.clone(),
|
script: a["script"].as_str().unwrap_or_default().to_string(),
|
||||||
self.names.clone(),
|
secs,
|
||||||
cx.clone(),
|
max_out,
|
||||||
stop.0.clone(),
|
reg: self.reg.clone(),
|
||||||
);
|
names: self.names.clone(),
|
||||||
|
docs: self.docs.clone(),
|
||||||
|
cx: cx.clone(),
|
||||||
|
stop: stop.0.clone(),
|
||||||
|
};
|
||||||
// QuickJS values are !Send: run the script on its own thread with a local runtime.
|
// QuickJS values are !Send: run the script on its own thread with a local runtime.
|
||||||
std::thread::spawn(move || {
|
std::thread::spawn(move || {
|
||||||
let rt = tokio::runtime::Builder::new_current_thread()
|
let rt = tokio::runtime::Builder::new_current_thread()
|
||||||
.enable_all()
|
.enable_all()
|
||||||
.build();
|
.build();
|
||||||
let r = match rt {
|
let r = match rt {
|
||||||
Ok(rt) => rt.block_on(run(script, secs, reg, names, cx, flag)),
|
Ok(rt) => rt.block_on(run(job)),
|
||||||
Err(e) => ToolResult::err(format!("runtime: {e}")),
|
Err(e) => ToolResult::err(format!("runtime: {e}")),
|
||||||
};
|
};
|
||||||
|
drop(permit);
|
||||||
let _ = tx.send(r);
|
let _ = tx.send(r);
|
||||||
});
|
});
|
||||||
rx.await
|
rx.await
|
||||||
@@ -168,19 +338,46 @@ impl Tool for Codemode {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// (settled ok?/error, text items, console lines)
|
/// (settled ok?/error, store writes as JSON, text items, console lines, images)
|
||||||
type Outcome = (Option<(bool, String)>, Vec<String>, Vec<String>);
|
type Outcome = (
|
||||||
|
Option<(bool, String, Option<String>)>,
|
||||||
|
Vec<String>,
|
||||||
|
Vec<String>,
|
||||||
|
Vec<String>, // `mime|base64`
|
||||||
|
);
|
||||||
|
|
||||||
async fn run(
|
fn preview(s: &str) -> String {
|
||||||
script: String,
|
let one: String = s.chars().take(80).collect();
|
||||||
secs: u64,
|
if s.chars().count() > 80 {
|
||||||
reg: Arc<Registry>,
|
format!("{one}…")
|
||||||
names: Arc<BTreeMap<String, String>>,
|
} else {
|
||||||
cx: ToolCtx,
|
one
|
||||||
stop: Arc<AtomicBool>,
|
}
|
||||||
) -> ToolResult {
|
}
|
||||||
|
|
||||||
|
fn ext(mime: &str) -> &'static str {
|
||||||
|
match mime {
|
||||||
|
"image/jpeg" => "jpg",
|
||||||
|
"image/gif" => "gif",
|
||||||
|
"image/webp" => "webp",
|
||||||
|
_ => "png",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run(job: Job) -> ToolResult {
|
||||||
|
let Job {
|
||||||
|
script,
|
||||||
|
secs,
|
||||||
|
max_out,
|
||||||
|
reg,
|
||||||
|
names,
|
||||||
|
docs,
|
||||||
|
cx,
|
||||||
|
stop,
|
||||||
|
} = job;
|
||||||
let t0 = Instant::now();
|
let t0 = Instant::now();
|
||||||
let ncalls = Arc::new(AtomicUsize::new(0));
|
// (tool, "running" | "ok" | "error" | "cancelled") in call order
|
||||||
|
let log: Arc<Mutex<Vec<(String, &'static str)>>> = Arc::default();
|
||||||
let fail = |e: String| ToolResult::err(format!("Script failed\n\nScript error: {e}"));
|
let fail = |e: String| ToolResult::err(format!("Script failed\n\nScript error: {e}"));
|
||||||
let rt = match AsyncRuntime::new() {
|
let rt = match AsyncRuntime::new() {
|
||||||
Ok(r) => r,
|
Ok(r) => r,
|
||||||
@@ -204,32 +401,72 @@ async fn run(
|
|||||||
};
|
};
|
||||||
let wrapped = format!(
|
let wrapped = format!(
|
||||||
"{PRELUDE}\nglobalThis.__done = undefined;\n(async () => {{\n{script}\n}})().then(\
|
"{PRELUDE}\nglobalThis.__done = undefined;\n(async () => {{\n{script}\n}})().then(\
|
||||||
(v) => {{ if (v !== undefined) __out.push(__s(v)); globalThis.__done = {{ ok: true }}; }},\
|
(v) => {{ if (v !== undefined) __out.push(__s(v)); globalThis.__done = {{ ok: true, store: __store_out() }}; __finish(); }},\
|
||||||
(e) => {{ globalThis.__done = {{ ok: false, err: e instanceof Error ? `${{e.name}}: ${{e.message}}` : __s(e) }}; }});"
|
(e) => {{ globalThis.__done = e instanceof __Exit ? {{ ok: true, store: __store_out() }} : {{ ok: false, err: e instanceof Error ? `${{e.name}}: ${{e.message}}` : __s(e) }}; __finish(); }});"
|
||||||
);
|
);
|
||||||
|
let finished = Arc::new(Notify::new());
|
||||||
|
let nested = cx
|
||||||
|
.state
|
||||||
|
.nested
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|e| e.into_inner())
|
||||||
|
.clone();
|
||||||
|
let all: Vec<Value> = docs
|
||||||
|
.iter()
|
||||||
|
.map(|d| json!({"name": d.id, "description": d.line}))
|
||||||
|
.collect();
|
||||||
|
let store_json = serde_json::to_string(
|
||||||
|
&*cx.state
|
||||||
|
.codemode_store
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|e| e.into_inner()),
|
||||||
|
)
|
||||||
|
.unwrap_or_else(|_| "{}".into());
|
||||||
let started = ctx
|
let started = ctx
|
||||||
.with(|ctx| {
|
.with(|ctx| {
|
||||||
let g = ctx.globals();
|
let g = ctx.globals();
|
||||||
let (r2, n2, c2, k2) = (reg.clone(), names.clone(), cx.clone(), ncalls.clone());
|
let (r2, n2, c2, l2) = (reg.clone(), names.clone(), cx.clone(), log.clone());
|
||||||
let call = Function::new(
|
let call = Function::new(
|
||||||
ctx.clone(),
|
ctx.clone(),
|
||||||
Async(move |name: String, args: String| {
|
Async(move |name: String, args: String| {
|
||||||
let (reg, names, cx) = (r2.clone(), n2.clone(), c2.clone());
|
let (reg, names, cx, log, nested) =
|
||||||
k2.fetch_add(1, Ordering::Relaxed);
|
(r2.clone(), n2.clone(), c2.clone(), l2.clone(), nested.clone());
|
||||||
async move {
|
async move {
|
||||||
let real = names.get(&name).cloned().unwrap_or(name);
|
let real = names.get(&name).cloned().unwrap_or(name);
|
||||||
|
let idx = {
|
||||||
|
let mut l = log.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
l.push((real.clone(), "running"));
|
||||||
|
l.len() - 1
|
||||||
|
};
|
||||||
|
let note = |s: String| {
|
||||||
|
if let Some(tx) = &nested {
|
||||||
|
let _ = tx.send(s);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
note(format!(" ↳ {real} {}", preview(&args)));
|
||||||
|
let t = Instant::now();
|
||||||
let r = match serde_json::from_str::<Value>(&args) {
|
let r = match serde_json::from_str::<Value>(&args) {
|
||||||
Ok(a) => reg.call(&real, a, &cx).await,
|
Ok(a) => reg.call(&real, a, &cx).await,
|
||||||
Err(e) => ToolResult::err(format!("bad arguments: {e}")),
|
Err(e) => ToolResult::err(format!("bad arguments: {e}")),
|
||||||
};
|
};
|
||||||
json!({"content": r.content, "error": r.is_error}).to_string()
|
log.lock().unwrap_or_else(|e| e.into_inner())[idx].1 =
|
||||||
|
if r.is_error { "error" } else { "ok" };
|
||||||
|
note(format!(
|
||||||
|
" ↳ {real} {} {}ms",
|
||||||
|
if r.is_error { "failed" } else { "ok" },
|
||||||
|
t.elapsed().as_millis()
|
||||||
|
));
|
||||||
|
json!({"content": r.content, "error": r.is_error, "images": r.images})
|
||||||
|
.to_string()
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
).map_err(|e| e.to_string())?;
|
)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
g.set("__call", call).map_err(|e| e.to_string())?;
|
g.set("__call", call).map_err(|e| e.to_string())?;
|
||||||
|
let (r3, n3, d3, d4) = (reg.clone(), names.clone(), docs.clone(), docs.clone());
|
||||||
let describe = Function::new(ctx.clone(), move |name: String| -> String {
|
let describe = Function::new(ctx.clone(), move |name: String| -> String {
|
||||||
let real = names.get(&name).cloned().unwrap_or(name);
|
let real = n3.get(&name).cloned().unwrap_or(name);
|
||||||
reg.get(&real)
|
r3.get(&real)
|
||||||
.map(|t| {
|
.map(|t| {
|
||||||
let s = t.spec();
|
let s = t.spec();
|
||||||
json!({"name": s.name, "description": s.description, "input_schema": s.input_schema}).to_string()
|
json!({"name": s.name, "description": s.description, "input_schema": s.input_schema}).to_string()
|
||||||
@@ -237,6 +474,37 @@ async fn run(
|
|||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
}).map_err(|e| e.to_string())?;
|
}).map_err(|e| e.to_string())?;
|
||||||
g.set("__describe", describe).map_err(|e| e.to_string())?;
|
g.set("__describe", describe).map_err(|e| e.to_string())?;
|
||||||
|
let find = Function::new(
|
||||||
|
ctx.clone(),
|
||||||
|
move |q: String, limit: f64, ns: String| -> String {
|
||||||
|
let limit = if limit.is_finite() && limit >= 1.0 { limit as usize } else { 8 };
|
||||||
|
search(&d3, &q, limit, &ns).to_string()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
g.set("__search", find).map_err(|e| e.to_string())?;
|
||||||
|
let ns_fn = Function::new(ctx.clone(), move |name: String| -> String {
|
||||||
|
let want = ident(&name);
|
||||||
|
let tools: Vec<&str> = d4
|
||||||
|
.iter()
|
||||||
|
.filter(|d| d.ns == want)
|
||||||
|
.map(|d| d.id.as_str())
|
||||||
|
.collect();
|
||||||
|
if tools.is_empty() {
|
||||||
|
String::new()
|
||||||
|
} else {
|
||||||
|
json!({"name": want, "tools": tools}).to_string()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
g.set("__ns", ns_fn).map_err(|e| e.to_string())?;
|
||||||
|
let f2 = finished.clone();
|
||||||
|
let fin = Function::new(ctx.clone(), move || f2.notify_one())
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
g.set("__finish", fin).map_err(|e| e.to_string())?;
|
||||||
|
g.set("__all_json", serde_json::to_string(&all).unwrap_or_default())
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
g.set("__store_json", store_json).map_err(|e| e.to_string())?;
|
||||||
ctx.eval::<(), _>(wrapped.as_str()).map_err(|e| {
|
ctx.eval::<(), _>(wrapped.as_str()).map_err(|e| {
|
||||||
let ex = ctx.catch();
|
let ex = ctx.catch();
|
||||||
ex.as_exception()
|
ex.as_exception()
|
||||||
@@ -258,7 +526,9 @@ async fn run(
|
|||||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
// Stop as soon as the script settles: unawaited tool calls are dropped (cancelled), not waited for.
|
||||||
tokio::select! {
|
tokio::select! {
|
||||||
|
_ = finished.notified() => {}
|
||||||
_ = rt.idle() => {}
|
_ = rt.idle() => {}
|
||||||
_ = watch => timed_out.store(Instant::now() >= deadline, Ordering::Relaxed),
|
_ = watch => timed_out.store(Instant::now() >= deadline, Ordering::Relaxed),
|
||||||
}
|
}
|
||||||
@@ -270,17 +540,58 @@ async fn run(
|
|||||||
Some(d) => Some((
|
Some(d) => Some((
|
||||||
d.get::<_, bool>("ok")?,
|
d.get::<_, bool>("ok")?,
|
||||||
d.get::<_, Option<String>>("err")?.unwrap_or_default(),
|
d.get::<_, Option<String>>("err")?.unwrap_or_default(),
|
||||||
|
d.get::<_, Option<String>>("store")?,
|
||||||
)),
|
)),
|
||||||
None => None,
|
None => None,
|
||||||
};
|
};
|
||||||
Ok((done, g.get("__out")?, g.get("__con")?))
|
Ok((done, g.get("__out")?, g.get("__con")?, g.get("__img")?))
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
let ms = t0.elapsed().as_millis();
|
let ms = t0.elapsed().as_millis();
|
||||||
let (done, out, con) = match res {
|
let (done, out, con, imgs) = match res {
|
||||||
Ok(x) => x,
|
Ok(x) => x,
|
||||||
Err(e) => return fail(e.to_string()),
|
Err(e) => return fail(e.to_string()),
|
||||||
};
|
};
|
||||||
|
// Calls still running were cut off by the end of the script, a timeout or an abort.
|
||||||
|
let calls = {
|
||||||
|
let mut l = log.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
for c in l.iter_mut().filter(|c| c.1 == "running") {
|
||||||
|
c.1 = "cancelled";
|
||||||
|
}
|
||||||
|
l.clone()
|
||||||
|
};
|
||||||
|
// Save images next to the output so the model has their paths; `image()` left markers.
|
||||||
|
let mut sent = vec![];
|
||||||
|
let mut labels: Vec<String> = vec![];
|
||||||
|
for (i, (mime, data)) in imgs
|
||||||
|
.iter()
|
||||||
|
.filter_map(|s| s.split_once('|'))
|
||||||
|
.enumerate()
|
||||||
|
{
|
||||||
|
labels.push(match base64::engine::general_purpose::STANDARD.decode(data) {
|
||||||
|
Ok(bytes) => {
|
||||||
|
let f = std::env::temp_dir().join(format!(
|
||||||
|
"hx-codemode-{}-{}-{i}.{}",
|
||||||
|
std::process::id(),
|
||||||
|
t0.elapsed().as_nanos(),
|
||||||
|
ext(mime)
|
||||||
|
));
|
||||||
|
sent.push((mime.to_string(), data.to_string()));
|
||||||
|
match std::fs::write(&f, &bytes) {
|
||||||
|
Ok(()) => format!("[Image saved to {} ({mime}, {} bytes)]", f.display(), bytes.len()),
|
||||||
|
Err(e) => format!("[Image ({mime}, {} bytes) could not be saved: {e}]", bytes.len()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => format!("[Image {i} is not valid base64: {e}]"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let out: Vec<String> = out
|
||||||
|
.into_iter()
|
||||||
|
.map(|t| match t.strip_prefix("\u{1}img").and_then(|i| i.parse::<usize>().ok()) {
|
||||||
|
Some(i) => labels.get(i).cloned().unwrap_or_default(),
|
||||||
|
None => t,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
let mut body = String::new();
|
let mut body = String::new();
|
||||||
let n = out.len();
|
let n = out.len();
|
||||||
for (i, t) in out.iter().enumerate() {
|
for (i, t) in out.iter().enumerate() {
|
||||||
@@ -296,16 +607,33 @@ async fn run(
|
|||||||
con.join("\n")
|
con.join("\n")
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
let err = match done {
|
let err = match &done {
|
||||||
Some((true, _)) => None,
|
Some((true, ..)) => None,
|
||||||
Some((false, e)) => Some(e),
|
Some((false, e, _)) => Some(e.clone()),
|
||||||
None if timed_out.load(Ordering::Relaxed) => Some(format!("timed out after {secs}s")),
|
None if timed_out.load(Ordering::Relaxed) => Some(format!("timed out after {secs}s")),
|
||||||
None => Some(
|
None => Some(
|
||||||
"script never finished (awaited a promise that cannot settle, or was interrupted)"
|
"script never finished (awaited a promise that cannot settle, or was interrupted)"
|
||||||
.into(),
|
.into(),
|
||||||
),
|
),
|
||||||
};
|
};
|
||||||
let (mut body, cut) = head_tail(&body, MAX_OUT, HEAD_OUT);
|
// Store writes count only for a script that succeeded.
|
||||||
|
if err.is_none()
|
||||||
|
&& let Some((_, _, Some(w))) = &done
|
||||||
|
&& let Ok(w) = serde_json::from_str::<Value>(w)
|
||||||
|
{
|
||||||
|
let mut s = cx
|
||||||
|
.state
|
||||||
|
.codemode_store
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|e| e.into_inner());
|
||||||
|
for k in w["del"].as_array().into_iter().flatten().filter_map(Value::as_str) {
|
||||||
|
s.remove(k);
|
||||||
|
}
|
||||||
|
for (k, v) in w["set"].as_object().into_iter().flatten() {
|
||||||
|
s.insert(k.clone(), v.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let (mut body, cut) = head_tail(&body, max_out, max_out / 4);
|
||||||
if cut > 0 {
|
if cut > 0 {
|
||||||
let f = std::env::temp_dir().join(format!(
|
let f = std::env::temp_dir().join(format!(
|
||||||
"hx-codemode-{}-{}.txt",
|
"hx-codemode-{}-{}.txt",
|
||||||
@@ -319,14 +647,30 @@ async fn run(
|
|||||||
f.display()
|
f.display()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
let n_calls = ncalls.load(Ordering::Relaxed);
|
let n_calls = calls.len();
|
||||||
match err {
|
match err {
|
||||||
None => ToolResult::ok(format!(
|
None => ToolResult::ok(format!(
|
||||||
"Script completed in {ms}ms, {n_calls} tool calls\n\n{body}"
|
"Script completed in {ms}ms, {n_calls} tool calls\n\n{body}"
|
||||||
)),
|
))
|
||||||
Some(e) => ToolResult::err(format!(
|
.with_images(sent),
|
||||||
"Script failed after {ms}ms, {n_calls} tool calls\n\n{body}Script error: {e}"
|
Some(e) => {
|
||||||
)),
|
let ran = if calls.is_empty() {
|
||||||
|
"No tool calls were made.".to_string()
|
||||||
|
} else {
|
||||||
|
format!(
|
||||||
|
"Tool calls made before the failure (they are not undone): {}",
|
||||||
|
calls
|
||||||
|
.iter()
|
||||||
|
.map(|(n, s)| format!("{n} ({s})"))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(", ")
|
||||||
|
)
|
||||||
|
};
|
||||||
|
ToolResult::err(format!(
|
||||||
|
"Script failed after {ms}ms, {n_calls} tool calls\n\n{body}Script error: {e}\n\n{ran}"
|
||||||
|
))
|
||||||
|
.with_images(sent)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -393,6 +737,8 @@ mod tests {
|
|||||||
"{}",
|
"{}",
|
||||||
r.content
|
r.content
|
||||||
);
|
);
|
||||||
|
// what ran before the failure is listed
|
||||||
|
assert!(r.content.contains("bash (error)"), "{}", r.content);
|
||||||
let r = go("await tools.nope({});").await;
|
let r = go("await tools.nope({});").await;
|
||||||
assert!(r.content.contains("unknown tool `nope`"), "{}", r.content);
|
assert!(r.content.contains("unknown tool `nope`"), "{}", r.content);
|
||||||
let r = go("this is not js").await;
|
let r = go("this is not js").await;
|
||||||
@@ -413,6 +759,119 @@ mod tests {
|
|||||||
assert!(r.content.contains("timed out after 5s"), "{}", r.content);
|
assert!(r.content.contains("timed out after 5s"), "{}", r.content);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn unawaited_calls_are_cancelled_when_the_script_ends() {
|
||||||
|
let t = Instant::now();
|
||||||
|
let r = go("tools.bash({command: 'sleep 20'}); return 1;").await;
|
||||||
|
assert!(!r.is_error, "{}", r.content);
|
||||||
|
assert!(t.elapsed() < Duration::from_secs(4), "waited for the call");
|
||||||
|
let r = go("tools.bash({command: 'sleep 20'}); throw new Error('x');").await;
|
||||||
|
assert!(r.content.contains("bash (cancelled)"), "{}", r.content);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn exit_json_raw_and_output_limit() {
|
||||||
|
let r = go(r#"
|
||||||
|
const j = await tools.bash.json({command: "echo '{\"a\": 5}'"});
|
||||||
|
const raw = await tools.bash.raw({command: "exit 3"});
|
||||||
|
text([j.a, raw.is_error]);
|
||||||
|
exit();
|
||||||
|
text("not reached");
|
||||||
|
"#)
|
||||||
|
.await;
|
||||||
|
assert!(!r.is_error, "{}", r.content);
|
||||||
|
assert!(r.content.contains("[\n 5,\n true\n]"), "{}", r.content);
|
||||||
|
assert!(!r.content.contains("not reached"), "{}", r.content);
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
let cm = Codemode::new(&crate::registry());
|
||||||
|
let r = cm
|
||||||
|
.call(
|
||||||
|
json!({"script": "text('x'.repeat(5000))", "max_output_tokens": 100}),
|
||||||
|
&cx(d.path()),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert!(r.content.contains("truncated"), "{}", r.content);
|
||||||
|
assert!(r.content.len() < 1000, "{}", r.content.len());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn discovery_globals() {
|
||||||
|
let r = go(r#"
|
||||||
|
const hits = await searchTools("edit a file", {limit: 2});
|
||||||
|
const none = await describeNamespace("nope");
|
||||||
|
text([ALL_TOOLS.some(t => t.name === "bash"), hits[0].name, none === undefined]);
|
||||||
|
"#)
|
||||||
|
.await;
|
||||||
|
assert!(!r.is_error, "{}", r.content);
|
||||||
|
assert!(r.content.contains("true,\n \"edit\",\n true"), "{}", r.content);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn store_persists_only_after_success() {
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
let c = cx(d.path());
|
||||||
|
let cm = Codemode::new(&crate::registry());
|
||||||
|
let run = |s: &'static str| cm.call(json!({"script": s, "timeout": 5}), &c);
|
||||||
|
assert!(!run("store('n', 1); store('o', {a: [1]});").await.is_error);
|
||||||
|
assert!(run("store('n', 2); throw new Error('x');").await.is_error);
|
||||||
|
let r = run("text([load('n'), load('o').a[0], load('missing') === undefined]); store('o', undefined);").await;
|
||||||
|
assert!(r.content.contains("1,\n 1,\n true"), "{}", r.content);
|
||||||
|
let r = run("text(load('o') === undefined)").await;
|
||||||
|
assert!(r.content.contains("true"), "{}", r.content);
|
||||||
|
let r = run("store('big', 'x'.repeat(300000))").await;
|
||||||
|
assert!(r.content.contains("262144"), "{}", r.content);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn images_flow_from_read_to_the_result() {
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
// 1x1 transparent png
|
||||||
|
let png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGNgYGBgAAAABQABh6FO1AAAAABJRU5ErkJggg==";
|
||||||
|
use base64::Engine;
|
||||||
|
std::fs::write(
|
||||||
|
d.path().join("p.png"),
|
||||||
|
base64::engine::general_purpose::STANDARD.decode(png).unwrap(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let cm = Codemode::new(&crate::registry());
|
||||||
|
let r = cm
|
||||||
|
.call(
|
||||||
|
json!({"script": r#"
|
||||||
|
const im = await tools.read({path: "p.png"});
|
||||||
|
text(im.type + " " + im.mimeType);
|
||||||
|
image(im);
|
||||||
|
image("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGNgYGBgAAAABQABh6FO1AAAAABJRU5ErkJggg==");
|
||||||
|
try { image("https://x/y.png"); } catch (e) { text(e.name); }
|
||||||
|
"#, "timeout": 5}),
|
||||||
|
&cx(d.path()),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert!(!r.is_error, "{}", r.content);
|
||||||
|
assert!(r.content.contains("image image/png"), "{}", r.content);
|
||||||
|
assert!(r.content.contains("[Image saved to"), "{}", r.content);
|
||||||
|
assert!(r.content.contains("TypeError"), "{}", r.content);
|
||||||
|
assert_eq!(r.images.len(), 2);
|
||||||
|
assert_eq!(r.images[0].0, "image/png");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn inner_calls_are_reported() {
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
let c = cx(d.path());
|
||||||
|
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
|
||||||
|
*c.state.nested.lock().unwrap() = Some(tx);
|
||||||
|
let cm = Codemode::new(&crate::registry());
|
||||||
|
cm.call(
|
||||||
|
json!({"script": "await tools.bash({command: 'echo hi'})", "timeout": 5}),
|
||||||
|
&c,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let a = rx.recv().await.unwrap();
|
||||||
|
let b = rx.recv().await.unwrap();
|
||||||
|
assert!(a.contains("bash") && a.contains("echo hi"), "{a}");
|
||||||
|
assert!(b.contains("bash ok"), "{b}");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn description_lists_tools_with_signatures() {
|
fn description_lists_tools_with_signatures() {
|
||||||
let d = Codemode::new(&crate::registry()).spec().description;
|
let d = Codemode::new(&crate::registry()).spec().description;
|
||||||
@@ -424,5 +883,6 @@ mod tests {
|
|||||||
assert!(crate::registry().get("skill").is_some());
|
assert!(crate::registry().get("skill").is_some());
|
||||||
assert!(hx_core::subagent::EXPLORE_TOOLS.contains(&"skill"));
|
assert!(hx_core::subagent::EXPLORE_TOOLS.contains(&"skill"));
|
||||||
assert_eq!(ident("mcp__dev-radius__search"), "mcp__dev_radius__search");
|
assert_eq!(ident("mcp__dev-radius__search"), "mcp__dev_radius__search");
|
||||||
|
assert_eq!(namespace("mcp__dev-radius__search"), "dev_radius");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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);
|
||||||
@@ -108,12 +109,12 @@ impl Tool for Read {
|
|||||||
"webp" => Some("image/webp"),
|
"webp" => Some("image/webp"),
|
||||||
_ => None,
|
_ => None,
|
||||||
} {
|
} {
|
||||||
// ponytail: image returned as data URL text; switch ToolResult to blocks when the TUI renders images.
|
|
||||||
use base64::Engine;
|
use base64::Engine;
|
||||||
return ToolResult::ok(format!(
|
return ToolResult::ok(format!("{} ({mt}, {} bytes)", p.display(), bytes.len()))
|
||||||
"data:{mt};base64,{}",
|
.with_images(vec![(
|
||||||
base64::engine::general_purpose::STANDARD.encode(&bytes)
|
mt.into(),
|
||||||
));
|
base64::engine::general_purpose::STANDARD.encode(&bytes),
|
||||||
|
)]);
|
||||||
}
|
}
|
||||||
if bytes.iter().take(8000).any(|&b| b == 0) {
|
if bytes.iter().take(8000).any(|&b| b == 0) {
|
||||||
return ToolResult::err(format!(
|
return ToolResult::err(format!(
|
||||||
@@ -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;
|
||||||
|
|
||||||
|
|||||||
@@ -12,7 +12,8 @@ futures = "0.3.34"
|
|||||||
hx-ai = { version = "0.1.0", path = "../hx-ai" }
|
hx-ai = { version = "0.1.0", path = "../hx-ai" }
|
||||||
hx-core = { version = "0.1.0", path = "../hx-core" }
|
hx-core = { version = "0.1.0", path = "../hx-core" }
|
||||||
ignore = "0.4.33"
|
ignore = "0.4.33"
|
||||||
ratatui = { version = "0.30.2", features = ["unstable-rendered-line-info"] }
|
pulldown-cmark = { version = "0.13", default-features = false }
|
||||||
|
ratatui ={ version = "0.30.2", features = ["unstable-rendered-line-info"] }
|
||||||
serde_json = "1.0.151"
|
serde_json = "1.0.151"
|
||||||
similar = { version = "3.2.0", features = ["inline"] }
|
similar = { version = "3.2.0", features = ["inline"] }
|
||||||
tokio = { version = "1.53.1", features = ["rt", "macros", "sync", "time", "rt-multi-thread"] }
|
tokio = { version = "1.53.1", features = ["rt", "macros", "sync", "time", "rt-multi-thread"] }
|
||||||
|
|||||||
@@ -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"));
|
||||||
|
}
|
||||||
|
}
|
||||||
+127
-10
@@ -3,7 +3,9 @@
|
|||||||
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 markdown;
|
||||||
pub mod permit_view;
|
pub mod permit_view;
|
||||||
pub mod picker;
|
pub mod picker;
|
||||||
pub mod popup;
|
pub mod popup;
|
||||||
@@ -172,6 +174,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 +390,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 +505,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 +564,25 @@ 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![];
|
||||||
|
let w = crossterm::terminal::size().map_or(80, |(w, _)| w as usize);
|
||||||
|
markdown::render(p, w.saturating_sub(4), &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 +945,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 +988,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 +1028,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 +1048,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 +1062,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) {
|
||||||
@@ -1184,6 +1243,8 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option<String> {
|
|||||||
if app.busy {
|
if app.busy {
|
||||||
app.queue.clear();
|
app.queue.clear();
|
||||||
abort.abort();
|
abort.abort();
|
||||||
|
} else if app.state.subs.any_running() {
|
||||||
|
app.state.subs.abort_all();
|
||||||
} else if app.ed.buf.is_empty() {
|
} else if app.ed.buf.is_empty() {
|
||||||
app.quit = true;
|
app.quit = true;
|
||||||
} else {
|
} else {
|
||||||
@@ -1197,6 +1258,7 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option<String> {
|
|||||||
app.queue.clear();
|
app.queue.clear();
|
||||||
abort.abort();
|
abort.abort();
|
||||||
}
|
}
|
||||||
|
KeyCode::Esc if app.state.subs.any_running() => app.state.subs.abort_all(),
|
||||||
KeyCode::Char('o') if ctrl => app.expanded = !app.expanded,
|
KeyCode::Char('o') if ctrl => app.expanded = !app.expanded,
|
||||||
KeyCode::Esc if app.panel.is_some() => app.panel = None,
|
KeyCode::Esc if app.panel.is_some() => app.panel = None,
|
||||||
KeyCode::Char('j') if ctrl => app.ed.insert("\n"),
|
KeyCode::Char('j') if ctrl => app.ed.insert("\n"),
|
||||||
@@ -1325,7 +1387,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 +1539,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
|
||||||
@@ -1608,9 +1688,16 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
|||||||
let _ = tx.send(Ui::Compacted(r));
|
let _ = tx.send(Ui::Compacted(r));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
_ if let Some(Source::Skill(p)) =
|
_ if matches!(
|
||||||
app.specs.iter().find(|s| s.name == c).map(|s| &s.source) =>
|
app.specs.iter().find(|s| s.name == c).map(|s| &s.source),
|
||||||
|
Some(Source::Skill(_))
|
||||||
|
) =>
|
||||||
{
|
{
|
||||||
|
let Some(Source::Skill(p)) =
|
||||||
|
app.specs.iter().find(|s| s.name == c).map(|s| &s.source)
|
||||||
|
else {
|
||||||
|
unreachable!()
|
||||||
|
};
|
||||||
match cmd::skill_prompt(c, p, arg) {
|
match cmd::skill_prompt(c, p, arg) {
|
||||||
Ok(t) => line = t,
|
Ok(t) => line = t,
|
||||||
Err(e) => app.t.push(Item::Error(format!("/{c}: {e}"))),
|
Err(e) => app.t.push(Item::Error(format!("/{c}: {e}"))),
|
||||||
@@ -1674,6 +1761,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 +2033,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 +2750,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,
|
||||||
|
|||||||
@@ -0,0 +1,500 @@
|
|||||||
|
//! Markdown → styled lines via pulldown-cmark: headings, lists, quotes, rules, fenced
|
||||||
|
//! code, inline emphasis/links and box-drawn tables. Half-streamed input is fine: the
|
||||||
|
//! parser treats an unclosed fence as code and an unfinished table as plain text.
|
||||||
|
|
||||||
|
use crate::theme;
|
||||||
|
use pulldown_cmark::{Alignment, CodeBlockKind, Event, Options, Parser, Tag, TagEnd};
|
||||||
|
use ratatui::style::{Modifier, Style};
|
||||||
|
use ratatui::text::{Line, Span};
|
||||||
|
|
||||||
|
type Cell = Vec<Span<'static>>;
|
||||||
|
|
||||||
|
struct Table {
|
||||||
|
aligns: Vec<Alignment>,
|
||||||
|
rows: Vec<Vec<Cell>>,
|
||||||
|
row: Vec<Cell>,
|
||||||
|
cell: Cell,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct W {
|
||||||
|
out: Vec<Line<'static>>,
|
||||||
|
cur: Vec<Span<'static>>,
|
||||||
|
styles: Vec<Style>,
|
||||||
|
/// one entry per open list: next ordinal for ordered lists
|
||||||
|
lists: Vec<Option<u64>>,
|
||||||
|
marker: Option<String>,
|
||||||
|
quote: usize,
|
||||||
|
code: bool,
|
||||||
|
link: Option<(String, String)>,
|
||||||
|
table: Option<Table>,
|
||||||
|
width: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl W {
|
||||||
|
fn style(&self) -> Style {
|
||||||
|
self.styles.last().copied().unwrap_or(theme::t().plain())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn push_style(&mut self, f: impl FnOnce(Style) -> Style) {
|
||||||
|
let s = f(self.style());
|
||||||
|
self.styles.push(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sink(&mut self) -> &mut Vec<Span<'static>> {
|
||||||
|
match &mut self.table {
|
||||||
|
Some(t) => &mut t.cell,
|
||||||
|
None => &mut self.cur,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn text(&mut self, t: &str, style: Style) {
|
||||||
|
if let Some((_, txt)) = &mut self.link {
|
||||||
|
txt.push_str(t);
|
||||||
|
}
|
||||||
|
self.sink().push(Span::styled(t.to_string(), style));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Blank line before a new block, unless nested in a list/quote or at the start.
|
||||||
|
fn gap(&mut self) {
|
||||||
|
self.flush();
|
||||||
|
if self.lists.is_empty()
|
||||||
|
&& self.quote == 0
|
||||||
|
&& self.out.last().is_some_and(|l| !l.spans.is_empty())
|
||||||
|
{
|
||||||
|
self.out.push(Line::default());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn flush(&mut self) {
|
||||||
|
if self.cur.is_empty() && self.marker.is_none() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let th = theme::t();
|
||||||
|
let mut spans = vec![];
|
||||||
|
if self.quote > 0 {
|
||||||
|
spans.push(Span::styled(
|
||||||
|
format!("{} ", th.sym.vrule).repeat(self.quote),
|
||||||
|
th.dim(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if !self.lists.is_empty() {
|
||||||
|
let indent = " ".repeat(self.lists.len() - 1);
|
||||||
|
match self.marker.take() {
|
||||||
|
Some(m) => spans.push(Span::styled(format!("{indent}{m} "), th.accent())),
|
||||||
|
None => spans.push(Span::raw(format!("{indent} "))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
spans.append(&mut self.cur);
|
||||||
|
self.out.push(Line::from(spans));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn start(&mut self, tag: Tag) {
|
||||||
|
let th = theme::t();
|
||||||
|
match tag {
|
||||||
|
Tag::Paragraph => self.gap(),
|
||||||
|
Tag::Heading { level, .. } => {
|
||||||
|
self.gap();
|
||||||
|
let st = match level as usize {
|
||||||
|
1 => th.plain().add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
|
||||||
|
2 => th.plain().add_modifier(Modifier::BOLD),
|
||||||
|
_ => th.sec().add_modifier(Modifier::BOLD),
|
||||||
|
};
|
||||||
|
self.styles.push(st);
|
||||||
|
}
|
||||||
|
Tag::BlockQuote(_) => {
|
||||||
|
self.gap();
|
||||||
|
self.quote += 1;
|
||||||
|
self.push_style(|s| s.add_modifier(Modifier::ITALIC));
|
||||||
|
}
|
||||||
|
Tag::CodeBlock(kind) => {
|
||||||
|
self.gap();
|
||||||
|
let lang = match kind {
|
||||||
|
CodeBlockKind::Fenced(l) => l.to_string(),
|
||||||
|
CodeBlockKind::Indented => String::new(),
|
||||||
|
};
|
||||||
|
self.out
|
||||||
|
.push(Line::styled(format!("```{lang}"), th.dim()));
|
||||||
|
self.code = true;
|
||||||
|
}
|
||||||
|
Tag::List(start) => {
|
||||||
|
if self.lists.is_empty() {
|
||||||
|
self.gap();
|
||||||
|
} else {
|
||||||
|
self.flush();
|
||||||
|
}
|
||||||
|
self.lists.push(start);
|
||||||
|
}
|
||||||
|
Tag::Item => {
|
||||||
|
self.flush();
|
||||||
|
let m = match self.lists.last_mut() {
|
||||||
|
Some(Some(n)) => {
|
||||||
|
let s = format!("{n}.");
|
||||||
|
*n += 1;
|
||||||
|
s
|
||||||
|
}
|
||||||
|
_ => th.sym.bullet.to_string(),
|
||||||
|
};
|
||||||
|
self.marker = Some(m);
|
||||||
|
}
|
||||||
|
Tag::Emphasis => self.push_style(|s| s.add_modifier(Modifier::ITALIC)),
|
||||||
|
Tag::Strong => self.push_style(|s| s.add_modifier(Modifier::BOLD)),
|
||||||
|
Tag::Strikethrough => self.push_style(|s| s.add_modifier(Modifier::CROSSED_OUT)),
|
||||||
|
Tag::Link { dest_url, .. } => {
|
||||||
|
self.link = Some((dest_url.to_string(), String::new()));
|
||||||
|
self.styles.push(th.link().add_modifier(Modifier::UNDERLINED));
|
||||||
|
}
|
||||||
|
Tag::Table(aligns) => {
|
||||||
|
self.gap();
|
||||||
|
self.table = Some(Table {
|
||||||
|
aligns,
|
||||||
|
rows: vec![],
|
||||||
|
row: vec![],
|
||||||
|
cell: vec![],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Tag::TableHead => self.push_style(|s| s.add_modifier(Modifier::BOLD)),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn end(&mut self, tag: TagEnd) {
|
||||||
|
let th = theme::t();
|
||||||
|
match tag {
|
||||||
|
TagEnd::Paragraph => self.flush(),
|
||||||
|
TagEnd::Heading(_) => {
|
||||||
|
self.flush();
|
||||||
|
self.styles.pop();
|
||||||
|
}
|
||||||
|
TagEnd::BlockQuote(_) => {
|
||||||
|
self.flush();
|
||||||
|
self.quote -= self.quote.min(1);
|
||||||
|
self.styles.pop();
|
||||||
|
}
|
||||||
|
TagEnd::CodeBlock => {
|
||||||
|
self.code = false;
|
||||||
|
self.out.push(Line::styled("```", th.dim()));
|
||||||
|
}
|
||||||
|
TagEnd::List(_) => {
|
||||||
|
self.flush();
|
||||||
|
self.lists.pop();
|
||||||
|
}
|
||||||
|
TagEnd::Item => self.flush(),
|
||||||
|
TagEnd::Emphasis | TagEnd::Strong | TagEnd::Strikethrough => {
|
||||||
|
self.styles.pop();
|
||||||
|
}
|
||||||
|
TagEnd::Link => {
|
||||||
|
self.styles.pop();
|
||||||
|
if let Some((url, txt)) = self.link.take()
|
||||||
|
&& !url.is_empty()
|
||||||
|
&& url != txt
|
||||||
|
{
|
||||||
|
self.sink()
|
||||||
|
.push(Span::styled(format!(" ({url})"), th.dim()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
TagEnd::TableCell => {
|
||||||
|
if let Some(t) = &mut self.table {
|
||||||
|
let c = std::mem::take(&mut t.cell);
|
||||||
|
t.row.push(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
TagEnd::TableHead | TagEnd::TableRow => {
|
||||||
|
if matches!(tag, TagEnd::TableHead) {
|
||||||
|
self.styles.pop();
|
||||||
|
}
|
||||||
|
if let Some(t) = &mut self.table {
|
||||||
|
let r = std::mem::take(&mut t.row);
|
||||||
|
t.rows.push(r);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
TagEnd::Table => {
|
||||||
|
if let Some(t) = self.table.take() {
|
||||||
|
let lines = table(&t.aligns, &t.rows, self.width);
|
||||||
|
self.out.extend(lines);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn event(&mut self, e: Event) {
|
||||||
|
let th = theme::t();
|
||||||
|
match e {
|
||||||
|
Event::Start(t) => self.start(t),
|
||||||
|
Event::End(t) => self.end(t),
|
||||||
|
Event::Text(t) | Event::Html(t) | Event::InlineHtml(t) if self.code => {
|
||||||
|
for l in t.lines() {
|
||||||
|
self.out.push(Line::styled(l.to_string(), th.block_code()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Event::Text(t) | Event::Html(t) | Event::InlineHtml(t) => {
|
||||||
|
let st = self.style();
|
||||||
|
self.text(&t, st);
|
||||||
|
}
|
||||||
|
Event::Code(t) => self.text(&t, th.code()),
|
||||||
|
Event::SoftBreak | Event::HardBreak => {
|
||||||
|
if self.table.is_some() {
|
||||||
|
let st = self.style();
|
||||||
|
self.text(" ", st);
|
||||||
|
} else {
|
||||||
|
self.flush();
|
||||||
|
// keep the list indent on continuation lines
|
||||||
|
if self.lists.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Event::Rule => {
|
||||||
|
self.gap();
|
||||||
|
self.out
|
||||||
|
.push(Line::styled(th.rule("", self.width), th.dim()));
|
||||||
|
}
|
||||||
|
Event::TaskListMarker(done) => {
|
||||||
|
self.marker = Some(
|
||||||
|
if done { th.sym.check_on } else { th.sym.check_off }.to_string(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Render `s` into `out`; `width` is the column budget (tables fit themselves into it).
|
||||||
|
pub fn render(s: &str, width: usize, out: &mut Vec<Line<'static>>) {
|
||||||
|
let mut w = W {
|
||||||
|
out: vec![],
|
||||||
|
cur: vec![],
|
||||||
|
styles: vec![],
|
||||||
|
lists: vec![],
|
||||||
|
marker: None,
|
||||||
|
quote: 0,
|
||||||
|
code: false,
|
||||||
|
link: None,
|
||||||
|
table: None,
|
||||||
|
width,
|
||||||
|
};
|
||||||
|
let opts = Options::ENABLE_TABLES | Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TASKLISTS;
|
||||||
|
for e in Parser::new_ext(s, opts) {
|
||||||
|
w.event(e);
|
||||||
|
}
|
||||||
|
w.flush();
|
||||||
|
while w.out.last().is_some_and(|l| l.spans.is_empty()) {
|
||||||
|
w.out.pop();
|
||||||
|
}
|
||||||
|
out.append(&mut w.out);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- tables ------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
fn cell_w(c: &[Span]) -> usize {
|
||||||
|
c.iter().map(Span::width).sum()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Greedy wrap of styled text to `w` columns (hard break when a word is longer).
|
||||||
|
fn wrap(spans: &[Span<'static>], w: usize) -> Vec<Cell> {
|
||||||
|
let w = w.max(1);
|
||||||
|
let chars: Vec<(char, Style)> = spans
|
||||||
|
.iter()
|
||||||
|
.flat_map(|s| s.content.chars().map(|c| (c, s.style)))
|
||||||
|
.collect();
|
||||||
|
let cw = |c: char| Span::raw(c.to_string()).width();
|
||||||
|
let mut rows: Vec<Vec<(char, Style)>> = vec![];
|
||||||
|
let mut cur: Vec<(char, Style)> = vec![];
|
||||||
|
let mut cur_w = 0;
|
||||||
|
for (c, st) in chars {
|
||||||
|
let n = cw(c);
|
||||||
|
if cur_w + n > w {
|
||||||
|
match cur.iter().rposition(|x| x.0 == ' ') {
|
||||||
|
Some(k) if c != ' ' => {
|
||||||
|
let tail = cur.split_off(k + 1);
|
||||||
|
cur.pop(); // the space
|
||||||
|
rows.push(std::mem::take(&mut cur));
|
||||||
|
cur = tail;
|
||||||
|
}
|
||||||
|
_ => rows.push(std::mem::take(&mut cur)),
|
||||||
|
}
|
||||||
|
cur_w = cur.iter().map(|x| cw(x.0)).sum();
|
||||||
|
if c == ' ' && cur.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cur.push((c, st));
|
||||||
|
cur_w += n;
|
||||||
|
}
|
||||||
|
rows.push(cur);
|
||||||
|
rows.into_iter()
|
||||||
|
.map(|r| {
|
||||||
|
let mut out: Cell = vec![];
|
||||||
|
for (c, st) in r {
|
||||||
|
match out.last_mut() {
|
||||||
|
Some(l) if l.style == st => l.content.to_mut().push(c),
|
||||||
|
_ => out.push(Span::styled(c.to_string(), st)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn table(aligns: &[Alignment], rows: &[Vec<Cell>], width: usize) -> Vec<Line<'static>> {
|
||||||
|
let th = theme::t();
|
||||||
|
let n = aligns.len();
|
||||||
|
let rows: Vec<Vec<Cell>> = rows
|
||||||
|
.iter()
|
||||||
|
.map(|r| {
|
||||||
|
let mut r = r.clone();
|
||||||
|
r.resize(n, vec![]);
|
||||||
|
r
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
if n == 0 || rows.is_empty() {
|
||||||
|
return vec![];
|
||||||
|
}
|
||||||
|
let mut cols: Vec<usize> = (0..n)
|
||||||
|
.map(|c| rows.iter().map(|r| cell_w(&r[c])).max().unwrap_or(0).max(1))
|
||||||
|
.collect();
|
||||||
|
let overhead = 3 * n + 1;
|
||||||
|
if width < overhead + 3 * n {
|
||||||
|
return table_as_list(&rows);
|
||||||
|
}
|
||||||
|
while cols.iter().sum::<usize>() + overhead > width {
|
||||||
|
let (k, &m) = cols.iter().enumerate().max_by_key(|x| x.1).unwrap_or((0, &0));
|
||||||
|
if m <= 3 {
|
||||||
|
return table_as_list(&rows);
|
||||||
|
}
|
||||||
|
cols[k] -= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
let s = th.sym.tbl; // h v tl tm tr ml mm mr bl bm br
|
||||||
|
let border = |l: &str, m: &str, r: &str| {
|
||||||
|
let parts: Vec<String> = cols.iter().map(|&w| s[0].repeat(w + 2)).collect();
|
||||||
|
Line::styled(format!("{l}{}{r}", parts.join(m)), th.dim())
|
||||||
|
};
|
||||||
|
let mut out = vec![border(s[2], s[3], s[4])];
|
||||||
|
for (ri, row) in rows.iter().enumerate() {
|
||||||
|
let wrapped: Vec<Vec<Cell>> = row.iter().zip(&cols).map(|(c, &w)| wrap(c, w)).collect();
|
||||||
|
let h = wrapped.iter().map(Vec::len).max().unwrap_or(1);
|
||||||
|
for y in 0..h {
|
||||||
|
let mut spans = vec![Span::styled(s[1].to_string(), th.dim())];
|
||||||
|
for (x, cell) in wrapped.iter().enumerate() {
|
||||||
|
let content = cell.get(y).cloned().unwrap_or_default();
|
||||||
|
let pad = cols[x].saturating_sub(cell_w(&content));
|
||||||
|
let (l, r) = match aligns[x] {
|
||||||
|
Alignment::Right => (pad, 0),
|
||||||
|
Alignment::Center => (pad / 2, pad - pad / 2),
|
||||||
|
_ => (0, pad),
|
||||||
|
};
|
||||||
|
spans.push(Span::raw(" ".repeat(l + 1)));
|
||||||
|
spans.extend(content);
|
||||||
|
spans.push(Span::raw(" ".repeat(r + 1)));
|
||||||
|
spans.push(Span::styled(s[1].to_string(), th.dim()));
|
||||||
|
}
|
||||||
|
out.push(Line::from(spans));
|
||||||
|
}
|
||||||
|
if ri == 0 {
|
||||||
|
out.push(border(s[5], s[6], s[7]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.push(border(s[8], s[9], s[10]));
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Too narrow for a grid: one `header: value` block per row.
|
||||||
|
fn table_as_list(rows: &[Vec<Cell>]) -> Vec<Line<'static>> {
|
||||||
|
let th = theme::t();
|
||||||
|
let mut out = vec![];
|
||||||
|
for r in &rows[1..] {
|
||||||
|
for (h, c) in rows[0].iter().zip(r) {
|
||||||
|
let mut spans: Vec<Span<'static>> = h.clone();
|
||||||
|
spans.push(Span::styled(": ", th.dim()));
|
||||||
|
spans.extend(c.clone());
|
||||||
|
out.push(Line::from(spans));
|
||||||
|
}
|
||||||
|
out.push(Line::default());
|
||||||
|
}
|
||||||
|
out.pop();
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn text(ls: &[Line]) -> Vec<String> {
|
||||||
|
ls.iter()
|
||||||
|
.map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lines(s: &str, w: usize) -> Vec<Line<'static>> {
|
||||||
|
let mut out = vec![];
|
||||||
|
render(s, w, &mut out);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn md(s: &str, w: usize) -> Vec<String> {
|
||||||
|
text(&lines(s, w))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn inline_md() {
|
||||||
|
assert_eq!(md("a `b` **c** d", 40), ["a b c d"]);
|
||||||
|
assert_eq!(lines("a `b` c", 40)[0].spans[1].style.fg, theme::t().code().fg);
|
||||||
|
assert_eq!(md("x ` unclosed", 40), ["x ` unclosed"]);
|
||||||
|
assert_eq!(md("*i* ~~s~~", 40), ["i s"]);
|
||||||
|
assert_eq!(
|
||||||
|
md("see [docs](http://x.y) and [z](z)", 40),
|
||||||
|
["see docs (http://x.y) and z"]
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
lines("**b**", 40)[0].spans[0]
|
||||||
|
.style
|
||||||
|
.add_modifier
|
||||||
|
.contains(Modifier::BOLD)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn table_aligned() {
|
||||||
|
let s = md("| Name | N |\n|:--|--:|\n| alpha | 1 |\n| b | 22 |", 40);
|
||||||
|
assert_eq!(
|
||||||
|
s,
|
||||||
|
[
|
||||||
|
"┌───────┬────┐",
|
||||||
|
"│ Name │ N │",
|
||||||
|
"├───────┼────┤",
|
||||||
|
"│ alpha │ 1 │",
|
||||||
|
"│ b │ 22 │",
|
||||||
|
"└───────┴────┘",
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn table_wraps_to_width() {
|
||||||
|
let t = "| a | b |\n|---|---|\n| one two three four five six | seven eight nine ten |";
|
||||||
|
let s = md(t, 24);
|
||||||
|
assert!(s.len() > 5, "{s:?}");
|
||||||
|
let w = s[0].chars().count();
|
||||||
|
assert!(w <= 24 && s.iter().all(|l| l.chars().count() == w), "{s:?}");
|
||||||
|
let narrow = md(t, 8);
|
||||||
|
assert!(narrow.iter().any(|l| l.starts_with("a: one")), "{narrow:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn blocks() {
|
||||||
|
let s = md("# T\n\ntext\n\n- a\n - b\n- [x] done\n\n1. one\n\n> q\n\n---\n\n```rs\nlet x;\n```", 20);
|
||||||
|
for want in ["T", "text", "• a", " • b", "☑ done", "1. one", "│ q", "```rs", "let x;"] {
|
||||||
|
assert!(s.iter().any(|l| l == want), "missing {want:?} in {s:?}");
|
||||||
|
}
|
||||||
|
assert!(s.iter().any(|l| l.starts_with('┈')), "{s:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn streaming_states_do_not_panic() {
|
||||||
|
for s in ["| a | b", "| a | b |\n|--", "| a | b |\n|---|---|", "```", "**", "[x](", "1."] {
|
||||||
|
md(s, 30);
|
||||||
|
}
|
||||||
|
assert_eq!(md("| a | b |", 30), ["| a | b |"]);
|
||||||
|
}
|
||||||
|
}
|
||||||
+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(' ');
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
out.push('\n');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.push_str(line);
|
||||||
|
prev_full = full;
|
||||||
}
|
}
|
||||||
rows.join("\n")
|
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]
|
||||||
|
|||||||
@@ -51,6 +51,11 @@ pub struct Sym {
|
|||||||
pub branch: &'static str,
|
pub branch: &'static str,
|
||||||
pub dirty: &'static str,
|
pub dirty: &'static str,
|
||||||
pub vrule: &'static str,
|
pub vrule: &'static str,
|
||||||
|
pub bullet: &'static str,
|
||||||
|
pub check_on: &'static str,
|
||||||
|
pub check_off: &'static str,
|
||||||
|
/// table box: h v tl tm tr ml mm mr bl bm br
|
||||||
|
pub tbl: [&'static str; 11],
|
||||||
pub spin: &'static [&'static str],
|
pub spin: &'static [&'static str],
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -77,6 +82,10 @@ const UNICODE: Sym = Sym {
|
|||||||
branch: "⎇ ",
|
branch: "⎇ ",
|
||||||
dirty: "●",
|
dirty: "●",
|
||||||
vrule: "│",
|
vrule: "│",
|
||||||
|
bullet: "•",
|
||||||
|
check_on: "☑",
|
||||||
|
check_off: "☐",
|
||||||
|
tbl: ["─", "│", "┌", "┬", "┐", "├", "┼", "┤", "└", "┴", "┘"],
|
||||||
spin: &["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"],
|
spin: &["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"],
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -103,6 +112,10 @@ const ASCII: Sym = Sym {
|
|||||||
branch: "@",
|
branch: "@",
|
||||||
dirty: "*",
|
dirty: "*",
|
||||||
vrule: "|",
|
vrule: "|",
|
||||||
|
bullet: "-",
|
||||||
|
check_on: "[x]",
|
||||||
|
check_off: "[ ]",
|
||||||
|
tbl: ["-", "|", "+", "+", "+", "+", "+", "+", "+", "+", "+"],
|
||||||
spin: &["-", "\\", "|", "/"],
|
spin: &["-", "\\", "|", "/"],
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -332,7 +332,7 @@ fn render(it: &Item, expanded: bool, width: usize, out: &mut Vec<Line<'static>>)
|
|||||||
}
|
}
|
||||||
Item::Assistant(s) => {
|
Item::Assistant(s) => {
|
||||||
let mut md = vec![];
|
let mut md = vec![];
|
||||||
markdown(s, &mut md);
|
crate::markdown::render(s, width.saturating_sub(2), &mut md);
|
||||||
lead(md, " ", th.plain(), out);
|
lead(md, " ", th.plain(), out);
|
||||||
}
|
}
|
||||||
Item::Thinking(s) if expanded => {
|
Item::Thinking(s) if expanded => {
|
||||||
@@ -554,63 +554,6 @@ fn advance(cur: Option<usize>, l: &str) -> Option<usize> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Minimal markdown: fenced code, headings, bullets, inline `code` and **bold**.
|
|
||||||
fn markdown(s: &str, out: &mut Vec<Line<'static>>) {
|
|
||||||
let mut code = false;
|
|
||||||
for l in s.lines() {
|
|
||||||
if l.trim_start().starts_with("```") {
|
|
||||||
code = !code;
|
|
||||||
out.push(Line::styled(l.to_string(), theme::t().dim()));
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if code {
|
|
||||||
out.push(Line::styled(l.to_string(), theme::t().block_code()));
|
|
||||||
} else if l.starts_with('#') {
|
|
||||||
out.push(Line::styled(
|
|
||||||
l.trim_start_matches('#').trim().to_string(),
|
|
||||||
theme::t()
|
|
||||||
.plain()
|
|
||||||
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
|
|
||||||
));
|
|
||||||
} else {
|
|
||||||
out.push(inline(l));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn inline(l: &str) -> Line<'static> {
|
|
||||||
let mut spans = vec![];
|
|
||||||
let mut rest = l;
|
|
||||||
while !rest.is_empty() {
|
|
||||||
let next = [
|
|
||||||
("`", theme::t().code()),
|
|
||||||
("**", theme::t().plain().add_modifier(Modifier::BOLD)),
|
|
||||||
]
|
|
||||||
.into_iter()
|
|
||||||
.filter_map(|(d, st)| {
|
|
||||||
let i = rest.find(d)?;
|
|
||||||
let j = rest[i + d.len()..].find(d)?;
|
|
||||||
Some((i, j, d, st))
|
|
||||||
})
|
|
||||||
.min_by_key(|x| x.0);
|
|
||||||
match next {
|
|
||||||
Some((i, j, d, st)) => {
|
|
||||||
spans.push(Span::raw(rest[..i].to_string()));
|
|
||||||
spans.push(Span::styled(
|
|
||||||
rest[i + d.len()..i + d.len() + j].to_string(),
|
|
||||||
st,
|
|
||||||
));
|
|
||||||
rest = &rest[i + d.len() * 2 + j..];
|
|
||||||
}
|
|
||||||
None => {
|
|
||||||
spans.push(Span::raw(rest.to_string()));
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Line::from(spans)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -798,11 +741,4 @@ mod tests {
|
|||||||
t.live.clear();
|
t.live.clear();
|
||||||
assert_eq!(t.lines(false, 40).len(), 2, "no tail when nothing is live");
|
assert_eq!(t.lines(false, 40).len(), 2, "no tail when nothing is live");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn inline_md() {
|
|
||||||
assert_eq!(text(&[inline("a `b` **c** d")]), ["a b c d"]);
|
|
||||||
assert_eq!(inline("a `b` c").spans[1].style.fg, theme::t().code().fg);
|
|
||||||
assert_eq!(text(&[inline("x ` unclosed")]), ["x ` unclosed"]);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
+1
-1
@@ -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;
|
||||||
}
|
}
|
||||||
@@ -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;
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
"""Fake orchestrator for `hx serve --acp`: drives hx over stdio and checks the protocol.
|
||||||
|
Usage: python3 tests/acp_client.py HX_BIN REPO SESSION_ID PORT
|
||||||
|
Scenario (against tests/fake_anthropic.py with acp_turns.json):
|
||||||
|
run 1: step with context limit 1 -> permission asked, edit done, step ends blocked (limit)
|
||||||
|
step 2 -> done, decision + plan reported
|
||||||
|
run 2 (new process, same session) -> step 3 sees the earlier conversation
|
||||||
|
"""
|
||||||
|
import json, subprocess, sys, urllib.request
|
||||||
|
|
||||||
|
hx, repo, sid, port = sys.argv[1:5]
|
||||||
|
seen = [] # every notification and request from hx, in order
|
||||||
|
|
||||||
|
|
||||||
|
class Hx:
|
||||||
|
def __init__(self):
|
||||||
|
self.p = subprocess.Popen([hx, "serve", "--acp", "--cwd", repo, "--session", sid],
|
||||||
|
stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
|
||||||
|
self.n = 0
|
||||||
|
|
||||||
|
def send(self, m):
|
||||||
|
self.p.stdin.write(json.dumps({"jsonrpc": "2.0", **m}) + "\n")
|
||||||
|
self.p.stdin.flush()
|
||||||
|
|
||||||
|
def call(self, method, params):
|
||||||
|
self.n += 1
|
||||||
|
self.send({"id": self.n, "method": method, "params": params})
|
||||||
|
while True:
|
||||||
|
line = self.p.stdout.readline()
|
||||||
|
assert line, "hx closed stdout"
|
||||||
|
m = json.loads(line)
|
||||||
|
if "method" in m:
|
||||||
|
seen.append(m)
|
||||||
|
if "id" in m: # permission request: allow once
|
||||||
|
assert m["method"] == "session/request_permission", m
|
||||||
|
self.send({"id": m["id"], "result": {"outcome": {"outcome": "selected", "optionId": "allow_once"}}})
|
||||||
|
elif m.get("id") == self.n:
|
||||||
|
assert "error" not in m, m
|
||||||
|
return m["result"]
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
self.p.stdin.close()
|
||||||
|
assert self.p.wait(timeout=30) == 0
|
||||||
|
|
||||||
|
|
||||||
|
def notes(method):
|
||||||
|
return [m["params"] for m in seen if m["method"] == method]
|
||||||
|
|
||||||
|
|
||||||
|
a = Hx()
|
||||||
|
init = a.call("initialize", {"protocolVersion": 1})
|
||||||
|
assert init["agentInfo"]["name"] == "hx", init
|
||||||
|
assert a.call("session/new", {"cwd": repo, "mcpServers": []})["sessionId"] == sid
|
||||||
|
|
||||||
|
r = a.call("hx/step", {"prompt": "write hello.txt", "instruction": "implement", "context": {"goal": "demo"},
|
||||||
|
"limits": {"context_tokens": 1}})
|
||||||
|
assert r["status"] == "blocked" and r["catch"] is None and r["reason"] == "limit" and "context limit" in r["summary"], r
|
||||||
|
perm = [m for m in seen if m["method"] == "session/request_permission"]
|
||||||
|
assert perm and perm[0]["params"]["options"][0]["optionId"] == "allow_once", perm
|
||||||
|
assert open(f"{repo}/hello.txt").read() == "hi from hx\n"
|
||||||
|
assert {"path": "hello.txt", "added": 1, "removed": 0} in notes("hx/edit"), notes("hx/edit")
|
||||||
|
assert any("hello.txt" in i for i in notes("hx/intent")), notes("hx/intent")
|
||||||
|
assert notes("hx/usage") and notes("hx/usage")[0]["used"] > 0, notes("hx/usage")
|
||||||
|
assert notes("hx/step_result")[0] == r
|
||||||
|
|
||||||
|
a.call("hx/message", "prefer small commits")
|
||||||
|
r = a.call("hx/step", {"prompt": "now summarize"})
|
||||||
|
assert r["status"] == "done" and r["summary"] == "wrote hello.txt", r
|
||||||
|
assert [d["text"] for d in notes("hx/decision")] == ["token bucket over sliding window"]
|
||||||
|
assert notes("hx/plan") == [{"steps": ["write", "test"], "files": ["hello.txt"]}], notes("hx/plan")
|
||||||
|
assert a.call("hx/interrupt", {}) == {}
|
||||||
|
a.close()
|
||||||
|
|
||||||
|
b = Hx()
|
||||||
|
b.call("initialize", {"protocolVersion": 1})
|
||||||
|
r = b.call("hx/step", {"prompt": "what did you do before?"})
|
||||||
|
assert r["status"] == "done", r
|
||||||
|
b.close()
|
||||||
|
|
||||||
|
log = json.load(urllib.request.urlopen(f"http://127.0.0.1:{port}/"))
|
||||||
|
text = json.dumps(log[-1]["body"]["messages"])
|
||||||
|
assert "write hello.txt" in text and "wrote hello.txt" in text, "session not continued"
|
||||||
|
assert "prefer small commits" in json.dumps(log[1]["body"]["messages"]), "hint not delivered"
|
||||||
|
print("acp e2e ok")
|
||||||
Executable
+15
@@ -0,0 +1,15 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# ACP e2e: `hx serve --acp` driven by a fake orchestrator (tests/acp_client.py) against a fake Anthropic API:
|
||||||
|
# permission requests, hx/edit|usage|intent|decision|plan|step_result, limits, hx/message, session continuation.
|
||||||
|
set -eu
|
||||||
|
root=$(cd "$(dirname "$0")/.." && pwd)
|
||||||
|
tmp=$(mktemp -d)
|
||||||
|
trap 'kill $srv 2>/dev/null; rm -rf "$tmp"' EXIT
|
||||||
|
port=$((20000 + $$ % 20000))
|
||||||
|
python3 "$root/tests/fake_anthropic.py" $port "$root/tests/acp_turns.json" & srv=$!
|
||||||
|
mkdir -p "$tmp/home/.hx" "$tmp/repo"
|
||||||
|
echo '{"claude":{"access":"fake-token","refresh":"r","expires":99999999999999}}' > "$tmp/home/.hx/auth.json"
|
||||||
|
printf 'claude_cli = false\n[lsp]\nmode = "off"\ntests = "off"\n' > "$tmp/home/.hx/config.toml"
|
||||||
|
sleep 0.5
|
||||||
|
export HOME="$tmp/home" HX_BASE_URL="http://127.0.0.1:$port"
|
||||||
|
python3 "$root/tests/acp_client.py" "$root/target/debug/hx" "$tmp/repo" demo-1 $port
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
[
|
||||||
|
[["tool_use", {"id": "t1", "name": "Write", "input": {"path": "hello.txt", "content": "hi from hx\n"}}]],
|
||||||
|
[["text", "Done.\n```hx-step\n{\"status\":\"done\",\"summary\":\"wrote hello.txt\",\"decisions\":[\"token bucket over sliding window\"],\"plan\":{\"steps\":[\"write\",\"test\"],\"files\":[\"hello.txt\"]}}\n```"]],
|
||||||
|
[["text", "```hx-step\n{\"status\":\"done\",\"summary\":\"as before\"}\n```"]]
|
||||||
|
]
|
||||||
@@ -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