Batching nudges: parallel-calls prompt line, codemode hint, tool-call count
This commit is contained in:
1 parent
8b5d24436f
commit
a30b3a3e73
5 files changed
+120
-4
No files matched your search
@@ -793,7 +793,13 @@ async fn main() -> Result<()> {
|
||||
// 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);
|
||||
agent.append_system(
|
||||
"\n\nUse `codemode` for 3+ independent reads/searches or to filter large output before it reaches you.",
|
||||
);
|
||||
}
|
||||
agent.bus.add(hx_core::nudge::BatchNudge::new(
|
||||
cfg.codemode.unwrap_or(false),
|
||||
));
|
||||
let specs = command_specs(&mcp, &cwd, &models, &kinds);
|
||||
trace("ready");
|
||||
if cli.mode == Mode::Rpc {
|
||||
|
||||
@@ -8,6 +8,7 @@ Use the tools to read, edit and run code. Read files before editing them. Keep a
|
||||
- Inspect with the tools, not scripts: `read` for files, `rg` to search text, `fd` or `find` to list files, `ls`/`tree` for directories.\n\
|
||||
- Never use node, python, perl, sed or awk to look at files or data; they need user approval every time. Read-only commands (ls cat head tail rg fd find grep wc jq sort, git status/log/diff/show) run without a prompt, also piped into each other.\n\
|
||||
- One simple command per call: no `;`, `&&`, redirects, `$()`. Those need approval too.\n\
|
||||
- Issue independent tool calls together in one turn; they run in parallel.\n\
|
||||
- Script only when the task needs it (build, test, edit), not to explore.";
|
||||
|
||||
const CONTEXT_FILES: &[&str] = &["AGENTS.md", "CLAUDE.md"];
|
||||
|
||||
@@ -9,6 +9,7 @@ pub mod herdr;
|
||||
pub mod hook;
|
||||
mod mask;
|
||||
pub mod memory;
|
||||
pub mod nudge;
|
||||
pub mod permit;
|
||||
pub mod session;
|
||||
pub mod stats;
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
//! Cheap nudge: after `STREAK` consecutive turns that each made one lone read-only call, remind the
|
||||
//! model once that independent reads can be batched (parallel native calls, or `codemode`).
|
||||
//! Injected at turn end, so the cached prefix is untouched.
|
||||
//! ponytail: name/first-word heuristic; swap for per-tool metadata if tools grow a read-only flag.
|
||||
|
||||
use crate::hook::{Event, Hook, HookAction};
|
||||
use async_trait::async_trait;
|
||||
use std::sync::Mutex;
|
||||
|
||||
const STREAK: u32 = 3;
|
||||
const READ_ONLY: &[&str] = &[
|
||||
"read", "rg", "fd", "find", "ls", "tree", "cat", "head", "tail", "grep", "wc",
|
||||
];
|
||||
|
||||
#[derive(Default)]
|
||||
struct S {
|
||||
calls: Vec<bool>, // per call this turn: read-only?
|
||||
streak: u32,
|
||||
}
|
||||
|
||||
pub struct BatchNudge {
|
||||
codemode: bool,
|
||||
s: Mutex<S>,
|
||||
}
|
||||
|
||||
impl BatchNudge {
|
||||
pub fn new(codemode: bool) -> Self {
|
||||
Self {
|
||||
codemode,
|
||||
s: Mutex::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_only(name: &str, args: &serde_json::Value) -> bool {
|
||||
match name {
|
||||
"read" => true,
|
||||
"bash" => args["command"]
|
||||
.as_str()
|
||||
.and_then(|c| c.split_whitespace().next())
|
||||
.is_some_and(|w| READ_ONLY.contains(&w)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Hook for BatchNudge {
|
||||
async fn on(&self, ev: &Event) -> HookAction {
|
||||
let mut s = self.s.lock().unwrap_or_else(|e| e.into_inner());
|
||||
match ev {
|
||||
Event::ToolCall { name, args, .. } => s.calls.push(read_only(name, args)),
|
||||
Event::TurnEnd => {
|
||||
let lone_read = s.calls == [true];
|
||||
s.calls.clear();
|
||||
s.streak = if lone_read { s.streak + 1 } else { 0 };
|
||||
if s.streak == STREAK {
|
||||
s.streak = 0;
|
||||
return HookAction::Inject(if self.codemode {
|
||||
"hint: several single reads in a row. Batch independent reads/searches in one turn (parallel tool calls), or use `codemode` with Promise.all and filter the output.".into()
|
||||
} else {
|
||||
"hint: several single reads in a row. Emit independent reads/searches as parallel tool calls in one turn.".into()
|
||||
});
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
HookAction::Continue
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
async fn turn(h: &BatchNudge, name: &str, args: serde_json::Value) -> HookAction {
|
||||
h.on(&Event::ToolCall {
|
||||
id: "i".into(),
|
||||
name: name.into(),
|
||||
args,
|
||||
})
|
||||
.await;
|
||||
h.on(&Event::TurnEnd).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn nudges_after_streak_then_resets() {
|
||||
let h = BatchNudge::new(true);
|
||||
assert_eq!(turn(&h, "read", json!({})).await, HookAction::Continue);
|
||||
assert_eq!(
|
||||
turn(&h, "bash", json!({"command": "rg foo"})).await,
|
||||
HookAction::Continue
|
||||
);
|
||||
assert!(
|
||||
matches!(turn(&h, "read", json!({})).await, HookAction::Inject(m) if m.contains("codemode"))
|
||||
);
|
||||
// a write breaks the streak
|
||||
turn(&h, "read", json!({})).await;
|
||||
turn(&h, "edit", json!({})).await;
|
||||
turn(&h, "read", json!({})).await;
|
||||
assert_eq!(turn(&h, "read", json!({})).await, HookAction::Continue);
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ 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::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const MEM: usize = 256 << 20;
|
||||
@@ -177,6 +177,7 @@ async fn run(
|
||||
stop: Arc<AtomicBool>,
|
||||
) -> ToolResult {
|
||||
let t0 = Instant::now();
|
||||
let ncalls = Arc::new(AtomicUsize::new(0));
|
||||
let fail = |e: String| ToolResult::err(format!("Script failed\n\nScript error: {e}"));
|
||||
let rt = match AsyncRuntime::new() {
|
||||
Ok(r) => r,
|
||||
@@ -206,11 +207,12 @@ async fn run(
|
||||
let started = ctx
|
||||
.with(|ctx| {
|
||||
let g = ctx.globals();
|
||||
let (r2, n2, c2) = (reg.clone(), names.clone(), cx.clone());
|
||||
let (r2, n2, c2, k2) = (reg.clone(), names.clone(), cx.clone(), ncalls.clone());
|
||||
let call = Function::new(
|
||||
ctx.clone(),
|
||||
Async(move |name: String, args: String| {
|
||||
let (reg, names, cx) = (r2.clone(), n2.clone(), c2.clone());
|
||||
k2.fetch_add(1, Ordering::Relaxed);
|
||||
async move {
|
||||
let real = names.get(&name).cloned().unwrap_or(name);
|
||||
let r = match serde_json::from_str::<Value>(&args) {
|
||||
@@ -314,10 +316,13 @@ async fn run(
|
||||
f.display()
|
||||
);
|
||||
}
|
||||
let n_calls = ncalls.load(Ordering::Relaxed);
|
||||
match err {
|
||||
None => ToolResult::ok(format!("Script completed in {ms}ms\n\n{body}")),
|
||||
None => ToolResult::ok(format!(
|
||||
"Script completed in {ms}ms, {n_calls} tool calls\n\n{body}"
|
||||
)),
|
||||
Some(e) => ToolResult::err(format!(
|
||||
"Script failed after {ms}ms\n\n{body}Script error: {e}"
|
||||
"Script failed after {ms}ms, {n_calls} tool calls\n\n{body}Script error: {e}"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user