Files
hx/crates/hx-core/src/nudge.rs
T

104 lines
3.2 KiB
Rust

//! 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);
}
}