#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct Request {
pub(crate) tool: String,
pub(crate) path: Option<String>,
pub(crate) cwd: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Decision {
Allow,
Deny,
}
impl Decision {
fn label(self) -> &'static str {
match self {
Self::Allow => "allow",
Self::Deny => "deny",
}
}
}
#[must_use]
pub(crate) fn request(stdin: &str) -> Request {
Request {
tool: string_field(stdin, "tool_name").unwrap_or_default(),
path: string_field(stdin, "file_path"),
cwd: string_field(stdin, "cwd"),
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct StatusLine {
pub(crate) transcript: Option<String>,
pub(crate) cwd: Option<String>,
pub(crate) model: Option<String>,
}
#[must_use]
pub(crate) fn statusline(stdin: &str) -> StatusLine {
StatusLine {
transcript: string_field(stdin, "transcript_path"),
cwd: string_field(stdin, "cwd"),
model: nested_string_field(stdin, "model", "id"),
}
}
fn nested_string_field(text: &str, outer: &str, inner: &str) -> Option<String> {
let at = text.find(&format!("\"{outer}\":"))?;
let tail = text.get(at..)?;
let open = tail.find('{')?;
let body = tail.get(open..)?;
let end = body.find('}')?;
string_field(body.get(..end)?, inner)
}
fn string_field(text: &str, key: &str) -> Option<String> {
let at = text.find(&format!("\"{key}\":"))?;
let tail = text.get(at.checked_add(key.len().checked_add(3)?)?..)?;
let inner = tail.trim_start().strip_prefix('"')?;
let end = inner.find('"')?;
inner.get(..end).map(str::to_owned)
}
#[must_use]
pub(crate) fn response(d: Decision, why: &str) -> String {
let msg = if why.is_empty() {
String::new()
} else {
format!(",\"systemMessage\":\"{}\"", crate::json::escape(why))
};
format!(
"{{\"hookSpecificOutput\":{{\"permissionDecision\":\"{}\"}}{msg}}}\n",
d.label()
)
}
#[cfg(test)]
mod tests {
use super::*;
const PAYLOAD: &str = r#"{"session_id":"s1","transcript_path":"/t.jsonl",
"cwd":"/repo","permission_mode":"ask","hook_event_name":"PreToolUse",
"tool_name":"Read","tool_input":{"file_path":"/repo/big.rs"}}"#;
#[test]
fn a_statusline_payload_names_its_transcript() {
let text = r#"{"hook_event_name":"Status","session_id":"s1",
"transcript_path":"/p/s1.jsonl","cwd":"/repo",
"model":{"id":"claude","display_name":"Opus"},
"workspace":{"current_dir":"/repo"}}"#;
assert_eq!(
statusline(text),
StatusLine {
transcript: Some("/p/s1.jsonl".to_owned()),
cwd: Some("/repo".to_owned()),
model: Some("claude".to_owned()),
}
);
}
#[test]
fn a_statusline_payload_without_a_model_names_none() {
let got = statusline(r#"{"transcript_path":"/p/s1.jsonl"}"#);
assert_eq!(got.model, None);
}
#[test]
fn a_model_without_an_id_does_not_borrow_a_later_one() {
let text = r#"{"model":{"display_name":"Opus"},
"workspace":{"id":"not-a-model"}}"#;
assert_eq!(statusline(text).model, None);
}
#[test]
fn a_statusline_payload_missing_the_transcript_is_none() {
let got = statusline(r#"{"session_id":"s1","cwd":"/repo"}"#);
assert_eq!(got.transcript, None);
assert_eq!(got.cwd, Some("/repo".to_owned()));
}
#[test]
fn a_pretooluse_payload_maps_to_a_request() {
assert_eq!(
request(PAYLOAD),
Request {
tool: "Read".to_owned(),
path: Some("/repo/big.rs".to_owned()),
cwd: Some("/repo".to_owned()),
}
);
}
#[test]
fn a_call_without_a_file_has_no_path() {
let bash = r#"{"tool_name":"Bash","cwd":"/repo",
"tool_input":{"command":"ls -la"}}"#;
let got = request(bash);
assert_eq!(got.tool, "Bash");
assert_eq!(got.path, None, "no file named, so none reported");
}
#[test]
fn an_unknown_field_is_ignored() {
let extra = r#"{"tool_name":"Read","brand_new_field":"whatever",
"tool_input":{"file_path":"a.rs"}}"#;
assert_eq!(request(extra).path, Some("a.rs".to_owned()));
}
#[test]
fn every_decision_renders_in_the_json() {
for (d, word) in [(Decision::Allow, "allow"), (Decision::Deny, "deny")]
{
let out = response(d, "");
assert!(
out.contains(&format!("\"permissionDecision\":\"{word}\""))
);
}
}
#[test]
fn a_reason_appears_only_when_there_is_one() {
assert!(!response(Decision::Allow, "").contains("systemMessage"));
let out = response(Decision::Deny, "over \"budget\"");
assert!(out.contains("systemMessage"), "{out}");
assert!(out.contains(r#"over \"budget\""#), "escaped: {out}");
}
#[test]
fn the_response_is_one_line() {
let out = response(Decision::Deny, "a reason");
assert_eq!(out.lines().count(), 1, "{out}");
assert!(out.ends_with('\n'));
}
}