Merge pull request 'codemode: JS scripts that call tools in a QuickJS sandbox' (#141) from feat/codemode into main

This commit was merged in pull request #141.
This commit is contained in:
hermes committed 2026-10-09 10:51:23 +00:00
commit e4694e126b
7 files changed
+560 -2

No files matched your search

Generated
+121 -1
View File
@@ -82,6 +82,17 @@ dependencies = [
"num-traits",
]
[[package]]
name = "async-lock"
version = "3.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311"
dependencies = [
"event-listener",
"event-listener-strategy",
"pin-project-lite",
]
[[package]]
name = "async-trait"
version = "0.1.92"
@@ -366,6 +377,15 @@ dependencies = [
"unicode-segmentation",
]
[[package]]
name = "convert_case"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1af709f1f33454bf52eadfc8c78b3b9ef9cb26fb54d16dc9cd9a7299f899fd1b"
dependencies = [
"unicode-segmentation",
]
[[package]]
name = "core-foundation"
version = "0.10.1"
@@ -549,7 +569,7 @@ version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"
dependencies = [
"convert_case",
"convert_case 0.10.0",
"proc-macro2",
"quote",
"rustc_version",
@@ -634,6 +654,25 @@ dependencies = [
"num-traits",
]
[[package]]
name = "event-listener"
version = "5.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2"
dependencies = [
"pin-project-lite",
]
[[package]]
name = "event-listener-strategy"
version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93"
dependencies = [
"event-listener",
"pin-project-lite",
]
[[package]]
name = "eventsource-stream"
version = "0.2.3"
@@ -1045,8 +1084,10 @@ version = "0.1.0"
dependencies = [
"async-trait",
"base64 0.23.1",
"futures",
"hx-ai",
"hx-core",
"rquickjs",
"serde_json",
"similar",
"tempfile",
@@ -1810,6 +1851,15 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
[[package]]
name = "proc-macro-crate"
version = "3.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"
dependencies = [
"toml_edit",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
@@ -2077,6 +2127,15 @@ version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
[[package]]
name = "relative-path"
version = "2.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2a073568cd8b9c4825429d3e9fc5f52851b4f97cc1348800689408921e6b8f8"
dependencies = [
"serde",
]
[[package]]
name = "reqwest"
version = "0.13.5"
@@ -2133,6 +2192,52 @@ dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "rquickjs"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a0a22bf72f515cc4189dd7c63d016f6de92a11eee98ddf7dd64794198f6eb34e"
dependencies = [
"rquickjs-core",
"rquickjs-macro",
]
[[package]]
name = "rquickjs-core"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6657979a24d543e5fc66f32cef2f47ca82ce8eb55cec5f7d59a12b7b570bbf24"
dependencies = [
"async-lock",
"hashbrown 0.17.1",
"relative-path",
"rquickjs-sys",
]
[[package]]
name = "rquickjs-macro"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0a2ea9adb03b669c933482ff740b683cd36be7cef23891657a8ccb850401d286"
dependencies = [
"convert_case 0.12.0",
"indexmap",
"proc-macro-crate",
"proc-macro2",
"quote",
"rquickjs-core",
"syn 3.0.6",
]
[[package]]
name = "rquickjs-sys"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cee271d0eeba64f0915b846cb7ae02e16faf3dfdffdca91731101d9d30fe3423"
dependencies = [
"cc",
]
[[package]]
name = "rustc-hash"
version = "2.1.3"
@@ -2816,6 +2921,18 @@ dependencies = [
"serde_core",
]
[[package]]
name = "toml_edit"
version = "0.25.15+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1340ea94a5856333492c9064b02c778b191dd2c853778d9609debdcdfea3a614"
dependencies = [
"indexmap",
"toml_datetime",
"toml_parser",
"winnow",
]
[[package]]
name = "toml_parser"
version = "1.1.3+spec-1.1.0"
@@ -3327,6 +3444,9 @@ name = "winnow"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"
dependencies = [
"memchr",
]
[[package]]
name = "wit-bindgen"
+1
View File
@@ -51,6 +51,7 @@ provider = "claude" # or "codex"
# compact_at = 900000 # default: 90% of the model's context window
max_tokens = 16384
# mouse = true # wheel scrolling; false keeps terminal text selection
# codemode = false # add the `codemode` tool: JS scripts that call other tools in a sandbox
# explore_model = "claude-haiku-4-5" # model for read-only `task` subagents; default: cheapest tier of the provider
# system_prompt = "..." # replaces built-in prompt; AGENTS.md still appended
+12
View File
@@ -99,6 +99,8 @@ struct Config {
max_tokens: Option<u32>,
/// Model for read-only `task` subagents; default: the provider's cheapest tier (Haiku / Luna).
explore_model: Option<String>,
/// 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>,
/// Reuse the last model chosen with /model or /provider (default true).
@@ -150,6 +152,7 @@ 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),
codemode: o.codemode.or(c.codemode),
mouse: o.mouse.or(c.mouse),
remember_model: o.remember_model.or(c.remember_model),
permissions: o.permissions.or(c.permissions),
@@ -409,6 +412,10 @@ async fn main() -> Result<()> {
let mut reg = hx_tools::registry();
hub.register(&mut reg);
reg.add(hx_lens::LspTool::new(mgr.clone()));
if cfg.codemode.unwrap_or(false) {
let cm = hx_tools::codemode::Codemode::new(&reg);
reg.add(cm);
}
let full = context::system_prompt(cfg.system_prompt.as_deref(), &home, &cwd);
let base = cfg
.system_prompt
@@ -742,6 +749,11 @@ async fn main() -> Result<()> {
}
agent.tools.add(task);
}
if cfg.codemode.unwrap_or(false) {
// snapshot after every other tool (MCP, lens, task); codemode itself is not callable inside
let cm = hx_tools::codemode::Codemode::new(&agent.tools);
agent.tools.add(cm);
}
let specs = command_specs(&mcp, &cwd, &models, &kinds);
trace("ready");
if cli.mode == Mode::Rpc {
+2
View File
@@ -7,8 +7,10 @@ license.workspace = true
[dependencies]
async-trait = "0.1.92"
base64 = "0.23.1"
futures = "0.3.34"
hx-ai = { version = "0.1.0", path = "../hx-ai" }
hx-core = { version = "0.1.0", path = "../hx-core" }
rquickjs = { version = "0.14.0", features = ["futures", "macro"] }
serde_json = "1.0.151"
similar = "3.2.0"
tokio = { version = "1.53.1", features = ["process", "time", "io-util", "rt", "macros"] }
+417
View File
@@ -0,0 +1,417 @@
//! `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
//! `models`/`image`). Inner calls go through `Registry::call`, so the permission gate and the
//! shared `State` (read-before-edit, edit log) apply as for direct calls.
//! ponytail: inner calls emit no agent events (TUI shows only the codemode call); add a bus
//! handle on `ToolCtx` if users want to see them live.
use super::{head_tail, spec};
use async_trait::async_trait;
use hx_ai::ToolSpec;
use hx_core::tool::{Registry, Tool, ToolCtx, ToolResult};
use rquickjs::{AsyncContext, AsyncRuntime, Function, function::Async};
use serde_json::{Value, json};
use std::collections::BTreeMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
const MEM: usize = 256 << 20;
/// ~10k tokens of output; the rest goes to a temp file.
const MAX_OUT: usize = 40_000;
const HEAD_OUT: usize = 10_000;
/// Tool listing budget in the description (~3k tokens).
const LIST_BUDGET: usize = 12_000;
const DEFAULT_TIMEOUT_S: u64 = 300;
const PRELUDE: &str = r#"
globalThis.__out = []; globalThis.__con = [];
const __s = (v) => typeof v === "string" ? v : JSON.stringify(v, null, 1);
globalThis.text = (v) => { __out.push(__s(v)); };
globalThis.console = Object.fromEntries(["log","info","warn","error","debug"].map(k =>
[k, (...a) => { __con.push(a.map(__s).join(" ")); }]));
class ToolError extends Error {}
globalThis.ToolError = ToolError;
globalThis.tools = new Proxy({}, { get: (_, n) => async (a) => {
const r = JSON.parse(await __call(String(n), JSON.stringify(a ?? {})));
if (r.error) throw new ToolError(r.content);
return r.content;
}});
globalThis.describeTool = async (n) => __describe(String(n)) || undefined;
"#;
pub struct Codemode {
reg: Arc<Registry>,
/// JS identifier -> real tool name
names: Arc<BTreeMap<String, String>>,
desc: String,
}
fn ident(n: &str) -> String {
n.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '_' || c == '$' {
c
} else {
'_'
}
})
.collect()
}
/// `{path: string, limit?: integer}` from a JSON schema.
fn sig(schema: &Value) -> String {
let req: Vec<&str> = schema["required"]
.as_array()
.into_iter()
.flatten()
.filter_map(Value::as_str)
.collect();
let props = schema["properties"].as_object();
let args: Vec<String> = props
.into_iter()
.flatten()
.map(|(k, v)| {
let t = v["type"].as_str().unwrap_or("any");
let o = if req.contains(&k.as_str()) { "" } else { "?" };
format!("{k}{o}: {t}")
})
.collect();
format!("{{{}}}", args.join(", "))
}
impl Codemode {
/// Snapshot of `reg` at construction: tools added later (and codemode itself) are not callable.
pub fn new(reg: &Registry) -> Self {
let mut names = BTreeMap::new();
let mut list = String::new();
let mut hidden = 0;
for s in reg.specs() {
let id = ident(&s.name);
let first = s.description.split(". ").next().unwrap_or("").trim();
let line = format!("- tools.{id}({}): {first}\n", sig(&s.input_schema));
if list.len() + line.len() <= LIST_BUDGET {
list.push_str(&line);
} else {
hidden += 1;
}
names.insert(id, s.name);
}
if hidden > 0 {
list.push_str(&format!(
"- ... {hidden} more; `await describeTool(name)` gives the schema\n"
));
}
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\
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\
Tools:\n{list}"
);
Self {
reg: Arc::new(reg.clone()),
names: Arc::new(names),
desc,
}
}
}
#[async_trait]
impl Tool for Codemode {
fn spec(&self) -> ToolSpec {
spec(
"codemode",
&self.desc,
json!({"type":"object","properties":{
"script":{"type":"string","description":"JavaScript async function body"},
"timeout":{"type":"integer","description":"seconds, default 300"}},
"required":["script"]}),
)
}
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
let script = a["script"].as_str().unwrap_or_default().to_string();
let secs = a["timeout"]
.as_u64()
.unwrap_or(DEFAULT_TIMEOUT_S)
.clamp(1, 3600);
// Dropping this future (agent abort) interrupts the script.
struct Stop(Arc<AtomicBool>);
impl Drop for Stop {
fn drop(&mut self) {
self.0.store(true, Ordering::Relaxed);
}
}
let stop = Stop(Arc::default());
let (tx, rx) = tokio::sync::oneshot::channel();
let (reg, names, cx, flag) = (
self.reg.clone(),
self.names.clone(),
cx.clone(),
stop.0.clone(),
);
// QuickJS values are !Send: run the script on its own thread with a local runtime.
std::thread::spawn(move || {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build();
let r = match rt {
Ok(rt) => rt.block_on(run(script, secs, reg, names, cx, flag)),
Err(e) => ToolResult::err(format!("runtime: {e}")),
};
let _ = tx.send(r);
});
rx.await
.unwrap_or_else(|_| ToolResult::err("codemode thread panicked"))
}
}
/// (settled ok?/error, text items, console lines)
type Outcome = (Option<(bool, String)>, Vec<String>, Vec<String>);
async fn run(
script: String,
secs: u64,
reg: Arc<Registry>,
names: Arc<BTreeMap<String, String>>,
cx: ToolCtx,
stop: Arc<AtomicBool>,
) -> ToolResult {
let t0 = Instant::now();
let fail = |e: String| ToolResult::err(format!("Script failed\n\nScript error: {e}"));
let rt = match AsyncRuntime::new() {
Ok(r) => r,
Err(e) => return fail(e.to_string()),
};
rt.set_memory_limit(MEM).await;
rt.set_max_stack_size(1 << 20).await;
let deadline = t0 + Duration::from_secs(secs);
let timed_out = Arc::new(AtomicBool::new(false));
let to = timed_out.clone();
let stop1 = stop.clone();
rt.set_interrupt_handler(Some(Box::new(move || {
let late = Instant::now() > deadline;
to.store(late, Ordering::Relaxed);
late || stop1.load(Ordering::Relaxed)
})))
.await;
let ctx = match AsyncContext::full(&rt).await {
Ok(c) => c,
Err(e) => return fail(e.to_string()),
};
let wrapped = format!(
"{PRELUDE}\nglobalThis.__done = undefined;\n(async () => {{\n{script}\n}})().then(\
(v) => {{ if (v !== undefined) __out.push(__s(v)); globalThis.__done = {{ ok: true }}; }},\
(e) => {{ globalThis.__done = {{ ok: false, err: e instanceof Error ? `${{e.name}}: ${{e.message}}` : __s(e) }}; }});"
);
let started = ctx
.with(|ctx| {
let g = ctx.globals();
let (r2, n2, c2) = (reg.clone(), names.clone(), cx.clone());
let call = Function::new(
ctx.clone(),
Async(move |name: String, args: String| {
let (reg, names, cx) = (r2.clone(), n2.clone(), c2.clone());
async move {
let real = names.get(&name).cloned().unwrap_or(name);
let r = match serde_json::from_str::<Value>(&args) {
Ok(a) => reg.call(&real, a, &cx).await,
Err(e) => ToolResult::err(format!("bad arguments: {e}")),
};
json!({"content": r.content, "error": r.is_error}).to_string()
}
}),
).map_err(|e| e.to_string())?;
g.set("__call", call).map_err(|e| e.to_string())?;
let describe = Function::new(ctx.clone(), move |name: String| -> String {
let real = names.get(&name).cloned().unwrap_or(name);
reg.get(&real)
.map(|t| {
let s = t.spec();
json!({"name": s.name, "description": s.description, "input_schema": s.input_schema}).to_string()
})
.unwrap_or_default()
}).map_err(|e| e.to_string())?;
g.set("__describe", describe).map_err(|e| e.to_string())?;
ctx.eval::<(), _>(wrapped.as_str()).map_err(|e| {
let ex = ctx.catch();
ex.as_exception()
.map(|x| x.to_string())
.unwrap_or_else(|| e.to_string())
})
})
.await;
if let Err(e) = started {
if timed_out.load(Ordering::Relaxed) {
return fail(format!("timed out after {secs}s"));
}
return fail(e);
}
// The interrupt handler only fires while JS runs; also bound time spent awaiting tools.
let stop2 = stop.clone();
let watch = async move {
while !stop2.load(Ordering::Relaxed) && Instant::now() < deadline {
tokio::time::sleep(Duration::from_millis(100)).await;
}
};
tokio::select! {
_ = rt.idle() => {}
_ = watch => timed_out.store(Instant::now() >= deadline, Ordering::Relaxed),
}
let res = ctx
.with(|ctx| -> rquickjs::Result<Outcome> {
let g = ctx.globals();
let done: Option<rquickjs::Object> = g.get("__done")?;
let done = match done {
Some(d) => Some((
d.get::<_, bool>("ok")?,
d.get::<_, Option<String>>("err")?.unwrap_or_default(),
)),
None => None,
};
Ok((done, g.get("__out")?, g.get("__con")?))
})
.await;
let ms = t0.elapsed().as_millis();
let (done, out, con) = match res {
Ok(x) => x,
Err(e) => return fail(e.to_string()),
};
let mut body = String::new();
let n = out.len();
for (i, t) in out.iter().enumerate() {
if n > 1 {
body.push_str(&format!("==> text {}/{n} <==\n", i + 1));
}
body.push_str(t);
body.push('\n');
}
if !con.is_empty() {
body.push_str(&format!(
"<console_output>\n{}\n</console_output>\n",
con.join("\n")
));
}
let err = match done {
Some((true, _)) => None,
Some((false, e)) => Some(e),
None if timed_out.load(Ordering::Relaxed) => Some(format!("timed out after {secs}s")),
None => Some(
"script never finished (awaited a promise that cannot settle, or was interrupted)"
.into(),
),
};
let (mut body, cut) = head_tail(&body, MAX_OUT, HEAD_OUT);
if cut > 0 {
let f = std::env::temp_dir().join(format!(
"hx-codemode-{}-{}.txt",
std::process::id(),
t0.elapsed().as_nanos()
));
let full: String = out.join("\n") + "\n" + &con.join("\n");
let _ = std::fs::write(&f, full);
body = format!(
"[truncated {cut} bytes; full output: {}]\n{body}",
f.display()
);
}
match err {
None => ToolResult::ok(format!("Script completed in {ms}ms\n\n{body}")),
Some(e) => ToolResult::err(format!(
"Script failed after {ms}ms\n\n{body}Script error: {e}"
)),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn cx(dir: &std::path::Path) -> ToolCtx {
ToolCtx {
cwd: dir.into(),
state: Default::default(),
}
}
async fn go(script: &str) -> ToolResult {
let d = tempfile::tempdir().unwrap();
std::fs::write(d.path().join("a.txt"), "alpha\nbeta\n").unwrap();
let cm = Codemode::new(&crate::registry());
cm.call(json!({"script": script, "timeout": 5}), &cx(d.path()))
.await
}
#[tokio::test]
async fn calls_tools_in_parallel_and_filters() {
let r = go(r#"
const [a, b] = await Promise.all([
tools.read({path: "a.txt"}),
tools.bash({command: "echo hi"}),
]);
console.log("n", 2);
text(a.split("\n").filter(l => l.includes("beta")));
return b.trim();
"#)
.await;
assert!(!r.is_error, "{}", r.content);
assert!(r.content.starts_with("Script completed"), "{}", r.content);
assert!(r.content.contains("==> text 1/2 <=="), "{}", r.content);
assert!(
r.content.contains("beta") && r.content.contains("hi"),
"{}",
r.content
);
assert!(!r.content.contains("alpha"), "{}", r.content);
assert!(
r.content.contains("<console_output>\nn 2\n"),
"{}",
r.content
);
}
#[tokio::test]
async fn tool_errors_throw_and_scripts_fail_cleanly() {
let r = go(r#"
try { await tools.bash({command: "exit 3"}); } catch (e) { text("caught " + (e instanceof ToolError)); }
text("partial");
throw new Error("boom");
"#)
.await;
assert!(r.is_error);
assert!(r.content.contains("caught true"), "{}", r.content);
assert!(r.content.contains("partial"), "{}", r.content);
assert!(
r.content.contains("Script error: Error: boom"),
"{}",
r.content
);
let r = go("await tools.nope({});").await;
assert!(r.content.contains("unknown tool `nope`"), "{}", r.content);
let r = go("this is not js").await;
assert!(
r.is_error && r.content.contains("expecting"),
"{}",
r.content
);
}
#[tokio::test]
async fn hangs_and_loops_end() {
let r = go("await new Promise(() => {});").await;
assert!(r.content.contains("never finished"), "{}", r.content);
let r = go("await tools.bash({command: 'sleep 30'});").await;
assert!(r.content.contains("timed out after 5s"), "{}", r.content);
let r = go("while (true) {}").await;
assert!(r.content.contains("timed out after 5s"), "{}", r.content);
}
#[test]
fn description_lists_tools_with_signatures() {
let d = Codemode::new(&crate::registry()).spec().description;
assert!(
d.contains("tools.bash({command: string, timeout?: integer})"),
"{d}"
);
assert_eq!(ident("mcp__dev-radius__search"), "mcp__dev_radius__search");
}
}
+2
View File
@@ -1,5 +1,7 @@
//! Built-in tools: read, write, edit, bash.
pub mod codemode;
use async_trait::async_trait;
use hx_ai::ToolSpec;
use hx_core::tool::{Registry, Tool, ToolCtx, ToolResult};
+5 -1
View File
@@ -7,7 +7,11 @@
}:
{
packages = [ pkgs.git ];
# stdenv.cc: C compiler for rquickjs-sys (QuickJS); gcc on Linux, clang on macOS
packages = [
pkgs.git
pkgs.stdenv.cc
];
languages.rust.enable = true;
}