Compare commits
10
Commits
742f2a124a
...
v0.2.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
061649cb07 | ||
|
|
9d8b7dfbd8 | ||
|
|
179e5cddc7 | ||
|
|
05165d7b8f | ||
|
|
c06381117b | ||
|
|
9fbcf4a62c | ||
|
|
b84b6ab23a | ||
|
|
161c33fe6c | ||
|
|
3f1acd045b | ||
|
|
c849463805 |
No files matched your search
@@ -15,6 +15,12 @@ hx -r # pick a session to resume
|
||||
hx -r parser # resume the session whose title best matches "parser"
|
||||
```
|
||||
|
||||
## Dependencies
|
||||
|
||||
- Rust toolchain (to build from source; `cmake` and `perl` may be needed for the TLS stack).
|
||||
- `git`.
|
||||
- Linux: [`bubblewrap`](https://github.com/containers/bubblewrap) (`bwrap`) on `PATH` (`apt install bubblewrap`, `pacman -S bubblewrap`, `dnf install bubblewrap`). The Nix package wraps `hx` so it is provided automatically.
|
||||
|
||||
TUI: `enter` send, `shift-enter`/`alt-enter`/`ctrl-j` newline (or end a line with `\` and press enter), `esc` abort, `ctrl-o` expand tool output.
|
||||
|
||||
Shift-enter needs a terminal that reports it; hx turns on the kitty keyboard protocol when the terminal answers the probe. Works in ghostty, kitty, WezTerm (`enable_kitty_keyboard = true`), iTerm2, foot, Alacritty 0.13+, Windows Terminal (map shift-enter to `\u001b[13;2u`) and zellij 0.41+. tmux 3.2+ needs `set -g extended-keys on` and `set -g extended-keys-format csi-u`. Elsewhere use `alt-enter`, `ctrl-j` or a trailing `\`. `/keys` prints every key as hx receives it, to see what a terminal or multiplexer (e.g. herdr) passes through. Long input lines wrap; the box grows up to 10 rows.
|
||||
@@ -44,6 +50,8 @@ Lens findings and affected-test results appear after each turn as a `┄ lens
|
||||
|
||||
Config: `~/.hx/config.toml`, overridden per project by `.hx/config.toml`. `hx config init [--project] [--force]` writes a fully commented sample with every key. Example:
|
||||
|
||||
**Session storage:** `sessions_dir` in config (or `HX_SESSIONS_DIR`, wins) moves sessions off `~/.hx/sessions`, e.g. to a synced or mounted cloud folder (rclone, Nextcloud, Syncthing). `~` expands; an unwritable path is an error, no silent fallback. `sessions_host = true` prefixes project folders with the host name so machines sharing one folder stay apart. Sessions are append-only JSONL: one hx per session file.
|
||||
|
||||
```toml
|
||||
provider = "claude" # or "codex"
|
||||
# claude_model = "claude-sonnet-5-5" # default: the account's latest Sonnet
|
||||
@@ -108,7 +116,7 @@ Permissions: only writes ask. `write`/`edit` and unknown `bash` commands prompt;
|
||||
|
||||
Auto permissions (`--auto`, `permissions = "auto"`, `/auto [on|off|log]`): nothing prompts for the usual work, and dangerous calls are refused without asking. A refused call returns `blocked by auto mode: <reason>` to the model (also over a stored "always" rule); `/auto log` lists the last 20. Per call, in order: (1) rules block `rm -rf` of home/root/project root/outside the project, `sudo`, raw disk writes and filesystem creation, download piped to a shell, force push, push to main/master, sending `.env`/keys over the network, `npm|cargo publish`, `docker push`, `kubectl delete`, `terraform destroy`, SQL `DROP`, writes to `/etc`, `~/.ssh`, shell rc files, `.git/hooks`; (2) rules allow routine work inside the project (build/test/format, local git, `mkdir`/`mv`/`cp`/`rm` in the project, `write`/`edit` of project files); (3) everything else (unknown binaries, `curl`, `python -c`, `$(..)`, redirects, paths outside the project) goes to one cheap-model request (Haiku/Luna, ~300 input tokens, 20 s timeout) that answers ALLOW or BLOCK; if that fails or is unavailable the normal prompt appears. `--yolo` / `/yolo` still skip everything. With the `claude_cli` provider claude's tools appear on the event bus (`tool_call` / `tool_result`; hx names `bash{command}`, `write|edit|read{path}`, other tools under claude's name), so extensions can block them (a `block` denies the call with its reason) and NDJSON / `hx stats` see them. Reads are asked too (`--settings` `permissions.ask`; Bash too, claude auto-runs read-only commands like `ls` without asking otherwise). In `-p` there is no prompt and everything is allowed, unless `permissions = "deny"` (every unanswered call is denied) or `permissions = "extensions-only"` (allowed only while a live `tool_call` extension exists). The same rules apply to claude's tool calls, but no model judge runs (unclear ones ask). Pattern rules are not a sandbox: combine with `[sandbox]` for confinement.
|
||||
|
||||
The model can call `task(prompt, kind)` (or `task(prompts=[…], kind)` to fan out: one subagent per prompt, parallel, answers returned numbered; a lone task blocks the parent, so the tool description steers the model to batches) to run a subagent with a fresh context and get back only its final answer (cut at 8 KB), so big searches don't fill the main context. `explore` (default) is read-only (`read`, `lsp`, `bash`) on the provider's cheapest model (`explore_model` in config); `general` has the parent's tools and model, and the lens runs on its edits. Up to 3 run in parallel, none can start another, a parent abort stops them. Their sessions are written to `<session>.sub/`; `hx stats` shows `task` usage (calls, lone vs. batched turns) and lists them and the footer token counts include them. **Overview:** while any subagent exists, a list sits above the footer (bottom right: spinner/✓, id, kind, task, time, calls, tokens). `ctrl-g` focuses it (`↑↓`, `enter` opens, `esc` closes); the detail view shows that agent's live transcript. Typing there messages the agent: while it runs the text is delivered at its next turn end (like steering the main agent), after it finished it continues that agent's conversation. `ctrl-c` aborts that agent only; `ctrl-s` sends its last answer to the main chat as `[subagent N] …`. NDJSON/RPC carry no per-agent events yet.
|
||||
Each `task` call asks for permission (`[a]` allows that kind for the project); `subagents = false` or `--no-subagents` removes the tool. The model can call `task(prompt, kind)` (or `task(prompts=[…], kind)` to fan out: one subagent per prompt, parallel, answers returned numbered; a lone task blocks the parent, so the tool description steers the model to batches) to run a subagent with a fresh context and get back only its final answer (cut at 8 KB), so big searches don't fill the main context. `explore` (default) is read-only (`read`, `lsp`, `bash`) on the provider's cheapest model (`explore_model` in config); `general` has the parent's tools and model, and the lens runs on its edits. Up to 3 run in parallel, none can start another, a parent abort stops them. Their sessions are written to `<session>.sub/`; `hx stats` shows `task` usage (calls, lone vs. batched turns) and lists them and the footer token counts include them. **Overview:** while any subagent exists, a list sits above the footer (bottom right: spinner/✓, id, kind, task, time, calls, tokens). `ctrl-g` focuses it (`↑↓`, `enter` opens, `esc` closes); the detail view shows that agent's live transcript. Typing there messages the agent: while it runs the text is delivered at its next turn end (like steering the main agent), after it finished it continues that agent's conversation. `ctrl-c` aborts that agent only; `ctrl-s` sends its last answer to the main chat as `[subagent N] …`. NDJSON/RPC carry no per-agent events yet.
|
||||
|
||||
A child starts with a cold prompt cache and costs tokens of its own: it saves *main-context* size, not total tokens.
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"version": "0.1.13",
|
||||
"version": "0.1.16",
|
||||
"sha256": {
|
||||
"aarch64-apple-darwin": "bbc47b4ef0225201654b0c0330dd161bc88100ad499e1e23652414c6a1d84910",
|
||||
"x86_64-unknown-linux-musl": "38c000648bb34f99e49437b79dfe9f518f6ca476f6cd9e04892982f0a11a0601"
|
||||
"aarch64-apple-darwin": "5750c046c3e592cbdc9b658ba9c499d44287e85fc0d47052d9cfbf0d9383cc77",
|
||||
"x86_64-unknown-linux-musl": "93f0727fdb7cd47d682f7f37996a4060a948886a0a126ba6105c5c45d121053a"
|
||||
}
|
||||
}
|
||||
@@ -5,11 +5,14 @@
|
||||
# model = "claude-sonnet-5-5" # model for the chosen provider; "auto" = pick per prompt (see [auto])
|
||||
# claude_model = "claude-sonnet-5-5" # default: the account's latest Sonnet
|
||||
# codex_model = "gpt-5.6-sol" # default: Codex's top-listed model
|
||||
# subagents = false # do not offer the `task` tool (default true; every call asks first)
|
||||
# explore_model = "claude-haiku-4-5" # read-only `task` subagents; default: cheapest tier of the provider
|
||||
# remember_model = true # reuse the last model picked with /model or /provider
|
||||
# compact_at = 900000 # auto-compact at this many tokens; default: 90% of the context window
|
||||
# max_tokens = 16384
|
||||
# permissions = "ask" # ask | auto (refuse dangerous calls, run safe ones) | yolo (nothing asks)
|
||||
# sessions_dir = "~/Nextcloud/hx-sessions" # default ~/.hx/sessions; point at a synced/mounted cloud folder (env HX_SESSIONS_DIR wins)
|
||||
# sessions_host = false # true: prefix project folders with the host name (machines sharing one sessions_dir)
|
||||
# mouse = true # wheel scrolling; false keeps terminal text selection
|
||||
# codemode = false # `codemode` tool: JS scripts that call other tools in a sandbox
|
||||
# system_prompt = "..." # replaces the built-in prompt; AGENTS.md is still appended
|
||||
|
||||
@@ -49,6 +49,9 @@ struct Cli {
|
||||
/// prompt (also `permissions = "auto"`).
|
||||
#[arg(long, conflicts_with = "yolo")]
|
||||
auto: bool,
|
||||
/// Do not offer the `task` subagent tool to the model.
|
||||
#[arg(long)]
|
||||
no_subagents: bool,
|
||||
/// Run bash, LSP servers and lens runners in a sandbox (bwrap / seatbelt).
|
||||
#[arg(long, conflicts_with = "no_sandbox")]
|
||||
sandbox: bool,
|
||||
@@ -160,10 +163,16 @@ struct Config {
|
||||
max_tokens: Option<u32>,
|
||||
/// Model for read-only `task` subagents; default: the provider's cheapest tier (Haiku / Luna).
|
||||
explore_model: Option<String>,
|
||||
/// Register the `task` subagent tool (default true; each call still asks the user). `--no-subagents` = off.
|
||||
subagents: Option<bool>,
|
||||
/// Add the `codemode` tool: JS scripts that call the other tools (default false).
|
||||
codemode: Option<bool>,
|
||||
/// Capture the mouse for wheel scrolling (default true; false = terminal selection works without shift).
|
||||
mouse: Option<bool>,
|
||||
/// Where sessions live (default `~/.hx/sessions`); `~` expands. Point at a synced/mounted cloud folder. `HX_SESSIONS_DIR` wins.
|
||||
sessions_dir: Option<String>,
|
||||
/// Prefix session folders with the host name, so machines sharing `sessions_dir` stay apart (default false).
|
||||
sessions_host: Option<bool>,
|
||||
/// Reuse the last model chosen with /model or /provider (default true).
|
||||
remember_model: Option<bool>,
|
||||
/// `/model auto`: tier pins (`fast`, `balanced`, `deep` = model ids) and `down_after`.
|
||||
@@ -236,8 +245,11 @@ impl Config {
|
||||
compact_at: o.compact_at.or(c.compact_at),
|
||||
max_tokens: o.max_tokens.or(c.max_tokens),
|
||||
explore_model: o.explore_model.or(c.explore_model),
|
||||
subagents: o.subagents.or(c.subagents),
|
||||
codemode: o.codemode.or(c.codemode),
|
||||
mouse: o.mouse.or(c.mouse),
|
||||
sessions_dir: o.sessions_dir.or(c.sessions_dir),
|
||||
sessions_host: o.sessions_host.or(c.sessions_host),
|
||||
remember_model: o.remember_model.or(c.remember_model),
|
||||
auto: o.auto.or(c.auto),
|
||||
permissions: o.permissions.or(c.permissions),
|
||||
@@ -585,8 +597,33 @@ impl<H: Hook> Hook for ArcHook<H> {
|
||||
}
|
||||
}
|
||||
|
||||
fn session_dir(cwd: &std::path::Path) -> std::path::PathBuf {
|
||||
hx_core::session::dir(&context::hx_home(), cwd)
|
||||
fn session_dir(cwd: &std::path::Path, cfg: &Config) -> Result<std::path::PathBuf> {
|
||||
let home = context::hx_home();
|
||||
let root = match std::env::var("HX_SESSIONS_DIR")
|
||||
.ok()
|
||||
.or(cfg.sessions_dir.clone())
|
||||
{
|
||||
Some(s) if !s.is_empty() => match s.strip_prefix('~') {
|
||||
Some(r) => std::env::var_os("HOME")
|
||||
.map(std::path::PathBuf::from)
|
||||
.unwrap_or_default()
|
||||
.join(r.trim_start_matches('/')),
|
||||
None => s.into(),
|
||||
},
|
||||
_ => home.join("sessions"),
|
||||
};
|
||||
let host = cfg.sessions_host.unwrap_or(false).then(|| {
|
||||
["HOSTNAME", "HOST", "COMPUTERNAME"]
|
||||
.iter()
|
||||
.find_map(|k| std::env::var(k).ok())
|
||||
.or_else(|| std::fs::read_to_string("/etc/hostname").ok())
|
||||
.map_or("host".into(), |h| h.trim().to_string())
|
||||
});
|
||||
let dir = hx_core::session::dir(&root, cwd, host.as_deref());
|
||||
// fail loud: a silent fallback would leave sessions off the cloud folder
|
||||
std::fs::create_dir_all(&dir)
|
||||
.map_err(|e| anyhow::anyhow!("sessions dir {}: {e}", dir.display()))?;
|
||||
Ok(dir)
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
@@ -704,7 +741,9 @@ async fn main() -> Result<()> {
|
||||
];
|
||||
rows.extend(skill_rows);
|
||||
let mut specs = reg.specs();
|
||||
specs.push(hx_core::subagent::spec());
|
||||
if !cli.no_subagents && cfg.subagents != Some(false) {
|
||||
specs.push(hx_core::subagent::spec());
|
||||
}
|
||||
specs.sort_by_key(|t| {
|
||||
std::cmp::Reverse(serde_json::to_string(t).map_or(0, |s| s.len()))
|
||||
});
|
||||
@@ -904,7 +943,7 @@ async fn main() -> Result<()> {
|
||||
}
|
||||
.unwrap_or_else(|| hx_ai::models::default_for(kind, &models))
|
||||
});
|
||||
let dir = session_dir(&cwd);
|
||||
let dir = session_dir(&cwd, &cfg)?;
|
||||
let query = cli.resume.as_deref().filter(|q| !q.is_empty());
|
||||
let path = match (cli.session, cli.r#continue, query) {
|
||||
_ if acp_id.is_some() => dir.join(format!(
|
||||
@@ -1052,7 +1091,7 @@ async fn main() -> Result<()> {
|
||||
mgr.warm(probe).await;
|
||||
}
|
||||
trace("lens");
|
||||
{
|
||||
if !cli.no_subagents && cfg.subagents != Some(false) {
|
||||
// children get the parent's tools as of now (no `task`, so no recursion)
|
||||
let mut general = agent.tools.clone();
|
||||
general.retain(|n| n != "ask_user" && n != "exit_plan");
|
||||
|
||||
@@ -42,7 +42,12 @@ pub fn question(tool: &str, input: &Value) -> Option<Request> {
|
||||
detail: s("file_path"),
|
||||
rule: String::new(),
|
||||
}),
|
||||
"Grep" | "Glob" | "LS" | "TodoWrite" | "NotebookRead" | "Task" | "Agent" => None,
|
||||
"Grep" | "Glob" | "LS" | "TodoWrite" | "NotebookRead" => None,
|
||||
"Task" | "Agent" => Some(Request {
|
||||
tool: "task".into(),
|
||||
detail: format!("subagent: {}", s("description")),
|
||||
rule: "task:claude".into(),
|
||||
}),
|
||||
t if t.starts_with("mcp__hx__") => None,
|
||||
"WebFetch" => Some(crate::permit::request(
|
||||
"web_fetch",
|
||||
|
||||
@@ -198,7 +198,7 @@ pub fn needs_permit(tool: &str, args: &serde_json::Value) -> bool {
|
||||
match tool {
|
||||
"bash" => !readonly_cmd(a("command").trim()),
|
||||
"read" => secret(a("path")),
|
||||
"web_fetch" => true,
|
||||
"web_fetch" | "task" => true,
|
||||
_ => gated(tool),
|
||||
}
|
||||
}
|
||||
@@ -261,6 +261,25 @@ pub fn request(tool: &str, args: &serde_json::Value) -> Request {
|
||||
rule: format!("web:{host}"),
|
||||
};
|
||||
}
|
||||
if tool == "task" {
|
||||
let kind = args["kind"].as_str().unwrap_or("explore");
|
||||
let ps: Vec<&str> = match args["prompts"].as_array() {
|
||||
Some(a) => a.iter().filter_map(|v| v.as_str()).collect(),
|
||||
None => vec![args["prompt"].as_str().unwrap_or_default()],
|
||||
};
|
||||
let first: String = ps
|
||||
.first()
|
||||
.copied()
|
||||
.unwrap_or_default()
|
||||
.chars()
|
||||
.take(120)
|
||||
.collect();
|
||||
return Request {
|
||||
tool: tool.into(),
|
||||
detail: format!("{} {kind} subagent(s): {first}", ps.len()),
|
||||
rule: format!("task:{kind}"),
|
||||
};
|
||||
}
|
||||
if tool != "bash" {
|
||||
return Request {
|
||||
tool: tool.into(),
|
||||
@@ -467,6 +486,13 @@ mod tests {
|
||||
assert_eq!(bash("go test $(id)").rule, "");
|
||||
assert_eq!(request("edit", &json!({"path": "a.rs"})).rule, "");
|
||||
assert!(gated("bash") && !gated("read"));
|
||||
let t = serde_json::json!({"prompts": ["a", "b"], "kind": "general"});
|
||||
assert!(needs_permit("task", &t));
|
||||
let r = request("task", &t);
|
||||
assert_eq!(
|
||||
(r.rule.as_str(), r.detail.starts_with("2 general")),
|
||||
("task:general", true)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -173,14 +173,18 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// `<hx home>/sessions/<slug of cwd>`.
|
||||
pub fn dir(home: &Path, cwd: &Path) -> PathBuf {
|
||||
let slug: String = cwd
|
||||
.to_string_lossy()
|
||||
/// `<root>/<slug of cwd>`, with `<host>-` in front when `host` is set (shared roots).
|
||||
pub fn dir(root: &Path, cwd: &Path, host: Option<&str>) -> PathBuf {
|
||||
let cwd = cwd.to_string_lossy();
|
||||
let slug: String = host
|
||||
.into_iter()
|
||||
.chain([cwd.trim_matches('/')])
|
||||
.collect::<Vec<_>>()
|
||||
.join("/")
|
||||
.chars()
|
||||
.map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
|
||||
.collect();
|
||||
home.join("sessions").join(slug.trim_matches('-'))
|
||||
root.join(slug.trim_matches('-'))
|
||||
}
|
||||
|
||||
/// A fresh, not yet created session file in `dir` (created on first append).
|
||||
@@ -279,7 +283,7 @@ pub fn list(dir: &Path) -> Vec<Meta> {
|
||||
v
|
||||
}
|
||||
|
||||
/// Sessions of every project under `<hx home>/sessions`, newest first.
|
||||
/// Sessions of every project under the sessions root, newest first.
|
||||
pub fn list_all(root: &Path) -> Vec<Meta> {
|
||||
let mut v: Vec<Meta> = std::fs::read_dir(root)
|
||||
.into_iter()
|
||||
@@ -370,8 +374,12 @@ mod tests {
|
||||
.collect();
|
||||
assert_eq!(t, [("newer", "other"), ("fix parser", "proj")]);
|
||||
assert_eq!(
|
||||
dir(Path::new("/h"), Path::new("/a/b c")),
|
||||
Path::new("/h/sessions/a-b-c")
|
||||
dir(Path::new("/h"), Path::new("/a/b c"), None),
|
||||
Path::new("/h/a-b-c")
|
||||
);
|
||||
assert_eq!(
|
||||
dir(Path::new("/h"), Path::new("/a/b"), Some("box")),
|
||||
Path::new("/h/box-a-b")
|
||||
);
|
||||
let n = new_path(&proj);
|
||||
assert!(n.starts_with(&proj) && !n.exists());
|
||||
|
||||
@@ -96,6 +96,7 @@ pub struct Subs {
|
||||
list: Mutex<Vec<Arc<Sub>>>,
|
||||
/// (child id, event) for the UI; set by interactive frontends
|
||||
pub events: OnceLock<mpsc::UnboundedSender<(usize, Event)>>,
|
||||
watching: std::sync::atomic::AtomicBool,
|
||||
}
|
||||
|
||||
const KEEP: usize = 20;
|
||||
@@ -107,6 +108,36 @@ impl Subs {
|
||||
pub fn get(&self, id: usize) -> Option<Arc<Sub>> {
|
||||
self.list().into_iter().find(|s| s.sh.id == id)
|
||||
}
|
||||
/// Abort every running child (also those continued in the background after their task ended).
|
||||
pub fn abort_all(&self) {
|
||||
for s in self.list() {
|
||||
if s.sh.status() == Status::Running {
|
||||
s.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn any_running(&self) -> bool {
|
||||
self.list().iter().any(|s| s.sh.status() == Status::Running)
|
||||
}
|
||||
/// Once per session: every parent abort reaches all running children. The parent flag resets
|
||||
/// after each run, so the loop re-arms.
|
||||
fn watch(&self, state: &Arc<crate::State>) {
|
||||
let Some(mut rx) = state.abort.get().cloned() else {
|
||||
return;
|
||||
};
|
||||
if self.watching.swap(true, Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
let st = state.clone();
|
||||
tokio::spawn(async move {
|
||||
while rx.wait_for(|a| *a).await.is_ok() {
|
||||
st.subs.abort_all();
|
||||
if rx.wait_for(|a| !*a).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
fn add(&self, s: Arc<Sub>) {
|
||||
let mut l = self.list.lock().unwrap_or_else(|e| e.into_inner());
|
||||
l.push(s);
|
||||
@@ -252,7 +283,7 @@ impl Task {
|
||||
pub fn spec() -> ToolSpec {
|
||||
ToolSpec {
|
||||
name: "task".into(),
|
||||
description: "Run a subagent in a fresh context; you get back only its final answer. kind=explore (default): read-only research on a cheaper model; use it for searching/reading that would fill your context (many files or >10k tokens). kind=general: same tools as you, may edit. The subagent sees nothing of this conversation: make every prompt self-contained. You are blocked until it answers, so a single task you then wait on only pays off when the search would put >10k tokens in your context; otherwise do it yourself. Prefer splitting work into 2+ independent subtasks: pass `prompts` (array) or several task calls in one turn, they run in parallel. Not for small lookups.".into(),
|
||||
description: "Run a subagent in a fresh context; you get back only its final answer. The user is asked to approve every call: use it only when the user asked for subagents or parallel work, or when a search would clearly put >10k tokens in your context. Do ordinary discovery (read, grep, lsp, bash) yourself in this session. kind=explore (default): read-only research on a cheaper model. kind=general: same tools as you, may edit. The subagent sees nothing of this conversation: make every prompt self-contained. You are blocked until it answers. For 2+ independent subtasks pass `prompts` (array); they run in parallel.".into(),
|
||||
input_schema: json!({"type":"object","properties":{
|
||||
"prompt":{"type":"string"},
|
||||
"prompts":{"type":"array","items":{"type":"string"},"description":"several independent subtasks: one subagent each, run in parallel, answers returned numbered"},
|
||||
@@ -357,23 +388,12 @@ impl Task {
|
||||
sem: self.sem.clone(),
|
||||
});
|
||||
cx.state.subs.add(sub.clone());
|
||||
// parent abort stops the child
|
||||
let bridge = cx.state.abort.get().cloned().map(|mut rx| {
|
||||
let s = sub.clone();
|
||||
tokio::spawn(async move {
|
||||
if rx.wait_for(|a| *a).await.is_ok() {
|
||||
s.abort();
|
||||
}
|
||||
})
|
||||
});
|
||||
cx.state.subs.watch(&cx.state);
|
||||
// waiting for a slot may have outlasted an abort
|
||||
if aborted() {
|
||||
sub.abort();
|
||||
}
|
||||
let r = sub.drive(prompt.to_string()).await;
|
||||
if let Some(b) = bridge {
|
||||
b.abort();
|
||||
}
|
||||
let u = sh.usage.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
||||
let tok = u.input_tokens + u.cache_read_tokens + u.cache_write_tokens + u.output_tokens;
|
||||
let stats = format!(
|
||||
@@ -682,4 +702,41 @@ mod tests {
|
||||
assert_eq!(reqs[1].messages.len(), 3);
|
||||
assert_eq!(cx.state.sub_usage.lock().unwrap().input_tokens, 2000);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn parent_abort_reaches_background_child() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let p = Arc::new(Script(
|
||||
Mutex::new(vec![text("a"), call("read", json!({}))]),
|
||||
Default::default(),
|
||||
));
|
||||
let t = Task::new(
|
||||
role(&p, "cheap"),
|
||||
role(&p, "main"),
|
||||
d.path().join("s.sub"),
|
||||
2,
|
||||
);
|
||||
let (parent, h) = Agent::new(
|
||||
p.clone(),
|
||||
Registry::default(),
|
||||
Session::open(d.path().join("p.jsonl")).unwrap(),
|
||||
ToolCtx {
|
||||
cwd: d.path().into(),
|
||||
state: Default::default(),
|
||||
},
|
||||
);
|
||||
let cx = parent.cx.clone();
|
||||
t.call(json!({"prompt":"one"}), &cx).await;
|
||||
let sub = cx.state.subs.get(1).unwrap();
|
||||
sub.prompt("two".into());
|
||||
assert!(cx.state.subs.any_running());
|
||||
h.abort();
|
||||
for _ in 0..100 {
|
||||
if sub.sh.status() == Status::Aborted {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
|
||||
}
|
||||
assert_eq!(sub.sh.status(), Status::Aborted);
|
||||
}
|
||||
}
|
||||
@@ -1241,6 +1241,8 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option<String> {
|
||||
if app.busy {
|
||||
app.queue.clear();
|
||||
abort.abort();
|
||||
} else if app.state.subs.any_running() {
|
||||
app.state.subs.abort_all();
|
||||
} else if app.ed.buf.is_empty() {
|
||||
app.quit = true;
|
||||
} else {
|
||||
@@ -1254,6 +1256,7 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option<String> {
|
||||
app.queue.clear();
|
||||
abort.abort();
|
||||
}
|
||||
KeyCode::Esc if app.state.subs.any_running() => app.state.subs.abort_all(),
|
||||
KeyCode::Char('o') if ctrl => app.expanded = !app.expanded,
|
||||
KeyCode::Esc if app.panel.is_some() => app.panel = None,
|
||||
KeyCode::Char('j') if ctrl => app.ed.insert("\n"),
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@
|
||||
packages = [
|
||||
pkgs.git
|
||||
pkgs.stdenv.cc
|
||||
];
|
||||
] ++ lib.optional pkgs.stdenv.hostPlatform.isLinux pkgs.bubblewrap;
|
||||
|
||||
languages.rust.enable = true;
|
||||
}
|
||||
@@ -31,8 +31,12 @@
|
||||
# ponytail: tests skipped (need git/network); enable when hermetic.
|
||||
doCheck = false;
|
||||
# rustls may build aws-lc-sys (cmake) depending on feature set.
|
||||
nativeBuildInputs = [ pkgs.cmake pkgs.perl ];
|
||||
nativeBuildInputs = [ pkgs.cmake pkgs.perl ] ++ pkgs.lib.optionals pkgs.stdenv.hostPlatform.isLinux [ pkgs.makeWrapper ];
|
||||
dontUseCmakeConfigure = true;
|
||||
# bubblewrap sandbox runtime dependency (Linux only).
|
||||
postInstall = pkgs.lib.optionalString pkgs.stdenv.hostPlatform.isLinux ''
|
||||
wrapProgram $out/bin/hx --suffix PATH : ${pkgs.lib.makeBinPath [ pkgs.bubblewrap ]}
|
||||
'';
|
||||
meta = {
|
||||
description = "Minimal Rust coding agent using existing subscriptions";
|
||||
license = pkgs.lib.licenses.unlicense;
|
||||
@@ -67,7 +71,7 @@
|
||||
|
||||
devShells = forAll (pkgs: {
|
||||
default = pkgs.mkShell {
|
||||
packages = with pkgs; [ cargo rustc clippy rustfmt rust-analyzer git ];
|
||||
packages = with pkgs; [ cargo rustc clippy rustfmt rust-analyzer git ] ++ pkgs.lib.optional pkgs.stdenv.hostPlatform.isLinux pkgs.bubblewrap;
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user