use super::*;
const MAX_CONTEXT: usize = 8000;
#[derive(Debug, PartialEq)]
pub enum Format {
Json,
Text,
Silent,
}
pub struct Event {
pub situation: String,
pub cwd: Option<String>,
pub format: Format,
pub session: Option<String>,
}
fn first_str<'a>(v: &'a Json, keys: &[&str]) -> Option<&'a str> {
keys.iter()
.filter_map(|k| v.get(k).and_then(Json::as_str))
.find(|s| !s.trim().is_empty())
}
pub fn parse(input: &str) -> Option<Event> {
let event = parse_json(input).ok()?;
let name = first_str(&event, &["tool_name", "toolName"])?;
let args = event.get("tool_input").or_else(|| event.get("toolArgs"));
let reparsed;
let args = match args {
Some(Json::Str(raw)) => {
reparsed = parse_json(raw)
.unwrap_or_else(|_| Json::Obj(vec![("command".into(), Json::Str(raw.clone()))]));
Some(&reparsed)
}
other => other,
};
let target = args
.and_then(|a| {
first_str(
a,
&["command", "cmd", "file_path", "filePath", "path", "pattern", "url", "query"],
)
})
.unwrap_or("");
if target.is_empty() {
return None;
}
let hook = first_str(&event, &["hook_event_name"]).unwrap_or("");
let format = if hook == "BeforeTool" || event.get("toolName").is_some() {
Format::Silent
} else {
Format::Json
};
Some(Event {
situation: format!("tool_{} {target}", name.to_lowercase()),
cwd: event.get("cwd").and_then(Json::as_str).map(str::to_owned),
format,
session: first_str(&event, &["session_id", "sessionId"]).and_then(session::clean),
})
}
pub fn render_with(lesson: &str, note: Option<&str>, format: &Format) -> String {
let mut text = if lesson.trim().is_empty() {
String::new()
} else {
format!("Instinct tripwire (advisory, nothing is blocked): a saved lesson fits this action.\n{lesson}")
};
if let Some(n) = note {
if !text.is_empty() {
text.push('\n');
}
text.push_str(n);
}
if text.len() > MAX_CONTEXT {
let mut end = MAX_CONTEXT;
while !text.is_char_boundary(end) {
end -= 1;
}
text.truncate(end);
}
match format {
Format::Json => format!(
"{{\"hookSpecificOutput\":{{\"hookEventName\":\"PreToolUse\",\"additionalContext\":\"{}\"}}}}",
escape_json(&text)
),
Format::Text => text,
Format::Silent => String::new(),
}
}
pub fn with_notice(out: String, format: &Format, notice: &str) -> String {
match format {
Format::Json if out.is_empty() => format!("{{\"systemMessage\":\"{}\"}}", escape_json(notice)),
Format::Json => match out.strip_prefix('{') {
Some(rest) => format!("{{\"systemMessage\":\"{}\",{rest}", escape_json(notice)),
None => out,
},
Format::Text if out.is_empty() => notice.to_string(),
Format::Text => format!("{notice}\n{out}"),
Format::Silent => out,
}
}
pub fn run(a: &Args) {
let mut input = String::new();
if std::io::stdin().take(1 << 20).read_to_string(&mut input).is_err() {
return;
}
let Ok(path) = store_path(a) else { return };
let Some(mut event) = parse(&input) else { return };
match a.opt("format") {
Some("text") => event.format = Format::Text,
Some("json") => event.format = Format::Json,
_ => {}
}
let explicit = a.opt("store").is_some() || std::env::var_os("INSTINCT_STORE").is_some_and(|v| !v.is_empty());
let seeded = super::starter::seed_first_run(&path, explicit);
if event.format == Format::Silent {
return;
}
super::team::set_cwd(event.cwd.as_deref());
let scope = eligibility::prompt_scope(a.opt("project"), event.cwd.as_deref());
let note = super::speed::before(&path, &input);
let timer = meter::start(&path, "guard");
let sid = event.session.as_deref();
let seen = sid.map(|s| session::seen(&path, s).lesson_ids()).unwrap_or_default();
let recalled = match super::starter::guard_pick(&path, &event.situation, &scope, &seen) {
Some(d) => Ok(vec![d]),
None => recall_methods(&path, &event.situation, 41 + seen.len().min(10), &scope).map(|mut m| {
m.retain(|d| !super::starter::has_cmd(d));
m
}),
};
{
let mut methods = recalled.unwrap_or_default();
methods.retain(|d| !seen.contains(&d.id));
methods.truncate(1);
if let Some(s) = sid {
methods.retain(|d| session::claim_lesson(&path, s, &d.id, session::Source::Guard));
}
let (lesson, ids) = render_recall(&methods);
let out = if lesson.trim().is_empty() && note.is_none() {
String::new()
} else {
render_with(&lesson, note.as_deref(), &event.format)
};
if let Some(t) = timer {
t.finish(if out.is_empty() { 0 } else { ids.len() }, out.len());
}
let mut said: Vec<String> = Vec::new();
if let (Format::Json, false, Some(d)) = (&event.format, out.is_empty(), methods.first()) {
let title = d.title.split_whitespace().collect::<Vec<_>>().join(" ");
said.push(format!("Instinct tripwire: {title} (advisory, nothing was blocked)"));
}
if let (Format::Json, Some(n)) = (&event.format, ¬e) {
said.push(n.clone());
}
if let Some(n) = seeded {
said.push(super::starter::first_run_notice(n));
}
let out = if said.is_empty() { out } else { with_notice(out, &event.format, &said.join("\n")) };
if !out.is_empty() {
println!("{out}");
}
}
}