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