1use std::collections::BTreeMap;
13
14use serde_json::{Value, json};
15
16use super::portable::MatcherGroup;
17use super::render::{self, Output, Rendered, Skip};
18use super::targets::{self, Profile};
19use super::typescript::{GroupRules, surviving_groups};
20use super::{HOOK_DIR_TOKEN, Tokens};
21use crate::harness::HarnessId;
22
23pub const DATA_VERSION: u64 = 1;
29
30pub const RUNNER_HARNESS: &str = "agy";
32
33pub const BLOCKING: &[&str] = &["PreToolUse", "UserPromptSubmit", "Stop"];
36
37#[derive(Debug, PartialEq, Eq)]
39struct Mapping {
40 agy: &'static str,
41 claude: &'static [&'static str],
42}
43
44#[derive(Debug, PartialEq, Eq)]
47pub struct Translation {
48 events: &'static [Mapping],
49 unsupported_events: &'static [(&'static str, &'static str)],
50 answer_limits: &'static [(&'static str, &'static str)],
52}
53
54pub(super) const AGY: Translation = Translation {
55 events: &[
56 Mapping {
57 agy: "PreToolUse",
58 claude: &["PreToolUse"],
59 },
60 Mapping {
61 agy: "PostToolUse",
62 claude: &["PostToolUse", "PostToolUseFailure"],
63 },
64 Mapping {
65 agy: "SessionStart",
66 claude: &["SessionStart"],
67 },
68 Mapping {
69 agy: "Stop",
70 claude: &["Stop"],
71 },
72 Mapping {
73 agy: "PreInvocation",
74 claude: &["UserPromptSubmit"],
75 },
76 ],
77 unsupported_events: &[
78 (
79 "SessionEnd",
80 "agy has no session-end event (its Stop fires at the end of each turn)",
81 ),
82 (
83 "PermissionRequest",
84 "agy has no permission hook: a PreToolUse `ask` answer is its only way to prompt",
85 ),
86 ],
87 answer_limits: &[
88 (
89 "PreToolUse",
90 "an `additionalContext` answer is dropped, and `updatedInput` replaces top-level keys only (a deleted key cannot be expressed)",
91 ),
92 (
93 "PostToolUse",
94 "agy passes no tool output and reads no answer from the hook: `block` and context answers are dropped",
95 ),
96 (
97 "PostToolUseFailure",
98 "agy passes no tool output and reads no answer from the hook: `block` and context answers are dropped",
99 ),
100 (
101 "SessionStart",
102 "agy fires it once per conversation and not on resume, so a `source` matcher only ever sees `startup`",
103 ),
104 (
105 "UserPromptSubmit",
106 "agy has no prompt event: the hook runs on its PreInvocation event when that is the first of a user prompt, which recurred at each prompt and only there in a probe",
107 ),
108 ],
109};
110
111impl Translation {
112 fn maps(&self, claude_event: &str) -> bool {
113 self.events.iter().any(|m| m.claude.contains(&claude_event))
114 }
115
116 pub fn serves(&self, agy_event: &str) -> &'static [&'static str] {
118 self.events
119 .iter()
120 .find(|m| m.agy == agy_event)
121 .map_or(&[], |m| m.claude)
122 }
123}
124
125const TOOLS: &[(&str, &[&str])] = &[
129 ("Bash", &["run_command"]),
130 ("Read", &["read_file"]),
131 ("Write", &["write_to_file"]),
132 (
133 "Edit",
134 &[
135 "replace_file_content",
136 "multi_replace_file_content",
137 "write_to_file",
138 ],
139 ),
140 ("Glob", &["find_by_name"]),
141 ("Grep", &["grep_search"]),
142 ("WebSearch", &["search_web"]),
143];
144
145const ARGS: &[(&str, &[&str])] = &[
149 ("command", &["CommandLine"]),
150 ("file_path", &["Path", "TargetFile", "AbsolutePath"]),
151 ("content", &["CodeContent"]),
152 ("old_string", &["TargetContent"]),
153 ("new_string", &["ReplacementContent"]),
154];
155
156pub fn claude_tool(agy_tool: &str) -> Option<&'static str> {
158 TOOLS
159 .iter()
160 .find(|(_, agy)| agy.contains(&agy_tool))
161 .map(|(claude, _)| *claude)
162}
163
164pub fn agy_tools(claude_tool: &str) -> &'static [&'static str] {
166 TOOLS
167 .iter()
168 .find(|(claude, _)| *claude == claude_tool)
169 .map_or(&[], |(_, agy)| agy)
170}
171
172pub fn claude_arg(agy_arg: &str) -> Option<&'static str> {
174 ARGS.iter()
175 .find(|(_, agy)| agy.contains(&agy_arg))
176 .map(|(claude, _)| *claude)
177}
178
179pub fn agy_args(claude_arg: &str) -> &'static [&'static str] {
181 ARGS.iter()
182 .find(|(claude, _)| *claude == claude_arg)
183 .map_or(&[], |(_, agy)| agy)
184}
185
186pub fn plain_names(pattern: &str) -> Option<Vec<&str>> {
189 (!pattern.is_empty()
190 && pattern
191 .chars()
192 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | ' ' | ',' | '|' | '-')))
193 .then(|| pattern.split(['|', ',']).map(str::trim).collect::<Vec<_>>())
194}
195
196fn matcher_problem(pattern: &str) -> Option<String> {
199 if pattern.is_empty() || pattern == "*" || plain_names(pattern).is_some() {
200 return None;
201 }
202 render::regex_problem(pattern)
203 .err()
204 .map(|reason| format!("`mars hook run` cannot compile matcher `{pattern}`: {reason}"))
205}
206
207fn agy_matcher(claude_events: &[(&str, Vec<Value>)]) -> String {
211 let mut names = Vec::new();
212 for (_, groups) in claude_events {
213 for group in groups {
214 let Some(pattern) = group["matcher"]
215 .as_str()
216 .filter(|m| !m.is_empty() && *m != "*")
217 else {
218 return "*".into();
219 };
220 let Some(plain) = plain_names(pattern) else {
221 return "*".into();
222 };
223 for name in plain {
224 let tools = agy_tools(name);
225 if tools.is_empty() {
226 return "*".into();
227 }
228 names.extend(tools.iter().copied());
229 }
230 }
231 }
232 names.sort_unstable();
233 names.dedup();
234 names.join("|")
235}
236
237fn runner_timeout(claude_events: &[(&str, Vec<Value>)]) -> u64 {
241 let total: f64 = claude_events
242 .iter()
243 .flat_map(|(_, groups)| groups)
244 .flat_map(|group| group["handlers"].as_array().into_iter().flatten())
245 .filter_map(|handler| handler["timeout"].as_f64())
246 .sum();
247 total.ceil() as u64 + 1
248}
249
250fn blocks_on_failure(claude_events: &[(&str, Vec<Value>)]) -> bool {
252 claude_events
253 .iter()
254 .filter(|(event, _)| BLOCKING.contains(event))
255 .flat_map(|(_, groups)| groups)
256 .flat_map(|group| group["handlers"].as_array().into_iter().flatten())
257 .any(|handler| handler["onFailure"] == "block")
258}
259
260pub fn runner_command(
266 command: &[String],
267 agy_event: &str,
268 data: &str,
269 block: bool,
270 windows: bool,
271) -> String {
272 let (program, prefix) = command
273 .split_first()
274 .map_or(("", &[][..]), |(p, r)| (p.as_str(), r));
275 let on_failure = if block { "block" } else { "continue" };
276 let args = format!(
277 "hook run --harness {RUNNER_HARNESS} --event {agy_event} --on-failure {on_failure}"
278 );
279 if windows {
280 let data = data.replace('/', "\\");
282 let prefix: String = prefix.iter().map(|word| format!(" \"{word}\"")).collect();
283 let found = if program.contains(['\\', '/']) {
285 format!("if exist \"{program}\"")
286 } else {
287 format!("where /q \"{program}\" & if not errorlevel 1")
288 };
289 format!(
290 "{found} (\"{program}\"{prefix} {args} \"{data}\") else (exit /b {})",
291 u8::from(block)
292 )
293 } else {
294 let quote = |text: &str| format!("'{}'", text.replace('\'', r"'\''"));
295 let prefix: String = prefix
296 .iter()
297 .map(|word| format!(" {}", quote(word)))
298 .collect();
299 let found = if program.contains('/') {
302 "[ -f \"$m\" ] && [ -x \"$m\" ]"
303 } else {
304 "command -v \"$m\" >/dev/null"
305 };
306 format!(
307 "m={}; {found} || {{ echo \"mars hook: $m not found; run mars sync\" >&2; exit {}; }}; exec \"$m\"{prefix} {args} {}",
308 quote(program),
309 u8::from(block),
310 quote(data)
311 )
312 }
313}
314
315pub(super) fn render(
319 table: &[(&str, &[MatcherGroup])],
320 profile: &Profile,
321 translation: &Translation,
322 tokens: &Tokens<'_>,
323 windows: bool,
324) -> Rendered {
325 let mut skips = Vec::new();
326 let mut answer_limits = Vec::new();
327 let mut skip = |event: &str, reason: String| {
328 skips.push(Skip {
329 event: Some(event.to_owned()),
330 reason,
331 })
332 };
333 let deferred = Tokens {
334 hook_dir: HOOK_DIR_TOKEN,
335 ..*tokens
336 };
337 for &(event, _) in table {
338 if !translation.maps(event) {
339 let reason = translation
340 .unsupported_events
341 .iter()
342 .find(|(name, _)| *name == event)
343 .map_or_else(
344 || format!("{} has no such event", HarnessId::Agy.display_name()),
345 |(_, reason)| (*reason).to_owned(),
346 );
347 skip(event, reason);
348 }
349 }
350 let mut entries = BTreeMap::new();
351 let mut serves = serde_json::Map::new();
352 let mut by_claude = serde_json::Map::new();
353 for mapping in translation.events {
354 let row = profile
355 .event(mapping.agy)
356 .expect("every mapped agy event has a row");
357 let mut kept: Vec<(&str, Vec<Value>)> = Vec::new();
358 for &claude_name in mapping.claude {
359 let Some((_, groups)) = table.iter().find(|(event, _)| *event == claude_name) else {
360 continue;
361 };
362 let claude = targets::claude_event(claude_name).expect("Claude's event");
363 let groups = surviving_groups(
364 claude_name,
365 groups,
366 claude,
367 &GroupRules {
368 harness_name: HarnessId::Agy.display_name(),
369 supplies_matcher: row.matcher.is_some(),
370 tokens: &deferred,
371 matcher_problem: &matcher_problem,
372 },
373 &mut skip,
374 );
375 if groups.is_empty() {
376 continue;
377 }
378 if let Some((_, limit)) = translation
379 .answer_limits
380 .iter()
381 .find(|(name, _)| *name == claude_name)
382 {
383 answer_limits.push(Skip {
384 event: Some(claude_name.to_owned()),
385 reason: (*limit).to_owned(),
386 });
387 }
388 kept.push((claude_name, groups));
389 }
390 if kept.is_empty() {
391 continue;
392 }
393 let command = runner_command(
394 tokens.mars_command,
395 mapping.agy,
396 tokens.generated_file,
397 blocks_on_failure(&kept),
398 windows,
399 );
400 let handler = json!({
401 "type": "command",
402 "command": command,
403 "timeout": runner_timeout(&kept),
404 });
405 let entry = if row.is_tool_event() {
406 json!({"matcher": agy_matcher(&kept), "hooks": [handler]})
407 } else {
408 handler
409 };
410 entries.insert(
411 mapping.agy.to_owned(),
412 vec![serde_json::from_value(entry).expect("a JSON value is an ordered value")],
413 );
414 serves.insert(
415 mapping.agy.to_owned(),
416 kept.iter().map(|(event, _)| *event).collect(),
417 );
418 for (claude_name, groups) in kept {
419 by_claude.insert(claude_name.to_owned(), Value::Array(groups));
420 }
421 }
422 let data_file = (!entries.is_empty()).then(|| {
423 let data = json!({
424 "version": DATA_VERSION,
425 "name": tokens.hook_name,
426 "dir": tokens.hook_dir,
427 "verified": profile.verified_against,
428 "serves": serves,
429 "events": by_claude,
430 });
431 serde_json::to_string_pretty(&data).expect("a JSON value serializes") + "\n"
432 });
433 Rendered {
434 output: Output::Keyed {
435 events: entries,
436 data_file,
437 },
438 skips,
439 answer_limits,
440 }
441}
442
443#[cfg(test)]
444mod tests {
445 use super::*;
446 use crate::HarnessId;
447 use crate::tool_natives::lookup;
448
449 #[test]
452 fn every_agy_tool_is_in_the_native_tool_table() {
453 let known: Vec<&str> = crate::tool_names::canonical_capabilities()
454 .filter_map(|capability| lookup(capability, HarnessId::Agy))
455 .flat_map(|native| native.native_tools().iter().copied())
456 .collect();
457 for (claude, tools) in TOOLS {
458 for tool in *tools {
459 assert!(
460 known.contains(tool),
461 "{claude}: `{tool}` is not an agy tool"
462 );
463 }
464 }
465 }
466}